package de.fojadrachi.playtube import org.json.JSONObject import java.io.BufferedReader import java.io.BufferedWriter import java.io.Closeable import java.io.IOException import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetAddress import java.net.InetSocketAddress import java.net.Socket import java.net.SocketTimeoutException /** * Steuerung von Playtube auf dem PC im selben WLAN (wie "Spotify Connect"). Gegenstueck am PC: * playtube/lan_remote.py. Protokoll: eine JSON-Nachricht pro Zeile ueber TCP (Port 47811); den PC * findet die App per UDP-Broadcast "PLAYTUBE_DISCOVER" an Port 47812. */ data class PcDevice(val name: String, val host: String, val port: Int = PcRemote.DEFAULT_PORT) /** Was auf dem PC gerade laeuft (aus der "status"-Antwort, Zeiten in Sekunden). */ data class PcState( val activeTab: String, val visibleTab: String, val title: String, val subtitle: String, val thumbnail: String, val playing: Boolean, val position: Double, val duration: Double, val volume: Int, val liked: Boolean, ) { companion object { val EMPTY = PcState("music", "music", "", "", "", false, 0.0, 0.0, 100, false) } } object PcRemote { const val DEFAULT_PORT = 47811 const val DISCOVERY_PORT = 47812 private const val DISCOVERY_REQUEST = "PLAYTUBE_DISCOVER" private const val CONNECT_TIMEOUT_MS = 4_000 private const val READ_TIMEOUT_MS = 6_000 /** Antwort eines PCs auf die Suche -> Geraet, oder null wenn es kein Playtube ist. */ fun parseDiscoveryReply(text: String, host: String): PcDevice? { val json = try { JSONObject(text) } catch (_: Exception) { return null } if (json.optString("service") != "playtube") return null val port = json.optInt("port", DEFAULT_PORT).takeIf { it in 1..65535 } ?: return null val name = json.optString("name").trim().take(60).ifBlank { host } return PcDevice(name, host, port) } /** "status"-Antwort -> [PcState]; null, wenn die Antwort keinen Stand enthaelt. */ fun parseState(reply: JSONObject): PcState? { val state = reply.optJSONObject("state") ?: return null val activeTab = state.optString("activeTab", "music") val tab = state.optJSONObject("tabs")?.optJSONObject(activeTab) return PcState( activeTab = activeTab, visibleTab = state.optString("visibleTab", activeTab), title = tab.text("title"), subtitle = tab.text("subtitle"), thumbnail = largeCover(tab.text("thumbnail").takeIf { it.startsWith("https://") }.orEmpty()), playing = tab?.optBoolean("playing") ?: false, position = tab?.optDouble("currentTime")?.takeIf { it.isFinite() } ?: 0.0, duration = tab?.optDouble("duration")?.takeIf { it.isFinite() } ?: 0.0, volume = (tab?.optDouble("volume")?.takeIf { it.isFinite() } ?: 100.0).toInt().coerceIn(0, 100), liked = tab?.optString("likeStatus").equals("LIKE", ignoreCase = true), ) } private val GOOGLE_IMAGE_SIZE = Regex("=(w\\d+-h\\d+|s\\d+)[^/=]*$") private val YTIMG_SMALL = Regex("/(default|mqdefault)\\.jpg$") /** * Das Cover aus der YouTube-Music-Player-Leiste ist nur 60x60 Pixel gross ("=w60-h60-l90-rj") - * fuer die Fernbedienung in 544x544 anfordern; kleine YouTube-Vorschaubilder durch hqdefault ersetzen. */ fun largeCover(url: String): String = when { url.contains("googleusercontent.com") || url.contains("ggpht.com") -> url.replace(GOOGLE_IMAGE_SIZE, "=w544-h544-l90-rj") url.contains("ytimg.com") -> url.replace(YTIMG_SMALL, "/hqdefault.jpg") else -> url } /** Textfeld ohne JSON-null ("null" als Text waere sonst sichtbar). */ private fun JSONObject?.text(key: String): String = if (this == null || isNull(key)) "" else optString(key) /** Sekunden -> "m:ss" bzw. "h:mm:ss". */ fun formatTime(seconds: Double): String { val total = seconds.coerceAtLeast(0.0).toLong() val h = total / 3600 val m = (total % 3600) / 60 val s = total % 60 return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s) } /** * Sucht Playtube-PCs im WLAN (blockiert bis [timeoutMs] - nicht auf dem Hauptthread aufrufen). * Mehrere Antworten desselben PCs werden zusammengefasst. */ fun discover(timeoutMs: Int = 1500): List { val found = LinkedHashMap() try { DatagramSocket().use { socket -> socket.broadcast = true socket.soTimeout = 300 val request = DISCOVERY_REQUEST.toByteArray() val broadcast = InetAddress.getByName("255.255.255.255") socket.send(DatagramPacket(request, request.size, broadcast, DISCOVERY_PORT)) val deadline = System.currentTimeMillis() + timeoutMs val buffer = ByteArray(1024) while (System.currentTimeMillis() < deadline) { val packet = DatagramPacket(buffer, buffer.size) try { socket.receive(packet) } catch (_: SocketTimeoutException) { continue } val host = packet.address.hostAddress ?: continue val text = String(packet.data, 0, packet.length, Charsets.UTF_8) parseDiscoveryReply(text, host)?.let { found["${it.host}:${it.port}"] = it } } } } catch (_: IOException) { // Kein WLAN o.ae. -> leere Liste; die IP-Adresse laesst sich von Hand eingeben. } return found.values.toList() } /** Fehlermeldung des PCs (z.B. "Falscher Code"). */ class RemoteException(message: String) : IOException(message) /** Eine offene Verbindung zum PC. Alle Aufrufe blockieren - nur auf einem Hintergrundthread nutzen. */ class Connection private constructor(private val socket: Socket) : Closeable { private val reader: BufferedReader = socket.getInputStream().bufferedReader(Charsets.UTF_8) private val writer: BufferedWriter = socket.getOutputStream().bufferedWriter(Charsets.UTF_8) private var nextId = 1 /** Schickt eine Anfrage und wartet auf die Antwort mit derselben id. */ fun request(command: String, fill: JSONObject.() -> Unit = {}): JSONObject { val id = nextId++ val message = JSONObject().put("id", id).put("cmd", command).apply(fill) writer.write(message.toString()) writer.write("\n") writer.flush() while (true) { val line = reader.readLine() ?: throw IOException("Verbindung getrennt") val reply = try { JSONObject(line) } catch (_: Exception) { continue } if (reply.optInt("id", -1) != id) continue if (!reply.optBoolean("ok")) throw RemoteException(reply.optString("error", "Fehler")) return reply } } override fun close() { try { socket.close() } catch (_: IOException) { } } companion object { fun open(device: PcDevice): Connection { val socket = Socket() try { socket.connect(InetSocketAddress(device.host, device.port), CONNECT_TIMEOUT_MS) socket.soTimeout = READ_TIMEOUT_MS socket.tcpNoDelay = true } catch (e: IOException) { socket.close() throw e } return Connection(socket) } } } }