diff --git a/README.md b/README.md index 58af890..37de292 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # 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. - **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 braucht die installierte Discord-App auf demselben Handy; es wird nichts angemeldet, und es 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. - **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. 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 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 | | `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) | +| `PcRemote.kt`, `PcRemoteActivity.kt` | „PC steuern“: PCs im WLAN finden, koppeln, Fernbedienung | ## Bekannte Grenzen diff --git a/app/build.gradle.kts b/app/build.gradle.kts index d0efae0..3f0bfa9 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -19,8 +19,8 @@ android { applicationId = "de.fojadrachi.playtube" minSdk = 26 targetSdk = 36 - versionCode = 3 - versionName = "1.1.1" + versionCode = 4 + versionName = "1.2.0" // Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play). buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"") diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 753b835..68df4ea 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -35,6 +35,10 @@ + + @@ -44,6 +48,14 @@ + + + (R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) } configureWebView() onBackPressedDispatcher.addCallback( diff --git a/app/src/main/java/de/fojadrachi/playtube/PcRemote.kt b/app/src/main/java/de/fojadrachi/playtube/PcRemote.kt new file mode 100644 index 0000000..72241dd --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/PcRemote.kt @@ -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 { + 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) + } + } + } +} diff --git a/app/src/main/java/de/fojadrachi/playtube/PcRemoteActivity.kt b/app/src/main/java/de/fojadrachi/playtube/PcRemoteActivity.kt new file mode 100644 index 0000000..004c3a2 --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/PcRemoteActivity.kt @@ -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() + + private lateinit var status: TextView + private lateinit var devicePanel: View + private lateinit var playerPanel: View + private lateinit var deviceAdapter: ArrayAdapter + 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(R.id.deviceList).apply { + adapter = deviceAdapter + setOnItemClickListener { _, _, position, _ -> devices.getOrNull(position)?.let(::connect) } + } + findViewById