241 lines
10 KiB
Kotlin
241 lines
10 KiB
Kotlin
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). */
|
|
/** Ein Titel der Warteschlange am PC. */
|
|
data class QueueItem(val title: String, val subtitle: String, val thumbnail: String, val current: Boolean)
|
|
|
|
/** Eine Playlist der YouTube-Music-Bibliothek am PC. */
|
|
data class PcPlaylist(val id: String, val title: String)
|
|
|
|
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,
|
|
/** "NONE", "ALL" oder "ONE" (leer = unbekannt). */
|
|
val repeatMode: String = "",
|
|
/** Schlaf-Timer am PC: Restsekunden, -1 = Songende, null = aus (oder Playtube zu alt). */
|
|
val sleepTimer: Long? = null,
|
|
) {
|
|
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),
|
|
repeatMode = tab.text("repeatMode").uppercase(),
|
|
sleepTimer = if (state.isNull("sleepTimer")) null else state.optLong("sleepTimer", Long.MIN_VALUE).takeIf { it >= -1 },
|
|
)
|
|
}
|
|
|
|
/** "queue"-Antwort -> Titel (Cover in Listengroesse); Eintraege ohne JSON-Objekt werden uebersprungen. */
|
|
fun parseQueue(reply: JSONObject): List<QueueItem> {
|
|
val array = reply.optJSONArray("queue") ?: return emptyList()
|
|
val items = ArrayList<QueueItem>()
|
|
for (i in 0 until array.length()) {
|
|
val item = array.optJSONObject(i) ?: continue
|
|
// Nichts weglassen: der Index muss zur Reihenfolge am PC passen (play_queue_item).
|
|
items += QueueItem(
|
|
title = item.text("title").trim(),
|
|
subtitle = item.text("subtitle").trim(),
|
|
thumbnail = sizedCover(item.text("thumbnail").takeIf { it.startsWith("https://") }.orEmpty(), 226),
|
|
current = item.optBoolean("current"),
|
|
)
|
|
}
|
|
return items
|
|
}
|
|
|
|
/** "list_playlists"-Antwort -> Playlists. */
|
|
fun parsePlaylists(reply: JSONObject): List<PcPlaylist> {
|
|
val array = reply.optJSONArray("playlists") ?: return emptyList()
|
|
val items = ArrayList<PcPlaylist>()
|
|
for (i in 0 until array.length()) {
|
|
val item = array.optJSONObject(i) ?: continue
|
|
val id = item.text("id").trim()
|
|
if (id.isEmpty()) continue
|
|
items += PcPlaylist(id, item.text("title").trim().ifEmpty { id })
|
|
}
|
|
return items
|
|
}
|
|
|
|
/** Ein PC mit Playtube 2.0.x kennt "queue" noch nicht und antwortet mit "unbekannter Befehl". */
|
|
fun isUnknownCommand(message: String?): Boolean =
|
|
message != null && (message.contains("unbekannter Befehl", ignoreCase = true) ||
|
|
message.contains("unknown command", 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 = sizedCover(url, 544)
|
|
|
|
/** Wie [largeCover], aber in [size] x [size] Pixeln (fuer kleine Listenbilder). */
|
|
fun sizedCover(url: String, size: Int): String = when {
|
|
url.contains("googleusercontent.com") || url.contains("ggpht.com") ->
|
|
url.replace(GOOGLE_IMAGE_SIZE, "=w$size-h$size-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<PcDevice> {
|
|
val found = LinkedHashMap<String, PcDevice>()
|
|
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)
|
|
}
|
|
}
|
|
}
|
|
}
|