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
+20 -1
View File
@@ -1,6 +1,6 @@
# Playtube für Android # Playtube für Android
Android-Version von [Playtube](https://git.fojadrachi.de/Fojadrachi/Playtube) – **nur YouTube Music**, Android-Version von [Playtube](https://github.com/fojadrachi/Playtube) – **nur YouTube Music**,
mit Hintergrundwiedergabe und Discord Rich Presence. Ohne YouTube-Tab und ohne Stream-Dock-Fernsteuerung. mit Hintergrundwiedergabe und Discord Rich Presence. Ohne YouTube-Tab und ohne Stream-Dock-Fernsteuerung.
- **YouTube Music in der App** (`music.youtube.com` in einer WebView), Anmeldung mit deinem - **YouTube Music in der App** (`music.youtube.com` in einer WebView), Anmeldung mit deinem
@@ -15,6 +15,11 @@ mit Hintergrundwiedergabe und Discord Rich Presence. Ohne YouTube-Tab und ohne S
Fortschritt, solange Musik läuft (nicht bei Pause). Nutzt das offizielle Discord Social SDK und Fortschritt, solange Musik läuft (nicht bei Pause). Nutzt das offizielle Discord Social SDK und
braucht die installierte Discord-App auf demselben Handy; es wird nichts angemeldet, und es braucht die installierte Discord-App auf demselben Handy; es wird nichts angemeldet, und es
werden keine Konto-Daten an Playtube gegeben. werden keine Konto-Daten an Playtube gegeben.
- **PC steuern** (wie Spotify Connect): Playtube auf dem PC im selben WLAN fernbedienen – Titel,
Cover, Play/Pause, Vor/Zurück, Spulen, Lautstärke, Like und Wechsel zwischen YouTube und
YouTube Music. Erreichbar über den runden Knopf am rechten Rand oder durch langes Drücken aufs
App-Icon („PC steuern“). Am PC einmalig in Playtube unter *Einstellungen › Steuerung vom Handy*
einschalten und mit dem 6-stelligen Code koppeln (siehe unten).
- **Links** zu `music.youtube.com` öffnen sich in Playtube. - **Links** zu `music.youtube.com` öffnen sich in Playtube.
- **Updates** aus den eigenen Releases (Tag `vX.Y.Z-android`), kein GitHub, kein Play Store. - **Updates** aus den eigenen Releases (Tag `vX.Y.Z-android`), kein GitHub, kein Play Store.
@@ -28,6 +33,19 @@ Voraussetzungen: Android 8.0 (API 26) oder neuer, aktuelles „Android System We
(„Unbekannte Apps installieren") – erlauben. („Unbekannte Apps installieren") – erlauben.
3. Beim ersten Start Benachrichtigungen erlauben (für die Steuerung auf dem Sperrbildschirm). 3. Beim ersten Start Benachrichtigungen erlauben (für die Steuerung auf dem Sperrbildschirm).
### PC steuern einrichten
1. Am PC in Playtube (ab Version 2.0.0) *Einstellungen › Steuerung vom Handy* einschalten und
speichern. Windows fragt einmalig nach der Firewall – für **private Netzwerke** erlauben.
2. Am Handy auf den runden Knopf am rechten Rand tippen. Die App sucht Playtube-PCs im WLAN
(UDP-Broadcast an Port 47812); wird keiner gefunden, die am PC angezeigte IP-Adresse eingeben.
3. Am PC „Handy koppeln“ wählen und den 6-stelligen Code am Handy eingeben. Danach verbindet sich
die App mit diesem PC ohne Code.
Verbindung: TCP-Port 47811 im lokalen Netz, unverschlüsselt (wie im Heimnetz üblich); der PC nimmt
nur Geräte aus privaten Netzen an und nur nach Kopplung. Das Gegenstück am PC ist
`playtube/lan_remote.py`.
Bei Akku-Optimierung des Herstellers (Xiaomi, Samsung, …) Playtube dort von der Optimierung Bei Akku-Optimierung des Herstellers (Xiaomi, Samsung, …) Playtube dort von der Optimierung
ausnehmen, sonst beendet Android die Hintergrundwiedergabe manchmal. ausnehmen, sonst beendet Android die Hintergrundwiedergabe manchmal.
@@ -90,6 +108,7 @@ von Playtube fragen ein anderes Repo ab und sehen sie nie.
| `UpdateChecker.kt` | Update-Prüfung über die Gitea-Releases | | `UpdateChecker.kt` | Update-Prüfung über die Gitea-Releases |
| `DiscordPresence.kt`, `PresencePlan.kt`, `cpp/` | Discord Rich Presence: was angezeigt wird, und die Brücke zum SDK | | `DiscordPresence.kt`, `PresencePlan.kt`, `cpp/` | Discord Rich Presence: was angezeigt wird, und die Brücke zum SDK |
| `UserAgent.kt` | macht die WebView-Kennung zu einer normalen Chrome-Kennung (Google-Anmeldung) | | `UserAgent.kt` | macht die WebView-Kennung zu einer normalen Chrome-Kennung (Google-Anmeldung) |
| `PcRemote.kt`, `PcRemoteActivity.kt` | „PC steuern“: PCs im WLAN finden, koppeln, Fernbedienung |
## Bekannte Grenzen ## Bekannte Grenzen
+2 -2
View File
@@ -19,8 +19,8 @@ android {
applicationId = "de.fojadrachi.playtube" applicationId = "de.fojadrachi.playtube"
minSdk = 26 minSdk = 26
targetSdk = 36 targetSdk = 36
versionCode = 3 versionCode = 4
versionName = "1.1.1" versionName = "1.2.0"
// Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play). // Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play).
buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"") buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"")
+12
View File
@@ -35,6 +35,10 @@
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
<!-- Langes Druecken aufs App-Icon: "PC steuern". -->
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
<!-- Geteilte/angetippte YouTube-Music-Links oeffnen sich in Playtube. --> <!-- Geteilte/angetippte YouTube-Music-Links oeffnen sich in Playtube. -->
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
@@ -44,6 +48,14 @@
</intent-filter> </intent-filter>
</activity> </activity>
<!-- Playtube auf dem PC im selben WLAN steuern (PcRemote.kt). -->
<activity
android:name=".PcRemoteActivity"
android:exported="false"
android:label="@string/pc_title"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
android:windowSoftInputMode="adjustResize" />
<service <service
android:name=".PlaybackService" android:name=".PlaybackService"
android:exported="false" android:exported="false"
@@ -52,6 +52,7 @@ class MainActivity : AppCompatActivity() {
webView = findViewById(R.id.webView) webView = findViewById(R.id.webView)
progress = findViewById(R.id.progress) progress = findViewById(R.id.progress)
keepContentBetweenSystemBars() keepContentBetweenSystemBars()
findViewById<View>(R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) }
configureWebView() configureWebView()
onBackPressedDispatcher.addCallback( 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))
}
}
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<gradient
android:angle="135"
android:endColor="@color/brand_to"
android:startColor="@color/brand_from" />
</shape>
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Daumen hoch (Material "thumb_up"). Farbe setzt PcRemoteActivity je nach Like-Status. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M1,21h4L5,9L1,9v12zM23,10c0,-1.1 -0.9,-2 -2,-2h-6.31l0.95,-4.57 0.03,-0.32c0,-0.41 -0.17,-0.79 -0.44,-1.06L14.17,1 7.59,7.59C7.22,7.95 7,8.45 7,9v10c0,1.1 0.9,2 2,2h9c0.83,0 1.54,-0.5 1.84,-1.22l3.02,-7.05c0.09,-0.23 0.14,-0.47 0.14,-0.73v-2z" />
</vector>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Bildschirm mit Wellen (Material "cast"): "Auf dem PC steuern". -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M21,3L3,3c-1.1,0 -2,0.9 -2,2v3h2L3,5h18v14h-7v2h7c1.1,0 2,-0.9 2,-2L23,5c0,-1.1 -0.9,-2 -2,-2zM1,18v3h3c0,-1.66 -1.34,-3 -3,-3zM1,14v2c2.76,0 5,2.24 5,5h2c0,-3.87 -3.13,-7 -7,-7zM1,10v2c4.97,0 9,4.03 9,9h2c0,-6.08 -4.93,-11 -11,-11z" />
</vector>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Icon der Verknuepfung "PC steuern": weisses Symbol auf dem Playtube-Verlauf. -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_play_button" />
<item
android:bottom="12dp"
android:drawable="@drawable/ic_pc_remote"
android:left="12dp"
android:right="12dp"
android:top="12dp" />
</layer-list>
+15
View File
@@ -19,4 +19,19 @@
android:max="100" android:max="100"
android:progressTint="@color/brand_to" android:progressTint="@color/brand_to"
android:visibility="gone" /> android:visibility="gone" />
<!-- "PC steuern" (PcRemoteActivity). Am rechten Rand mittig: dort liegen bei YouTube Music
keine festen Bedienelemente (oben Kopfzeile, unten Player und Navigation). -->
<ImageButton
android:id="@+id/pcRemoteButton"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_gravity="end|center_vertical"
android:layout_marginEnd="6dp"
android:alpha="0.85"
android:background="@drawable/bg_play_button"
android:contentDescription="@string/pc_open"
android:padding="10dp"
android:scaleType="fitCenter"
android:src="@drawable/ic_pc_remote" />
</FrameLayout> </FrameLayout>
@@ -0,0 +1,244 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/remoteRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:id="@+id/remoteHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pc_title"
android:textColor="@color/text"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="@+id/remoteStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="@color/text_muted"
android:textSize="14sp" />
<!-- Geraeteliste: PCs im WLAN -->
<LinearLayout
android:id="@+id/devicePanel"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:orientation="vertical">
<ListView
android:id="@+id/deviceList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="@color/surface"
android:dividerHeight="1dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="@string/pc_hint"
android:textColor="@color/text_muted"
android:textSize="13sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:orientation="horizontal">
<Button
android:id="@+id/searchButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/pc_search" />
<Button
android:id="@+id/manualButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="@string/pc_manual" />
</LinearLayout>
</LinearLayout>
<!-- Fernbedienung fuer den verbundenen PC -->
<LinearLayout
android:id="@+id/playerPanel"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical"
android:visibility="gone">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/tabYoutube"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="YouTube" />
<Button
android:id="@+id/tabMusic"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="YouTube Music" />
</LinearLayout>
<ImageView
android:id="@+id/cover"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:contentDescription="@string/pc_cover"
android:scaleType="fitCenter" />
<TextView
android:id="@+id/trackTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ellipsize="end"
android:maxLines="2"
android:textColor="@color/text"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/trackSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/text_muted"
android:textSize="15sp" />
<SeekBar
android:id="@+id/positionBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:progressTint="@color/brand_to"
android:thumbTint="@color/brand_to" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/positionText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="@color/text_muted"
android:textSize="12sp" />
<TextView
android:id="@+id/durationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/text_muted"
android:textSize="12sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="@+id/likeButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/pc_like"
android:src="@drawable/ic_like" />
<ImageButton
android:id="@+id/previousButton"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_marginStart="12dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/action_previous"
android:src="@android:drawable/ic_media_previous" />
<ImageButton
android:id="@+id/playPauseButton"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:background="@drawable/bg_play_button"
android:contentDescription="@string/action_play"
android:src="@android:drawable/ic_media_play" />
<ImageButton
android:id="@+id/nextButton"
android:layout_width="56dp"
android:layout_height="56dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/action_next"
android:src="@android:drawable/ic_media_next" />
<View
android:layout_width="60dp"
android:layout_height="1dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:contentDescription="@string/pc_volume"
android:src="@android:drawable/ic_lock_silent_mode_off"
android:tint="@color/text_muted" />
<SeekBar
android:id="@+id/volumeBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:max="100"
android:progressTint="@color/brand_from"
android:thumbTint="@color/brand_from" />
</LinearLayout>
<Button
android:id="@+id/disconnectButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/pc_disconnect" />
</LinearLayout>
</LinearLayout>
+30
View File
@@ -13,7 +13,37 @@
<string name="update_download">Herunterladen</string> <string name="update_download">Herunterladen</string>
<string name="update_later">Später</string> <string name="update_later">Später</string>
<!-- PC steuern (PcRemoteActivity) -->
<string name="pc_title">PC steuern</string>
<string name="pc_shortcut">PC steuern</string>
<string name="pc_open">Playtube auf dem PC steuern</string>
<string name="pc_searching">Suche Playtube-PCs im WLAN …</string>
<string name="pc_found">Tippe auf einen PC, um ihn zu steuern.</string>
<string name="pc_none_found">Kein PC gefunden.</string>
<string name="pc_hint">Am PC in Playtube unter Einstellungen › „Steuerung vom Handy“ einschalten. Handy und PC müssen im selben WLAN sein.</string>
<string name="pc_search">Erneut suchen</string>
<string name="pc_manual">IP-Adresse eingeben</string>
<string name="pc_manual_hint">z. B. 192.168.178.20</string>
<string name="pc_connect">Verbinden</string>
<string name="pc_cancel">Abbrechen</string>
<string name="pc_pair_title">Mit %1$s koppeln</string>
<string name="pc_pair_message">Am PC in Playtube unter Einstellungen › „Steuerung vom Handy“ auf „Handy koppeln“ tippen und den 6-stelligen Code hier eingeben.</string>
<string name="pc_pair_hint">Code</string>
<string name="pc_pair">Koppeln</string>
<string name="pc_connecting">Verbinde mit %1$s …</string>
<string name="pc_connected">Verbunden mit %1$s</string>
<string name="pc_error">Verbindung fehlgeschlagen: %1$s</string>
<string name="pc_lost">Verbindung zu %1$s verloren.</string>
<string name="pc_nothing_playing">Gerade läuft nichts</string>
<string name="pc_disconnect">Trennen</string>
<string name="pc_cover">Cover</string>
<string name="pc_like">Gefällt mir</string>
<string name="pc_volume">Lautstärke</string>
<color name="background">#0F0F0F</color> <color name="background">#0F0F0F</color>
<color name="surface">#1F1F1F</color>
<color name="text">#FFFFFF</color>
<color name="text_muted">#AAAAAA</color>
<color name="system_bars">#000000</color> <color name="system_bars">#000000</color>
<color name="brand_from">#7C3AED</color> <color name="brand_from">#7C3AED</color>
<color name="brand_to">#EC4899</color> <color name="brand_to">#EC4899</color>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_pc_remote"
android:shortcutId="pc_remote"
android:shortcutShortLabel="@string/pc_shortcut">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="de.fojadrachi.playtube.PcRemoteActivity"
android:targetPackage="de.fojadrachi.playtube" />
</shortcut>
</shortcuts>
@@ -0,0 +1,80 @@
package de.fojadrachi.playtube
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class PcRemoteTest {
@Test
fun parsesDiscoveryReply() {
val device = PcRemote.parseDiscoveryReply(
"""{"service": "playtube", "protocol": 1, "name": "MEIN-PC", "port": 47811}""",
"192.168.1.20",
)
assertEquals(PcDevice("MEIN-PC", "192.168.1.20", 47811), device)
}
@Test
fun ignoresForeignOrBrokenDiscoveryReplies() {
assertNull(PcRemote.parseDiscoveryReply("""{"service": "other", "port": 1}""", "1.2.3.4"))
assertNull(PcRemote.parseDiscoveryReply("""{"service": "playtube", "port": 70000}""", "1.2.3.4"))
assertNull(PcRemote.parseDiscoveryReply("kein json", "1.2.3.4"))
}
@Test
fun usesHostWhenNameIsMissing() {
val device = PcRemote.parseDiscoveryReply("""{"service": "playtube"}""", "10.0.0.2")
assertEquals(PcDevice("10.0.0.2", "10.0.0.2", PcRemote.DEFAULT_PORT), device)
}
@Test
fun parsesStateOfTheActiveTab() {
val reply = JSONObject(
"""
{"id": 3, "ok": true, "state": {
"protocol": 1, "visibleTab": "youtube", "activeTab": "music",
"tabs": {
"youtube": null,
"music": {"title": "Song", "subtitle": "Artist", "thumbnail": "https://i.ytimg.com/x.jpg",
"playing": true, "currentTime": 61.5, "duration": 200, "volume": 42,
"likeStatus": "LIKE"}
}}}
""".trimIndent(),
)
val state = PcRemote.parseState(reply)!!
assertEquals("music", state.activeTab)
assertEquals("youtube", state.visibleTab)
assertEquals("Song", state.title)
assertEquals("Artist", state.subtitle)
assertEquals("https://i.ytimg.com/x.jpg", state.thumbnail)
assertTrue(state.playing)
assertEquals(61.5, state.position, 0.001)
assertEquals(200.0, state.duration, 0.001)
assertEquals(42, state.volume)
assertTrue(state.liked)
}
@Test
fun handlesEmptyTabsAndNulls() {
val reply = JSONObject(
"""{"ok": true, "state": {"activeTab": "youtube", "tabs": {"youtube": {"title": null,
"thumbnail": "http://unsicher", "currentTime": null}, "music": null}}}""",
)
val state = PcRemote.parseState(reply)!!
assertEquals("", state.title)
assertEquals("", state.thumbnail)
assertEquals(0.0, state.position, 0.001)
assertFalse(state.playing)
assertNull(PcRemote.parseState(JSONObject("""{"ok": true}""")))
}
@Test
fun formatsTimes() {
assertEquals("0:00", PcRemote.formatTime(-5.0))
assertEquals("1:05", PcRemote.formatTime(65.9))
assertEquals("1:01:01", PcRemote.formatTime(3661.0))
}
}