feat: PC steuern - Playtube auf dem PC im WLAN fernbedienen (v1.2.0)

Wie Spotify Connect: PCs mit Playtube im selben WLAN finden (UDP-Broadcast
an Port 47812), einmalig mit dem 6-stelligen Code vom PC koppeln und dann
Titel, Cover, Play/Pause, Vor/Zurueck, Spulen, Lautstaerke, Like und den
Wechsel YouTube/YouTube Music steuern. Erreichbar ueber den runden Knopf
am rechten Rand oder die Verknuepfung "PC steuern" am App-Icon.
Gegenstueck am PC: Playtube 2.0.0 (src/lan.rs).

Noch nicht gebaut und nicht auf einem Geraet getestet (kein Android-SDK
auf dem Entwicklungsrechner).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-05 19:28:43 +01:00
co-authored by Claude Opus 5.5
parent e3650a6776
commit 16bdbe9128
15 changed files with 1097 additions and 3 deletions
@@ -52,6 +52,7 @@ class MainActivity : AppCompatActivity() {
webView = findViewById(R.id.webView)
progress = findViewById(R.id.progress)
keepContentBetweenSystemBars()
findViewById<View>(R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) }
configureWebView()
onBackPressedDispatcher.addCallback(
@@ -0,0 +1,176 @@
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 = 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),
)
}
/** 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)
}
}
}
}
@@ -0,0 +1,464 @@
package de.fojadrachi.playtube
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.InputFilter
import android.text.InputType
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.atomic.AtomicBoolean
/**
* "PC steuern": findet Playtube auf dem PC im selben WLAN und steuert es wie eine Fernbedienung
* (Titel, Cover, Play/Pause, Spulen, Lautstaerke, Like, YouTube/YouTube Music). Protokoll siehe
* [PcRemote]. Gekoppelte PCs merkt sich die App (Token in den App-Einstellungen).
*/
class PcRemoteActivity : AppCompatActivity() {
private val main = Handler(Looper.getMainLooper())
/** Alle Netzwerkaufrufe an den PC laufen nacheinander auf diesem Thread. */
private val worker: ExecutorService = Executors.newSingleThreadExecutor()
/** Nur auf [worker] benutzen. */
@Volatile private var connection: PcRemote.Connection? = null
private val statusPending = AtomicBoolean(false)
private var device: PcDevice? = null
private var state = PcState.EMPTY
private var coverUrl = ""
private var draggingPosition = false
private var draggingVolume = false
private val devices = mutableListOf<PcDevice>()
private lateinit var status: TextView
private lateinit var devicePanel: View
private lateinit var playerPanel: View
private lateinit var deviceAdapter: ArrayAdapter<String>
private lateinit var cover: ImageView
private lateinit var trackTitle: TextView
private lateinit var trackSubtitle: TextView
private lateinit var positionBar: SeekBar
private lateinit var positionText: TextView
private lateinit var durationText: TextView
private lateinit var playPause: ImageButton
private lateinit var like: ImageButton
private lateinit var volumeBar: SeekBar
private lateinit var tabYoutube: Button
private lateinit var tabMusic: Button
private val pollLoop = object : Runnable {
override fun run() {
requestStatus()
main.postDelayed(this, POLL_INTERVAL_MS)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pc_remote)
keepContentBetweenSystemBars()
status = findViewById(R.id.remoteStatus)
devicePanel = findViewById(R.id.devicePanel)
playerPanel = findViewById(R.id.playerPanel)
cover = findViewById(R.id.cover)
trackTitle = findViewById(R.id.trackTitle)
trackSubtitle = findViewById(R.id.trackSubtitle)
positionBar = findViewById(R.id.positionBar)
positionText = findViewById(R.id.positionText)
durationText = findViewById(R.id.durationText)
playPause = findViewById(R.id.playPauseButton)
like = findViewById(R.id.likeButton)
volumeBar = findViewById(R.id.volumeBar)
tabYoutube = findViewById(R.id.tabYoutube)
tabMusic = findViewById(R.id.tabMusic)
deviceAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, mutableListOf())
findViewById<ListView>(R.id.deviceList).apply {
adapter = deviceAdapter
setOnItemClickListener { _, _, position, _ -> devices.getOrNull(position)?.let(::connect) }
}
findViewById<Button>(R.id.searchButton).setOnClickListener { search() }
findViewById<Button>(R.id.manualButton).setOnClickListener { askForAddress() }
findViewById<Button>(R.id.disconnectButton).setOnClickListener { disconnect() }
findViewById<ImageButton>(R.id.previousButton).setOnClickListener { send("previous") }
findViewById<ImageButton>(R.id.nextButton).setOnClickListener { send("next") }
playPause.setOnClickListener {
state = state.copy(playing = !state.playing) // sofort umschalten, der naechste Status bestaetigt
render()
send("play_pause")
}
like.setOnClickListener { send("like") }
tabYoutube.setOnClickListener { send("switch_tab", target = "youtube") }
tabMusic.setOnClickListener { send("switch_tab", target = "music") }
positionBar.setOnSeekBarChangeListener(object : SeekBarListener() {
override fun onStartTrackingTouch(bar: SeekBar) {
draggingPosition = true
}
override fun onProgressChanged(bar: SeekBar, progress: Int, fromUser: Boolean) {
if (fromUser) positionText.text = PcRemote.formatTime(progress.toDouble())
}
override fun onStopTrackingTouch(bar: SeekBar) {
draggingPosition = false
// Der PC spult relativ ("seek" = Sekunden vor/zurueck).
val delta = (bar.progress - state.position).coerceIn(-3600.0, 3600.0)
state = state.copy(position = bar.progress.toDouble())
send("seek", value = delta)
}
})
volumeBar.setOnSeekBarChangeListener(object : SeekBarListener() {
override fun onStartTrackingTouch(bar: SeekBar) {
draggingVolume = true
}
override fun onStopTrackingTouch(bar: SeekBar) {
draggingVolume = false
state = state.copy(volume = bar.progress)
send("set_volume", value = bar.progress.toDouble())
}
})
search()
}
override fun onStart() {
super.onStart()
if (device != null) main.post(pollLoop)
}
override fun onStop() {
main.removeCallbacks(pollLoop)
super.onStop()
}
override fun onDestroy() {
main.removeCallbacksAndMessages(null)
onWorker { closeConnection() }
worker.shutdown()
super.onDestroy()
}
private fun keepContentBetweenSystemBars() {
val root = findViewById<View>(R.id.remoteRoot)
val base = root.paddingLeft
ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets ->
val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
view.setPadding(base + bars.left, base + bars.top, base + bars.right, base + bars.bottom)
WindowInsetsCompat.CONSUMED
}
}
// ------------------------------------------------------------------ PCs finden
private fun search() {
status.setText(R.string.pc_searching)
Thread {
val found = PcRemote.discover()
main.post {
if (isFinishing) return@post
devices.clear()
devices.addAll(found)
deviceAdapter.clear()
deviceAdapter.addAll(found.map { "${it.name}\n${it.host}" })
status.setText(if (found.isEmpty()) R.string.pc_none_found else R.string.pc_found)
}
}.start()
}
private fun askForAddress() {
val input = EditText(this).apply {
hint = getString(R.string.pc_manual_hint)
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
setText(prefs().getString(KEY_LAST_HOST, ""))
}
AlertDialog.Builder(this)
.setTitle(R.string.pc_manual)
.setView(padded(input))
.setPositiveButton(R.string.pc_connect) { _, _ ->
val host = input.text.toString().trim()
if (host.isNotEmpty()) {
connect(PcDevice(prefs().getString(KEY_NAME_FOR + host, null) ?: host, host))
}
}
.setNegativeButton(R.string.pc_cancel, null)
.show()
}
// ------------------------------------------------------------------ Verbinden / Koppeln
private fun connect(target: PcDevice) {
val token = prefs().getString(KEY_TOKEN_FOR + target.name, null)
if (token == null) {
askForCode(target)
return
}
status.text = getString(R.string.pc_connecting, target.name)
onWorker {
try {
closeConnection()
val conn = PcRemote.Connection.open(target)
val reply = try {
conn.request("hello") { put("token", token) }
} catch (e: IOException) {
conn.close()
throw e
}
connection = conn
main.post { onConnected(target, reply.optString("name")) }
} catch (e: PcRemote.RemoteException) {
// Kopplung am PC entfernt -> neu koppeln.
main.post {
prefs().edit().remove(KEY_TOKEN_FOR + target.name).apply()
askForCode(target)
}
} catch (e: IOException) {
main.post { status.text = getString(R.string.pc_error, e.message ?: e.javaClass.simpleName) }
}
}
}
private fun askForCode(target: PcDevice) {
val input = EditText(this).apply {
hint = getString(R.string.pc_pair_hint)
inputType = InputType.TYPE_CLASS_NUMBER
filters = arrayOf(InputFilter.LengthFilter(6))
}
AlertDialog.Builder(this)
.setTitle(getString(R.string.pc_pair_title, target.name))
.setMessage(R.string.pc_pair_message)
.setView(padded(input))
.setPositiveButton(R.string.pc_pair) { _, _ -> pair(target, input.text.toString().trim()) }
.setNegativeButton(R.string.pc_cancel, null)
.show()
}
private fun pair(target: PcDevice, code: String) {
status.text = getString(R.string.pc_connecting, target.name)
onWorker {
try {
closeConnection()
val conn = PcRemote.Connection.open(target)
val reply = try {
conn.request("pair") {
put("code", code)
put("device", Build.MODEL ?: "Android")
}
} catch (e: IOException) {
conn.close()
throw e
}
connection = conn
val token = reply.optString("token")
main.post {
prefs().edit().putString(KEY_TOKEN_FOR + target.name, token).apply()
onConnected(target, reply.optString("name"))
}
} catch (e: IOException) {
main.post { status.text = getString(R.string.pc_error, e.message ?: e.javaClass.simpleName) }
}
}
}
private fun onConnected(target: PcDevice, reportedName: String) {
// Der PC meldet seinen Namen - unter dem merken wir uns Token und Adresse.
val name = reportedName.ifBlank { target.name }
val token = prefs().getString(KEY_TOKEN_FOR + target.name, null)
prefs().edit().apply {
if (token != null) putString(KEY_TOKEN_FOR + name, token)
putString(KEY_NAME_FOR + target.host, name)
putString(KEY_LAST_HOST, target.host)
}.apply()
device = target.copy(name = name)
status.text = getString(R.string.pc_connected, name)
devicePanel.visibility = View.GONE
playerPanel.visibility = View.VISIBLE
main.removeCallbacks(pollLoop)
main.post(pollLoop)
}
private fun disconnect() {
main.removeCallbacks(pollLoop)
onWorker { closeConnection() }
device = null
state = PcState.EMPTY
coverUrl = ""
cover.setImageDrawable(null)
playerPanel.visibility = View.GONE
devicePanel.visibility = View.VISIBLE
search()
}
private fun onConnectionLost() {
val name = device?.name ?: return
disconnect()
status.text = getString(R.string.pc_lost, name)
}
/** Fuehrt [block] auf [worker] aus - nach dem Schliessen der Activity nicht mehr. */
private fun onWorker(block: () -> Unit) {
try {
worker.execute(block)
} catch (_: RejectedExecutionException) {
}
}
/** Nur auf [worker] aufrufen. */
private fun closeConnection() {
connection?.close()
connection = null
}
// ------------------------------------------------------------------ Befehle und Stand
private fun requestStatus() {
// Bei langsamem WLAN nicht eine Abfrage pro Sekunde aufstauen.
if (!statusPending.compareAndSet(false, true)) return
onWorker {
try {
val conn = connection ?: return@onWorker
val next = PcRemote.parseState(conn.request("status")) ?: return@onWorker
main.post {
if (device == null) return@post
state = next
render()
}
} catch (_: IOException) {
closeConnection()
main.post { onConnectionLost() }
} finally {
statusPending.set(false)
}
}
}
private fun send(command: String, target: String = "auto", value: Double? = null) {
onWorker {
val conn = connection ?: return@onWorker
try {
conn.request(command) {
put("target", target)
if (value != null) put("value", value)
}
} catch (_: PcRemote.RemoteException) {
// Befehl abgelehnt (z.B. nichts geladen) - Verbindung bleibt.
} catch (_: IOException) {
closeConnection()
main.post { onConnectionLost() }
return@onWorker
}
main.post { requestStatus() }
}
}
private fun render() {
trackTitle.text = state.title.ifBlank { getString(R.string.pc_nothing_playing) }
trackSubtitle.text = state.subtitle
playPause.setImageResource(
if (state.playing) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play,
)
playPause.contentDescription = getString(if (state.playing) R.string.action_pause else R.string.action_play)
val duration = state.duration.toInt().coerceAtLeast(0)
positionBar.max = duration
positionBar.isEnabled = duration > 0
durationText.text = PcRemote.formatTime(state.duration)
if (!draggingPosition) {
positionBar.progress = state.position.toInt().coerceIn(0, duration)
positionText.text = PcRemote.formatTime(state.position)
}
if (!draggingVolume) volumeBar.progress = state.volume
val likeColor = if (state.liked) R.color.brand_to else R.color.text_muted
like.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(this, likeColor))
tabYoutube.alpha = if (state.visibleTab == "youtube") 1f else 0.5f
tabMusic.alpha = if (state.visibleTab == "music") 1f else 0.5f
if (state.thumbnail != coverUrl) loadCover(state.thumbnail)
}
private fun loadCover(url: String) {
coverUrl = url
if (url.isEmpty()) {
cover.setImageDrawable(null)
return
}
Thread {
val bitmap = downloadBitmap(url)
main.post { if (coverUrl == url) cover.setImageBitmap(bitmap) }
}.start()
}
private fun downloadBitmap(url: String): Bitmap? =
try {
val connection = URL(url).openConnection() as HttpURLConnection
connection.connectTimeout = 8_000
connection.readTimeout = 8_000
try {
connection.inputStream.use(BitmapFactory::decodeStream)
} finally {
connection.disconnect()
}
} catch (_: Exception) {
null
}
// ------------------------------------------------------------------ Hilfen
private fun prefs() = getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun padded(view: View): View =
LinearLayout(this).apply {
val pad = (20 * resources.displayMetrics.density).toInt()
setPadding(pad, pad / 2, pad, 0)
addView(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
}
/** SeekBar-Listener mit leeren Standardmethoden. */
private open class SeekBarListener : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(bar: SeekBar, progress: Int, fromUser: Boolean) {}
override fun onStartTrackingTouch(bar: SeekBar) {}
override fun onStopTrackingTouch(bar: SeekBar) {}
}
companion object {
private const val POLL_INTERVAL_MS = 1000L
private const val PREFS = "pc_remote"
private const val KEY_TOKEN_FOR = "token:"
private const val KEY_NAME_FOR = "name:"
private const val KEY_LAST_HOST = "last_host"
fun start(context: Context) {
context.startActivity(Intent(context, PcRemoteActivity::class.java))
}
}
}