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:
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user