Compare commits

..
Author SHA1 Message Date
FojadrachiandClaude Sonnet 5.5 29d38ef2e6 feat: PC steuern im neuen Stil, Warteschlange, Playlists, dauerhafte Verbindung (1.3.0)
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-06 16:20:44 +01:00
30 changed files with 1584 additions and 342 deletions
+9 -3
View File
@@ -16,8 +16,10 @@ mit Hintergrundwiedergabe und Discord Rich Presence. Ohne YouTube-Tab und ohne S
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
Cover, Play/Pause, Vor/Zurück, Zufall/Wiederholen, Spulen, Lautstärke, Like, Wechsel zwischen
YouTube und YouTube Music, dazu **Warteschlange** und **Playlists** (Titel antippen = abspielen;
ab Playtube 2.1.0 am PC). Der Bildschirm ist im Spotify-Stil gehalten (Akzent: Playtube-Lila/Pink),
die Verbindung bleibt auch im Hintergrund bestehen (Benachrichtigung „Steuert …“ mit Trennen). 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.
@@ -42,6 +44,10 @@ Voraussetzungen: Android 8.0 (API 26) oder neuer, aktuelles „Android System We
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.
Die Verbindung hält ein Vordergrunddienst (`PcRemoteService`): Sie bleibt, wenn du den Bildschirm
verlässt, fragt dann nur alle 4 s den Stand ab und verbindet sich nach einem Abbruch bis zu 5-mal neu.
Beendet wird sie über „Trennen“ (App oder Benachrichtigung). Die Wiedergabe auf dem Handy bleibt unberührt.
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`.
@@ -108,7 +114,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 |
| `PcRemote.kt`, `PcSession.kt`, `PcRemoteService.kt`, `PcRemoteActivity.kt`, `ImageCache.kt` | „PC steuern“: Protokoll, dauerhafte Verbindung (Vordergrunddienst), Fernbedienung, Cover-Cache |
## Bekannte Grenzen
+3 -2
View File
@@ -19,8 +19,8 @@ android {
applicationId = "de.fojadrachi.playtube"
minSdk = 26
targetSdk = 36
versionCode = 5
versionName = "1.2.1"
versionCode = 6
versionName = "1.3.0"
// Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play).
buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"")
@@ -78,6 +78,7 @@ dependencies {
implementation("androidx.appcompat:appcompat:1.7.0")
implementation("androidx.webkit:webkit:1.12.1")
implementation("androidx.media:media:1.7.0")
implementation("androidx.palette:palette:1.0.0")
// Discord Social SDK (Rich Presence): nicht im Repo, siehe README "Discord-SDK".
implementation(files("../libs/discord_partner_sdk.aar"))
+9
View File
@@ -8,6 +8,9 @@
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- "PC steuern" bleibt im Hintergrund verbunden (PcRemoteService). -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<!-- Das Discord-SDK bringt Sprach-Berechtigungen und eine Login-Activity mit; Playtube nutzt
nur die Rich Presence und braucht davon nichts. -->
@@ -53,9 +56,15 @@
android:name=".PcRemoteActivity"
android:exported="false"
android:label="@string/pc_title"
android:launchMode="singleTop"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
android:windowSoftInputMode="adjustResize" />
<service
android:name=".PcRemoteService"
android:exported="false"
android:foregroundServiceType="connectedDevice" />
<service
android:name=".PlaybackService"
android:exported="false"
@@ -0,0 +1,85 @@
package de.fojadrachi.playtube
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.os.Looper
import android.util.LruCache
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executors
/** Laedt Cover im Hintergrund und haelt die letzten in einem kleinen Speicher-Cache (~12 MB). */
object ImageCache {
private const val MAX_BYTES = 4 * 1024 * 1024 * 3
private const val MAX_DOWNLOAD = 4 * 1024 * 1024
private val cache = object : LruCache<String, Bitmap>(MAX_BYTES) {
override fun sizeOf(key: String, value: Bitmap) = value.byteCount
}
private val executor = Executors.newFixedThreadPool(3)
private val main = Handler(Looper.getMainLooper())
fun cached(url: String, maxPx: Int): Bitmap? = cache.get(key(url, maxPx))
/** Ruft [done] auf dem Hauptthread auf (mit null, wenn das Bild nicht geladen werden konnte). */
fun load(url: String, maxPx: Int, done: (Bitmap?) -> Unit) {
if (!url.startsWith("https://")) {
done(null)
return
}
cached(url, maxPx)?.let {
done(it)
return
}
try {
executor.execute {
val bitmap = download(url, maxPx)
if (bitmap != null) cache.put(key(url, maxPx), bitmap)
main.post { done(bitmap) }
}
} catch (_: Exception) {
done(null)
}
}
private fun key(url: String, maxPx: Int) = "$maxPx|$url"
private fun download(url: String, maxPx: Int): Bitmap? =
try {
val connection = URL(url).openConnection() as HttpURLConnection
connection.connectTimeout = 8_000
connection.readTimeout = 8_000
val bytes = try {
connection.inputStream.use { it.readNBytesLimited(MAX_DOWNLOAD) }
} finally {
connection.disconnect()
}
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
val options = BitmapFactory.Options().apply { inSampleSize = sampleSize(bounds.outWidth, bounds.outHeight, maxPx) }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
} catch (_: Exception) {
null
}
private fun java.io.InputStream.readNBytesLimited(limit: Int): ByteArray {
val out = java.io.ByteArrayOutputStream()
val buffer = ByteArray(16 * 1024)
while (true) {
val read = read(buffer)
if (read < 0) break
out.write(buffer, 0, read)
if (out.size() > limit) throw java.io.IOException("Bild zu gross")
}
return out.toByteArray()
}
/** Groesster Faktor (Zweierpotenz), bei dem die Seiten noch mindestens [maxPx] Pixel haben. */
fun sampleSize(width: Int, height: Int, maxPx: Int): Int {
var sample = 1
val side = minOf(width, height)
while (maxPx > 0 && side / (sample * 2) >= maxPx) sample *= 2
return sample
}
}
@@ -20,6 +20,12 @@ import java.net.SocketTimeoutException
data class PcDevice(val name: String, val host: String, val port: Int = PcRemote.DEFAULT_PORT)
/** Was auf dem PC gerade laeuft (aus der "status"-Antwort, Zeiten in Sekunden). */
/** Ein Titel der Warteschlange am PC. */
data class QueueItem(val title: String, val subtitle: String, val thumbnail: String, val current: Boolean)
/** Eine Playlist der YouTube-Music-Bibliothek am PC. */
data class PcPlaylist(val id: String, val title: String)
data class PcState(
val activeTab: String,
val visibleTab: String,
@@ -31,6 +37,8 @@ data class PcState(
val duration: Double,
val volume: Int,
val liked: Boolean,
/** "NONE", "ALL" oder "ONE" (leer = unbekannt). */
val repeatMode: String = "",
) {
companion object {
val EMPTY = PcState("music", "music", "", "", "", false, 0.0, 0.0, 100, false)
@@ -73,9 +81,45 @@ object PcRemote {
duration = tab?.optDouble("duration")?.takeIf { it.isFinite() } ?: 0.0,
volume = (tab?.optDouble("volume")?.takeIf { it.isFinite() } ?: 100.0).toInt().coerceIn(0, 100),
liked = tab?.optString("likeStatus").equals("LIKE", ignoreCase = true),
repeatMode = tab.text("repeatMode").uppercase(),
)
}
/** "queue"-Antwort -> Titel (Cover in Listengroesse); Eintraege ohne JSON-Objekt werden uebersprungen. */
fun parseQueue(reply: JSONObject): List<QueueItem> {
val array = reply.optJSONArray("queue") ?: return emptyList()
val items = ArrayList<QueueItem>()
for (i in 0 until array.length()) {
val item = array.optJSONObject(i) ?: continue
// Nichts weglassen: der Index muss zur Reihenfolge am PC passen (play_queue_item).
items += QueueItem(
title = item.text("title").trim(),
subtitle = item.text("subtitle").trim(),
thumbnail = sizedCover(item.text("thumbnail").takeIf { it.startsWith("https://") }.orEmpty(), 226),
current = item.optBoolean("current"),
)
}
return items
}
/** "list_playlists"-Antwort -> Playlists. */
fun parsePlaylists(reply: JSONObject): List<PcPlaylist> {
val array = reply.optJSONArray("playlists") ?: return emptyList()
val items = ArrayList<PcPlaylist>()
for (i in 0 until array.length()) {
val item = array.optJSONObject(i) ?: continue
val id = item.text("id").trim()
if (id.isEmpty()) continue
items += PcPlaylist(id, item.text("title").trim().ifEmpty { id })
}
return items
}
/** Ein PC mit Playtube 2.0.x kennt "queue" noch nicht und antwortet mit "unbekannter Befehl". */
fun isUnknownCommand(message: String?): Boolean =
message != null && (message.contains("unbekannter Befehl", ignoreCase = true) ||
message.contains("unknown command", ignoreCase = true))
private val GOOGLE_IMAGE_SIZE = Regex("=(w\\d+-h\\d+|s\\d+)[^/=]*$")
private val YTIMG_SMALL = Regex("/(default|mqdefault)\\.jpg$")
@@ -83,9 +127,12 @@ object PcRemote {
* Das Cover aus der YouTube-Music-Player-Leiste ist nur 60x60 Pixel gross ("=w60-h60-l90-rj") -
* fuer die Fernbedienung in 544x544 anfordern; kleine YouTube-Vorschaubilder durch hqdefault ersetzen.
*/
fun largeCover(url: String): String = when {
fun largeCover(url: String): String = sizedCover(url, 544)
/** Wie [largeCover], aber in [size] x [size] Pixeln (fuer kleine Listenbilder). */
fun sizedCover(url: String, size: Int): String = when {
url.contains("googleusercontent.com") || url.contains("ggpht.com") ->
url.replace(GOOGLE_IMAGE_SIZE, "=w544-h544-l90-rj")
url.replace(GOOGLE_IMAGE_SIZE, "=w$size-h$size-l90-rj")
url.contains("ytimg.com") -> url.replace(YTIMG_SMALL, "/hqdefault.jpg")
else -> url
}
@@ -1,18 +1,24 @@
package de.fojadrachi.playtube
import android.Manifest
import android.animation.ValueAnimator
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Outline
import android.graphics.drawable.GradientDrawable
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.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.view.ViewGroup
import android.view.ViewOutlineProvider
import android.widget.BaseAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
@@ -21,46 +27,47 @@ import android.widget.LinearLayout
import android.widget.ListView
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.graphics.ColorUtils
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
import androidx.palette.graphics.Palette
/**
* "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).
* (Titel, Cover, Play/Pause, Spulen, Lautstaerke, Like, Warteschlange, Playlists). Die Verbindung
* haelt [PcSession] mit dem Vordergrunddienst [PcRemoteService] - sie bleibt bestehen, wenn man diesen
* Bildschirm verlaesst. Protokoll siehe [PcRemote].
*/
class PcRemoteActivity : AppCompatActivity() {
class PcRemoteActivity : AppCompatActivity(), PcSession.Listener {
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 var coverUrl = ""
private var gradientColor = BACKGROUND
private var gradientAnimator: ValueAnimator? = null
private var lastPhase = PcSession.Phase.IDLE
private var pendingTarget: PcDevice? = null
/** Meldung (Fehler / Verbindung verloren), die die Suche nicht ueberschreiben soll. */
private var note: String? = null
private var listMode: ListMode? = null
private var queueItems = listOf<QueueItem>()
private var playlistItems = listOf<PcPlaylist>()
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 listPanel: View
private lateinit var gradient: View
private lateinit var cover: ImageView
private lateinit var deviceName: TextView
private lateinit var trackTitle: TextView
private lateinit var trackSubtitle: TextView
private lateinit var positionBar: SeekBar
@@ -68,16 +75,20 @@ class PcRemoteActivity : AppCompatActivity() {
private lateinit var durationText: TextView
private lateinit var playPause: ImageButton
private lateinit var like: ImageButton
private lateinit var repeat: ImageButton
private lateinit var volumeBar: SeekBar
private lateinit var tabYoutube: Button
private lateinit var tabMusic: Button
private lateinit var deviceAdapter: RowAdapter
private lateinit var itemAdapter: RowAdapter
private lateinit var listTitle: TextView
private lateinit var listMessage: TextView
private lateinit var itemList: ListView
private val pollLoop = object : Runnable {
override fun run() {
requestStatus()
main.postDelayed(this, POLL_INTERVAL_MS)
}
}
private enum class ListMode { QUEUE, PLAYLISTS }
private val notificationPermission =
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* ohne Erlaubnis: nur keine Benachrichtigung */ }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -87,7 +98,10 @@ class PcRemoteActivity : AppCompatActivity() {
status = findViewById(R.id.remoteStatus)
devicePanel = findViewById(R.id.devicePanel)
playerPanel = findViewById(R.id.playerPanel)
listPanel = findViewById(R.id.listPanel)
gradient = findViewById(R.id.gradient)
cover = findViewById(R.id.cover)
deviceName = findViewById(R.id.deviceName)
trackTitle = findViewById(R.id.trackTitle)
trackSubtitle = findViewById(R.id.trackSubtitle)
positionBar = findViewById(R.id.positionBar)
@@ -95,29 +109,52 @@ class PcRemoteActivity : AppCompatActivity() {
durationText = findViewById(R.id.durationText)
playPause = findViewById(R.id.playPauseButton)
like = findViewById(R.id.likeButton)
repeat = findViewById(R.id.repeatButton)
volumeBar = findViewById(R.id.volumeBar)
tabYoutube = findViewById(R.id.tabYoutube)
tabMusic = findViewById(R.id.tabMusic)
listTitle = findViewById(R.id.listTitle)
listMessage = findViewById(R.id.listMessage)
itemList = findViewById(R.id.itemList)
deviceAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, mutableListOf())
setupRoundCover()
applyGradient(BACKGROUND)
deviceAdapter = RowAdapter(this)
findViewById<ListView>(R.id.deviceList).apply {
adapter = deviceAdapter
setOnItemClickListener { _, _, position, _ -> devices.getOrNull(position)?.let(::connect) }
setOnItemClickListener { _, _, position, _ -> devices.getOrNull(position)?.let(::connectTo) }
}
itemAdapter = RowAdapter(this)
itemList.apply {
adapter = itemAdapter
setOnItemClickListener { _, _, position, _ -> onListItemClicked(position) }
}
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")
findViewById<Button>(R.id.searchButton).setOnClickListener {
note = null
search()
}
like.setOnClickListener { send("like") }
tabYoutube.setOnClickListener { send("switch_tab", target = "youtube") }
tabMusic.setOnClickListener { send("switch_tab", target = "music") }
findViewById<Button>(R.id.manualButton).setOnClickListener { askForAddress() }
findViewById<Button>(R.id.disconnectButton).setOnClickListener { PcSession.disconnect() }
findViewById<ImageButton>(R.id.deviceBack).setOnClickListener { showPlayer() }
findViewById<ImageButton>(R.id.closeButton).setOnClickListener { finish() }
findViewById<ImageButton>(R.id.devicesButton).setOnClickListener { showDevices() }
findViewById<ImageButton>(R.id.listBack).setOnClickListener { closeList() }
findViewById<Button>(R.id.queueButton).setOnClickListener { openList(ListMode.QUEUE) }
findViewById<Button>(R.id.playlistsButton).setOnClickListener { openList(ListMode.PLAYLISTS) }
findViewById<ImageButton>(R.id.previousButton).setOnClickListener { PcSession.send("previous") }
findViewById<ImageButton>(R.id.nextButton).setOnClickListener { PcSession.send("next") }
findViewById<ImageButton>(R.id.shuffleButton).setOnClickListener { PcSession.send("shuffle") }
repeat.setOnClickListener { PcSession.send("repeat") }
playPause.setOnClickListener {
PcSession.send("play_pause") // der naechste Status (1 s) bestaetigt; die Taste schaltet sofort um
renderPlayPause(!PcSession.state.playing)
}
like.setOnClickListener { PcSession.send("like") }
tabYoutube.setOnClickListener { PcSession.send("switch_tab", target = "youtube") }
tabMusic.setOnClickListener { PcSession.send("switch_tab", target = "music") }
positionBar.setOnSeekBarChangeListener(object : SeekBarListener() {
override fun onStartTrackingTouch(bar: SeekBar) {
@@ -131,9 +168,8 @@ class PcRemoteActivity : AppCompatActivity() {
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)
val delta = (bar.progress - PcSession.state.position).coerceIn(-3600.0, 3600.0)
PcSession.send("seek", value = delta)
}
})
volumeBar.setOnSeekBarChangeListener(object : SeekBarListener() {
@@ -143,54 +179,160 @@ class PcRemoteActivity : AppCompatActivity() {
override fun onStopTrackingTouch(bar: SeekBar) {
draggingVolume = false
state = state.copy(volume = bar.progress)
send("set_volume", value = bar.progress.toDouble())
PcSession.send("set_volume", value = bar.progress.toDouble())
}
})
search()
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
when {
listMode != null -> closeList()
PcSession.isActive && devicePanel.visibility == View.VISIBLE -> showPlayer()
else -> {
isEnabled = false
onBackPressedDispatcher.onBackPressed()
}
}
}
})
if (Build.VERSION.SDK_INT >= 33 &&
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) {
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
}
if (PcSession.isActive) {
lastPhase = PcSession.phase
showPlayer()
} else {
showDevices()
}
}
override fun onStart() {
super.onStart()
if (device != null) main.post(pollLoop)
PcSession.addListener(this)
onUpdate()
}
override fun onStop() {
main.removeCallbacks(pollLoop)
PcSession.removeListener(this)
super.onStop()
}
override fun onDestroy() {
main.removeCallbacksAndMessages(null)
onWorker { closeConnection() }
worker.shutdown()
gradientAnimator?.cancel()
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)
view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
WindowInsetsCompat.CONSUMED
}
}
/** Quadratisches Cover mit runden Ecken, so gross wie der freie Platz erlaubt. */
private fun setupRoundCover() {
val corner = 12 * resources.displayMetrics.density
cover.clipToOutline = true
cover.outlineProvider = object : ViewOutlineProvider() {
override fun getOutline(view: View, outline: Outline) {
outline.setRoundRect(0, 0, view.width, view.height, corner)
}
}
findViewById<View>(R.id.coverBox).addOnLayoutChangeListener { box, left, top, right, bottom, _, _, _, _ ->
val side = minOf(right - left, bottom - top).coerceAtLeast(0)
if (cover.layoutParams.width != side || cover.layoutParams.height != side) {
cover.layoutParams = cover.layoutParams.apply {
width = side
height = side
}
}
}
}
// ------------------------------------------------------------------ Bereiche umschalten
private fun showPlayer() {
devicePanel.visibility = View.GONE
playerPanel.visibility = View.VISIBLE
render()
}
private fun showDevices() {
closeList()
val connected = PcSession.isActive
playerPanel.visibility = View.GONE
devicePanel.visibility = View.VISIBLE
findViewById<View>(R.id.deviceBack).visibility = if (connected) View.VISIBLE else View.GONE
findViewById<View>(R.id.disconnectButton).visibility = if (connected) View.VISIBLE else View.GONE
applyGradient(BACKGROUND)
search()
}
// ------------------------------------------------------------------ PC-Sitzung (Listener)
override fun onUpdate() {
val phase = PcSession.phase
val previous = lastPhase
lastPhase = phase
when (phase) {
PcSession.Phase.IDLE -> {
if (previous != PcSession.Phase.IDLE) showDevices()
}
PcSession.Phase.CONNECTING -> status.text = getString(R.string.pc_connecting, PcSession.device?.name.orEmpty())
PcSession.Phase.CONNECTED, PcSession.Phase.RECONNECTING -> {
if (previous == PcSession.Phase.CONNECTING) showPlayer()
if (playerPanel.visibility == View.VISIBLE) render()
}
}
}
override fun onProblem(problem: PcSession.Problem, message: String) {
when (problem) {
PcSession.Problem.PAIRING_REQUIRED -> pendingTarget?.let(::askForCode)
PcSession.Problem.FAILED -> {
note = getString(R.string.pc_error, message)
status.text = note
if (playerPanel.visibility == View.VISIBLE) showDevices()
}
PcSession.Problem.LOST -> {
note = getString(R.string.pc_lost, message)
status.text = note
showDevices()
}
}
}
// ------------------------------------------------------------------ PCs finden
private fun search() {
status.setText(R.string.pc_searching)
if (note == null) status.setText(R.string.pc_searching) else status.text = note
Thread {
val found = PcRemote.discover()
main.post {
if (isFinishing) return@post
if (isFinishing || isDestroyed) 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)
val connectedHost = PcSession.device?.takeIf { PcSession.isActive }?.host
deviceAdapter.setRows(
found.map {
Row(
title = it.name,
subtitle = if (it.host == connectedHost) getString(R.string.pc_this_pc) else it.host,
iconRes = R.drawable.ic_computer,
highlighted = it.host == connectedHost,
)
},
)
if (PcSession.phase != PcSession.Phase.CONNECTING) {
note?.let { status.text = it } ?: status.setText(if (found.isEmpty()) R.string.pc_none_found else R.string.pc_found)
}
}
}.start()
}
@@ -199,7 +341,7 @@ class PcRemoteActivity : AppCompatActivity() {
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, ""))
setText(PcSession.prefs(this@PcRemoteActivity).getString(PcSession.KEY_LAST_HOST, ""))
}
AlertDialog.Builder(this)
.setTitle(R.string.pc_manual)
@@ -207,7 +349,8 @@ class PcRemoteActivity : AppCompatActivity() {
.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))
val name = PcSession.prefs(this).getString(PcSession.KEY_NAME_FOR + host, null) ?: host
connectTo(PcDevice(name, host))
}
}
.setNegativeButton(R.string.pc_cancel, null)
@@ -216,35 +359,15 @@ class PcRemoteActivity : AppCompatActivity() {
// ------------------------------------------------------------------ Verbinden / Koppeln
private fun connect(target: PcDevice) {
val token = prefs().getString(KEY_TOKEN_FOR + target.name, null)
private fun connectTo(target: PcDevice) {
note = null
pendingTarget = target
val token = PcSession.prefs(this).getString(PcSession.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) }
}
}
PcSession.connect(this, target, token, null)
}
private fun askForCode(target: PcDevice) {
@@ -257,136 +380,21 @@ class PcRemoteActivity : AppCompatActivity() {
.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()) }
.setPositiveButton(R.string.pc_pair) { _, _ ->
PcSession.connect(this, target, null, 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() }
}
}
// ------------------------------------------------------------------ Anzeige
private fun render() {
val state = PcSession.state
deviceName.text = PcSession.device?.name.orEmpty()
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)
trackSubtitle.text = if (PcSession.phase == PcSession.Phase.RECONNECTING) getString(R.string.pc_reconnecting) else state.subtitle
renderPlayPause(state.playing)
val duration = state.duration.toInt().coerceAtLeast(0)
positionBar.max = duration
@@ -398,44 +406,129 @@ class PcRemoteActivity : AppCompatActivity() {
}
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
like.setImageResource(if (state.liked) R.drawable.ic_favorite else R.drawable.ic_favorite_border)
like.imageTintList = tint(if (state.liked) R.color.brand_to else R.color.text)
repeat.setImageResource(if (state.repeatMode == "ONE") R.drawable.ic_repeat_one else R.drawable.ic_repeat)
repeat.imageTintList = tint(if (state.repeatMode == "ALL" || state.repeatMode == "ONE") R.color.brand_to else R.color.text_muted)
findViewById<ImageButton>(R.id.shuffleButton).imageTintList = tint(R.color.text_muted)
tabYoutube.alpha = if (state.visibleTab == "youtube") 1f else 0.45f
tabMusic.alpha = if (state.visibleTab == "music") 1f else 0.45f
if (state.thumbnail != coverUrl) loadCover(state.thumbnail)
}
private fun renderPlayPause(playing: Boolean) {
playPause.setImageResource(if (playing) R.drawable.ic_pause else R.drawable.ic_play)
playPause.contentDescription = getString(if (playing) R.string.action_pause else R.string.action_play)
}
private fun tint(colorRes: Int) = android.content.res.ColorStateList.valueOf(ContextCompat.getColor(this, colorRes))
private fun loadCover(url: String) {
coverUrl = url
if (url.isEmpty()) {
cover.setImageDrawable(null)
applyGradient(BACKGROUND)
return
}
Thread {
val bitmap = downloadBitmap(url)
main.post { if (coverUrl == url) cover.setImageBitmap(bitmap) }
}.start()
ImageCache.load(url, 544) { bitmap ->
if (coverUrl != url || isDestroyed) return@load
cover.setImageBitmap(bitmap)
if (bitmap != null) {
Palette.from(bitmap).maximumColorCount(12).generate { palette ->
if (coverUrl != url || palette == null || isDestroyed) return@generate
val base = palette.getDarkMutedColor(palette.getMutedColor(palette.getDominantColor(BACKGROUND)))
animateGradient(ColorUtils.blendARGB(base, BACKGROUND, 0.2f))
}
}
}
}
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
private fun animateGradient(target: Int) {
gradientAnimator?.cancel()
gradientAnimator = ValueAnimator.ofArgb(gradientColor, target).apply {
duration = 500
addUpdateListener { applyGradient(it.animatedValue as Int) }
start()
}
}
private fun applyGradient(color: Int) {
gradientColor = color
gradient.background = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(color, BACKGROUND, BACKGROUND))
}
// ------------------------------------------------------------------ Warteschlange / Playlists
private fun openList(mode: ListMode) {
listMode = mode
listPanel.visibility = View.VISIBLE
listTitle.setText(if (mode == ListMode.QUEUE) R.string.pc_queue else R.string.pc_playlists)
itemAdapter.setRows(emptyList())
showListMessage(getString(R.string.pc_loading))
loadList(mode, scrollToCurrent = true)
}
private fun closeList() {
listMode = null
listPanel.visibility = View.GONE
}
private fun loadList(mode: ListMode, scrollToCurrent: Boolean) {
val command = if (mode == ListMode.QUEUE) "queue" else "list_playlists"
PcSession.request(command, { if (mode == ListMode.QUEUE) put("target", PcSession.state.activeTab) }) { result ->
if (listMode != mode || isDestroyed) return@request
result.onSuccess { reply ->
if (mode == ListMode.QUEUE) {
queueItems = PcRemote.parseQueue(reply)
itemAdapter.setRows(
queueItems.map {
Row(it.title.ifBlank { "–" }, it.subtitle, it.thumbnail, R.drawable.ic_queue_music, it.current)
},
)
showListMessage(if (queueItems.isEmpty()) getString(R.string.pc_queue_empty) else null)
if (scrollToCurrent) queueItems.indexOfFirst { it.current }.takeIf { it > 0 }?.let { itemList.setSelection(it) }
} else {
playlistItems = PcRemote.parsePlaylists(reply)
itemAdapter.setRows(playlistItems.map { Row(it.title, "", "", R.drawable.ic_library_music, false) })
showListMessage(if (playlistItems.isEmpty()) getString(R.string.pc_playlists_empty) else null)
}
}.onFailure { error ->
val text = if (PcRemote.isUnknownCommand(error.message)) {
getString(R.string.pc_update_pc)
} else {
getString(R.string.pc_list_error, error.message ?: error.javaClass.simpleName)
}
showListMessage(text)
}
}
}
private fun showListMessage(text: String?) {
listMessage.text = text.orEmpty()
listMessage.visibility = if (text == null) View.GONE else View.VISIBLE
}
private fun onListItemClicked(position: Int) {
when (listMode) {
ListMode.QUEUE -> {
if (position !in queueItems.indices) return
PcSession.send("play_queue_item", target = PcSession.state.activeTab, value = position.toDouble())
// Sofort markieren; kurz darauf ist die Liste vom PC neu geladen.
itemAdapter.setHighlight(position)
main.postDelayed({ if (listMode == ListMode.QUEUE) loadList(ListMode.QUEUE, scrollToCurrent = false) }, 1500)
}
ListMode.PLAYLISTS -> {
val playlist = playlistItems.getOrNull(position) ?: return
PcSession.request("play_playlist", { put("playlist", playlist.id) })
closeList()
}
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()
@@ -450,12 +543,65 @@ class PcRemoteActivity : AppCompatActivity() {
override fun onStopTrackingTouch(bar: SeekBar) {}
}
/** Eine Zeile in Geraete-, Warteschlangen- und Playlist-Listen. */
private data class Row(
val title: String,
val subtitle: String,
val imageUrl: String = "",
val iconRes: Int = 0,
val highlighted: Boolean = false,
)
private class RowAdapter(private val context: Context) : BaseAdapter() {
private var rows = listOf<Row>()
private val pink = ContextCompat.getColor(context, R.color.brand_to)
private val white = ContextCompat.getColor(context, R.color.text)
private val density = context.resources.displayMetrics.density
fun setRows(new: List<Row>) {
rows = new
notifyDataSetChanged()
}
fun setHighlight(position: Int) {
rows = rows.mapIndexed { i, row -> row.copy(highlighted = i == position) }
notifyDataSetChanged()
}
override fun getCount() = rows.size
override fun getItem(position: Int) = rows[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.item_row, parent, false)
val row = rows[position]
val title = view.findViewById<TextView>(R.id.rowTitle)
val subtitle = view.findViewById<TextView>(R.id.rowSubtitle)
val image = view.findViewById<ImageView>(R.id.rowImage)
title.text = row.title
title.setTextColor(if (row.highlighted) pink else white)
subtitle.text = row.subtitle
subtitle.visibility = if (row.subtitle.isEmpty()) View.GONE else View.VISIBLE
image.tag = row.imageUrl
image.scaleType = ImageView.ScaleType.CENTER
image.setImageResource(row.iconRes)
image.imageTintList = android.content.res.ColorStateList.valueOf(ContextCompat.getColor(context, R.color.text_muted))
if (row.imageUrl.isNotEmpty()) {
ImageCache.load(row.imageUrl, (48 * density).toInt()) { bitmap ->
if (bitmap != null && image.tag == row.imageUrl) {
image.imageTintList = null
image.scaleType = ImageView.ScaleType.CENTER_CROP
image.setImageBitmap(bitmap)
}
}
}
return view
}
}
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"
private val BACKGROUND = Color.parseColor("#121212")
fun start(context: Context) {
context.startActivity(Intent(context, PcRemoteActivity::class.java))
@@ -0,0 +1,156 @@
package de.fojadrachi.playtube
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.graphics.Bitmap
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import androidx.media.app.NotificationCompat.MediaStyle
/**
* Haelt die Verbindung zum PC ("Steuert <PC>"): Vordergrunddienst mit Benachrichtigung (Cover, Titel,
* Zurueck / Play-Pause / Vor, Trennen). Beruehrt die Wiedergabe auf dem Handy nicht - es gibt hier
* keine Media-Session und keinen Audiofokus. Die eigentliche Arbeit macht [PcSession].
*/
class PcRemoteService : Service(), PcSession.Listener {
private var cover: Bitmap? = null
private var coverUrl = ""
private var shownKey = ""
override fun onCreate() {
super.onCreate()
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(
NotificationChannel(CHANNEL_ID, getString(R.string.channel_pc_remote), NotificationManager.IMPORTANCE_LOW),
)
PcSession.addListener(this)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_DISCONNECT -> {
PcSession.disconnect()
stopSelf()
return START_NOT_STICKY
}
ACTION_PREVIOUS -> PcSession.send("previous")
ACTION_PLAY_PAUSE -> PcSession.send("play_pause")
ACTION_NEXT -> PcSession.send("next")
}
if (PcSession.phase == PcSession.Phase.IDLE && intent?.action != null) {
stopSelf()
return START_NOT_STICKY
}
startInForeground(buildNotification())
return START_NOT_STICKY
}
private fun startInForeground(notification: Notification) {
if (Build.VERSION.SDK_INT >= 29) {
startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)
} else {
startForeground(NOTIFICATION_ID, notification)
}
}
override fun onDestroy() {
PcSession.removeListener(this)
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? = null
// ------------------------------------------------------------------ Listener
override fun onUpdate() {
if (PcSession.phase == PcSession.Phase.IDLE) {
stopSelf()
return
}
val state = PcSession.state
if (state.thumbnail != coverUrl) {
coverUrl = state.thumbnail
cover = null
if (coverUrl.isNotEmpty()) {
val url = coverUrl
ImageCache.load(url, COVER_PX) { bitmap ->
if (coverUrl == url && bitmap != null) {
cover = bitmap
refresh()
}
}
}
}
refresh()
}
override fun onProblem(problem: PcSession.Problem, message: String) {}
/** Nur neu zeichnen, wenn sich etwas Sichtbares geaendert hat (jede Sekunde ein Status kommt an). */
private fun refresh() {
val state = PcSession.state
val key = "${PcSession.phase}|${PcSession.device?.name}|${state.title}|${state.subtitle}|${state.playing}|${cover != null}"
if (key == shownKey) return
shownKey = key
getSystemService(NotificationManager::class.java).notify(NOTIFICATION_ID, buildNotification())
}
private fun buildNotification(): Notification {
val name = PcSession.device?.name.orEmpty()
val state = PcSession.state
val reconnecting = PcSession.phase == PcSession.Phase.RECONNECTING
val text = when {
reconnecting -> getString(R.string.pc_reconnecting)
state.title.isBlank() -> getString(R.string.pc_nothing_playing)
state.subtitle.isBlank() -> state.title
else -> "${state.title} – ${state.subtitle}"
}
val open = PendingIntent.getActivity(
this, 0, Intent(this, PcRemoteActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(getString(R.string.pc_controlling, name))
.setContentText(text)
.setLargeIcon(cover)
.setContentIntent(open)
.setOnlyAlertOnce(true)
.setOngoing(true)
.setShowWhen(false)
.setCategory(NotificationCompat.CATEGORY_TRANSPORT)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(R.drawable.ic_skip_previous, getString(R.string.action_previous), action(ACTION_PREVIOUS, 1))
.addAction(
if (state.playing) R.drawable.ic_pause else R.drawable.ic_play,
getString(if (state.playing) R.string.action_pause else R.string.action_play),
action(ACTION_PLAY_PAUSE, 2),
)
.addAction(R.drawable.ic_skip_next, getString(R.string.action_next), action(ACTION_NEXT, 3))
.addAction(0, getString(R.string.pc_disconnect), action(ACTION_DISCONNECT, 4))
.setStyle(MediaStyle().setShowActionsInCompactView(0, 1, 2))
return builder.build()
}
private fun action(action: String, requestCode: Int): PendingIntent =
PendingIntent.getService(
this, requestCode, Intent(this, PcRemoteService::class.java).setAction(action),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
)
companion object {
private const val CHANNEL_ID = "pc_remote"
private const val NOTIFICATION_ID = 2
private const val COVER_PX = 256
private const val ACTION_PREVIOUS = "de.fojadrachi.playtube.PC_PREVIOUS"
private const val ACTION_PLAY_PAUSE = "de.fojadrachi.playtube.PC_PLAY_PAUSE"
private const val ACTION_NEXT = "de.fojadrachi.playtube.PC_NEXT"
private const val ACTION_DISCONNECT = "de.fojadrachi.playtube.PC_DISCONNECT"
}
}
@@ -0,0 +1,317 @@
package de.fojadrachi.playtube
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Build
import android.os.Handler
import android.os.Looper
import androidx.core.content.ContextCompat
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
/**
* Die Verbindung zum PC ueberlebt den Steuerungsbildschirm (wie Spotify Connect): sie lebt hier im
* Prozess, gehalten von [PcRemoteService] (Vordergrunddienst + Benachrichtigung). Verbindung, Status-
* Abfrage und Befehle laufen auf einem eigenen Thread; Aufrufer und Listener sind immer der Hauptthread.
*/
object PcSession {
enum class Phase { IDLE, CONNECTING, CONNECTED, RECONNECTING }
enum class Problem { PAIRING_REQUIRED, FAILED, LOST }
interface Listener {
fun onUpdate()
fun onProblem(problem: Problem, message: String)
}
const val PREFS = "pc_remote"
const val KEY_TOKEN_FOR = "token:"
const val KEY_NAME_FOR = "name:"
const val KEY_LAST_HOST = "last_host"
private const val POLL_VISIBLE_MS = 1_000L
private const val POLL_BACKGROUND_MS = 4_000L
private const val RECONNECT_ATTEMPTS = 5
private val main = Handler(Looper.getMainLooper())
private val worker: ExecutorService = Executors.newSingleThreadExecutor()
private val listeners = mutableListOf<Listener>()
/** Nur auf [worker] benutzen. */
private var connection: PcRemote.Connection? = null
private var statusPending = false
private var generation = 0
private var reconnectAttempt = 0
private lateinit var appContext: Context
var phase = Phase.IDLE
private set
var device: PcDevice? = null
private set
var state: PcState = PcState.EMPTY
private set
/** Verbunden oder gerade dabei (Player soll angezeigt werden). */
val isActive: Boolean get() = phase == Phase.CONNECTED || phase == Phase.RECONNECTING
fun prefs(context: Context): SharedPreferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
// ------------------------------------------------------------------ Listener / Polling
fun addListener(listener: Listener) {
listeners += listener
if (listeners.size == 1 && phase == Phase.CONNECTED) {
main.removeCallbacks(poll)
main.post(poll) // sofort frischen Stand holen, danach im 1-s-Takt
}
}
fun removeListener(listener: Listener) {
listeners -= listener
}
private val poll = object : Runnable {
override fun run() {
if (phase != Phase.CONNECTED) return
requestStatus()
main.postDelayed(this, if (listeners.isEmpty()) POLL_BACKGROUND_MS else POLL_VISIBLE_MS)
}
}
private fun notifyUpdate() = listeners.toList().forEach { it.onUpdate() }
private fun notifyProblem(problem: Problem, message: String) =
listeners.toList().forEach { it.onProblem(problem, message) }
// ------------------------------------------------------------------ Verbinden / Trennen
/**
* Verbindet mit [target]: mit [code] wird neu gekoppelt, sonst mit dem gespeicherten [token].
* Startet dabei den Vordergrunddienst, der die Verbindung haelt.
*/
fun connect(context: Context, target: PcDevice, token: String?, code: String?) {
appContext = context.applicationContext
val gen = ++generation
main.removeCallbacks(poll)
phase = Phase.CONNECTING
device = target
state = PcState.EMPTY
reconnectAttempt = 0
notifyUpdate()
ContextCompat.startForegroundService(appContext, Intent(appContext, PcRemoteService::class.java))
onWorker {
closeConnection()
try {
val conn = PcRemote.Connection.open(target)
val reply = try {
if (code != null) {
conn.request("pair") {
put("code", code)
put("device", Build.MODEL ?: "Android")
}
} else {
conn.request("hello") { put("token", token.orEmpty()) }
}
} catch (e: IOException) {
conn.close()
throw e
}
connection = conn
main.post { if (gen == generation) onConnected(target, reply, code != null) else onWorker { conn.close() } }
} catch (e: PcRemote.RemoteException) {
main.post {
if (gen != generation) return@post
if (code == null) {
prefs(appContext).edit().remove(KEY_TOKEN_FOR + target.name).apply()
reset()
notifyProblem(Problem.PAIRING_REQUIRED, e.message.orEmpty())
} else {
reset()
notifyProblem(Problem.FAILED, e.message ?: "Fehler")
}
}
} catch (e: IOException) {
main.post {
if (gen != generation) return@post
reset()
notifyProblem(Problem.FAILED, e.message ?: e.javaClass.simpleName)
}
}
}
}
private fun onConnected(target: PcDevice, reply: JSONObject, paired: Boolean) {
// Der PC meldet seinen Namen - unter dem merken wir uns Token und Adresse.
val name = reply.optString("name").ifBlank { target.name }
val token = if (paired) reply.optString("token") else prefs(appContext).getString(KEY_TOKEN_FOR + target.name, null)
prefs(appContext).edit().apply {
if (!token.isNullOrEmpty()) {
putString(KEY_TOKEN_FOR + target.name, token)
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)
phase = Phase.CONNECTED
notifyUpdate()
main.removeCallbacks(poll)
main.post(poll)
}
/** Trennt bewusst (Knopf "Trennen") und beendet den Dienst. */
fun disconnect() {
reset()
notifyUpdate()
}
private fun reset() {
generation++
main.removeCallbacks(poll)
main.removeCallbacks(reconnectRunnable)
phase = Phase.IDLE
device = null
state = PcState.EMPTY
statusPending = false
onWorker { closeConnection() }
if (::appContext.isInitialized) appContext.stopService(Intent(appContext, PcRemoteService::class.java))
}
// ------------------------------------------------------------------ Verbindungsverlust
private fun onConnectionLost() {
if (phase != Phase.CONNECTED) return
phase = Phase.RECONNECTING
reconnectAttempt = 0
main.removeCallbacks(poll)
notifyUpdate()
scheduleReconnect()
}
private val reconnectRunnable = Runnable { reconnect() }
private fun scheduleReconnect() {
main.postDelayed(reconnectRunnable, 2_000L * (reconnectAttempt + 1))
}
private fun reconnect() {
val target = device ?: return
if (phase != Phase.RECONNECTING) return
val token = prefs(appContext).getString(KEY_TOKEN_FOR + target.name, null)
val gen = generation
reconnectAttempt++
onWorker {
closeConnection()
try {
val conn = PcRemote.Connection.open(target)
try {
conn.request("hello") { put("token", token.orEmpty()) }
} catch (e: IOException) {
conn.close()
throw e
}
connection = conn
main.post {
if (gen != generation || phase != Phase.RECONNECTING) return@post
phase = Phase.CONNECTED
notifyUpdate()
main.removeCallbacks(poll)
main.post(poll)
}
} catch (e: IOException) {
main.post {
if (gen != generation || phase != Phase.RECONNECTING) return@post
if (e is PcRemote.RemoteException || reconnectAttempt >= RECONNECT_ATTEMPTS) {
val name = device?.name.orEmpty()
reset()
notifyUpdate()
notifyProblem(Problem.LOST, name)
} else {
scheduleReconnect()
}
}
}
}
}
// ------------------------------------------------------------------ Befehle und Stand
private fun requestStatus() {
// Bei langsamem WLAN nicht eine Abfrage pro Sekunde aufstauen.
if (statusPending) return
statusPending = true
val gen = generation
onWorker {
try {
val conn = connection
if (conn == null) {
main.post { statusPending = false }
return@onWorker
}
val next = PcRemote.parseState(conn.request("status"))
main.post {
statusPending = false
if (gen != generation || phase != Phase.CONNECTED) return@post
if (next != null) {
state = next
notifyUpdate()
}
}
} catch (_: IOException) {
closeConnection()
main.post {
statusPending = false
if (gen == generation) onConnectionLost()
}
}
}
}
/** Befehl ohne Antwort; danach wird der Stand neu abgefragt. */
fun send(command: String, target: String = "auto", value: Double? = null) {
request(command, {
put("target", target)
if (value != null) put("value", value)
}) { requestStatus() }
}
/** Anfrage mit Antwort; [done] kommt auf dem Hauptthread (Fehler: RemoteException vom PC oder IOException). */
fun request(command: String, fill: JSONObject.() -> Unit = {}, done: (Result<JSONObject>) -> Unit = {}) {
val gen = generation
onWorker {
val conn = connection
if (conn == null) {
main.post { done(Result.failure(IOException("Nicht verbunden"))) }
return@onWorker
}
try {
val reply = conn.request(command, fill)
main.post { done(Result.success(reply)) }
} catch (e: PcRemote.RemoteException) {
main.post { done(Result.failure(e)) } // Befehl abgelehnt - Verbindung bleibt
} catch (e: IOException) {
closeConnection()
main.post {
if (gen == generation) onConnectionLost()
done(Result.failure(e))
}
}
}
}
private fun onWorker(block: () -> Unit) {
try {
worker.execute(block)
} catch (_: RejectedExecutionException) {
}
}
/** Nur auf [worker] aufrufen. */
private fun closeConnection() {
connection?.close()
connection = null
}
}
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#33FFFFFF" />
<corners android:radius="22dp" />
</shape>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:color="#FFFFFF" />
</shape>
+5
View File
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#2A2A2A" />
<corners android:radius="6dp" />
</shape>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M20,18c1.1,0 1.99,-0.9 1.99,-2L22,6c0,-1.1 -0.9,-2 -2,-2H4c-1.1,0 -2,0.9 -2,2v10c0,1.1 0.9,2 2,2H0v2h24v-2h-4zM4,6h16v10H4V6z" />
</vector>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M12,21.35l-1.45,-1.32C5.4,15.36 2,12.28 2,8.5 2,5.42 4.42,3 7.5,3c1.74,0 3.41,0.81 4.5,2.09C13.09,3.81 14.76,3 16.5,3 19.58,3 22,5.42 22,8.5c0,3.78 -3.4,6.86 -8.55,11.54L12,21.35z" />
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M16.5,3c-1.74,0 -3.41,0.81 -4.5,2.09C10.91,3.81 9.24,3 7.5,3 4.42,3 2,5.42 2,8.5c0,3.78 3.4,6.86 8.55,11.54L12,21.35l1.45,-1.32C18.6,15.36 22,12.28 22,8.5 22,5.42 19.58,3 16.5,3zm-4.4,15.55l-0.1,0.1 -0.1,-0.1C7.14,14.24 4,11.39 4,8.5 4,6.5 5.5,5 7.5,5c1.54,0 3.04,0.99 3.57,2.36h1.87C13.46,5.99 14.96,5 16.5,5c2,0 3.5,1.5 3.5,3.5 0,2.89 -3.14,5.74 -7.9,10.05z" />
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M7.41,8.59L12,13.17l4.59,-4.58L18,10l-6,6 -6,-6 1.41,-1.41z" />
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M20,2H8c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2V4c0,-1.1 -0.9,-2 -2,-2zm-2,5h-3v5.5c0,1.38 -1.12,2.5 -2.5,2.5S10,13.88 10,12.5s1.12,-2.5 2.5,-2.5c0.57,0 1.08,0.19 1.5,0.51V5h4v2zM4,6H2v14c0,1.1 0.9,2 2,2h14v-2H4V6z" />
</vector>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M6,19h4V5H6v14zm8,-14v14h4V5h-4z" />
</vector>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M8,5v14l11,-7z" />
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M15,6H3v2h12V6zm0,4H3v2h12v-2zM3,16h8v-2H3v2zM17,6v8.18c-0.31,-0.11 -0.65,-0.18 -1,-0.18 -1.66,0 -3,1.34 -3,3s1.34,3 3,3 3,-1.34 3,-3V8h3V6h-5z" />
</vector>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M7,7h10v3l4,-4 -4,-4v3H5v6h2V7zm10,10H7v-3l-4,4 4,4v-3h12v-6h-2v4z" />
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M7,7h10v3l4,-4 -4,-4v3H5v6h2V7zm10,10H7v-3l-4,4 4,4v-3h12v-6h-2v4zm-4,-2V9h-1l-2,1v1h1.5v4H13z" />
</vector>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M10.59,9.17L5.41,4 4,5.41l5.17,5.17 1.42,-1.41zM14.5,4l2.04,2.04L4,18.59 5.41,20 17.96,7.46 20,9.5V4h-5.5zm0.33,9.41l-1.41,1.41 3.13,3.13L14.5,20H20v-5.5l-2.04,2.04 -3.13,-3.13z" />
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M6,18l8.5,-6L6,6v12zM16,6v12h2V6h-2z" />
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M6,6h2v12H6zm3.5,6l8.5,6V6z" />
</vector>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<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="M3,9v6h4l5,5V4L7,9H3zm13.5,3c0,-1.77 -1.02,-3.29 -2.5,-4.03v8.05c1.48,-0.73 2.5,-2.25 2.5,-4.02zM14,3.23v2.06c2.89,0.86 5,3.54 5,6.71s-2.11,5.85 -5,6.71v2.06c4.01,-0.91 7,-4.49 7,-8.77s-2.99,-7.86 -7,-8.77z" />
</vector>
+305 -88
View File
@@ -1,50 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
<FrameLayout 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">
android:background="@color/remote_background">
<TextView
android:id="@+id/remoteHeading"
<!-- Farbverlauf aus der Cover-Farbe -->
<View
android:id="@+id/gradient"
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" />
android:layout_height="match_parent" />
<!-- 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">
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="@+id/deviceBack"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/pc_back_to_player"
android:src="@drawable/ic_keyboard_arrow_down"
android:visibility="gone" />
<TextView
android:id="@+id/remoteHeading"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/pc_title"
android:textColor="@color/text"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
<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" />
<ListView
android:id="@+id/deviceList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="12dp"
android:layout_weight="1"
android:divider="@color/surface"
android:dividerHeight="1dp" />
android:divider="@null"
android:dividerHeight="0dp"
android:scrollbars="none" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_marginTop="8dp"
android:text="@string/pc_hint"
android:textColor="@color/text_muted"
android:textSize="13sp" />
@@ -70,77 +92,172 @@
android:layout_weight="1"
android:text="@string/pc_manual" />
</LinearLayout>
<Button
android:id="@+id/disconnectButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="@string/pc_disconnect"
android:visibility="gone" />
</LinearLayout>
<!-- Fernbedienung fuer den verbundenen PC -->
<!-- Player im Stil einer Streaming-Fernbedienung -->
<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:layout_height="match_parent"
android:orientation="vertical"
android:paddingStart="24dp"
android:paddingEnd="24dp"
android:paddingBottom="8dp"
android:visibility="gone">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="@+id/closeButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/pc_close"
android:src="@drawable/ic_keyboard_arrow_down" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pc_playing_on"
android:textColor="@color/text_muted"
android:textSize="11sp" />
<TextView
android:id="@+id/deviceName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/text"
android:textSize="14sp"
android:textStyle="bold" />
</LinearLayout>
<ImageButton
android:id="@+id/devicesButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/pc_devices"
android:src="@drawable/ic_computer" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:orientation="horizontal">
<Button
android:id="@+id/tabYoutube"
style="?android:attr/borderlessButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_height="36dp"
android:layout_weight="1"
android:text="YouTube" />
android:text="YouTube"
android:textColor="@color/text"
android:textSize="13sp" />
<Button
android:id="@+id/tabMusic"
style="?android:attr/borderlessButtonStyle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_height="36dp"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="YouTube Music" />
android:text="YouTube Music"
android:textColor="@color/text"
android:textSize="13sp" />
</LinearLayout>
<ImageView
android:id="@+id/cover"
<FrameLayout
android:id="@+id/coverBox"
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" />
android:layout_marginTop="12dp"
android:layout_weight="1">
<TextView
android:id="@+id/trackTitle"
<ImageView
android:id="@+id/cover"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:background="@drawable/bg_tile"
android:contentDescription="@string/pc_cover"
android:scaleType="centerCrop" />
</FrameLayout>
<LinearLayout
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" />
android:gravity="center_vertical"
android:orientation="horizontal">
<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" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/trackTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:textColor="@color/text"
android:textSize="22sp"
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" />
</LinearLayout>
<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_favorite_border" />
</LinearLayout>
<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" />
android:layout_marginStart="-16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="-16dp"
android:progressBackgroundTint="#55FFFFFF"
android:progressTint="@color/text"
android:thumbTint="@color/text" />
<LinearLayout
android:layout_width="match_parent"
@@ -164,56 +281,64 @@
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginTop="4dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="@+id/likeButton"
android:layout_width="48dp"
android:id="@+id/shuffleButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/pc_like"
android:src="@drawable/ic_like" />
android:contentDescription="@string/pc_shuffle"
android:src="@drawable/ic_shuffle" />
<ImageButton
android:id="@+id/previousButton"
android:layout_width="56dp"
android:layout_width="0dp"
android:layout_height="56dp"
android:layout_marginStart="12dp"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/action_previous"
android:src="@android:drawable/ic_media_previous" />
android:scaleType="center"
android:src="@drawable/ic_skip_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:background="@drawable/bg_play_white"
android:contentDescription="@string/action_play"
android:src="@android:drawable/ic_media_play" />
android:src="@drawable/ic_play"
android:tint="#000000" />
<ImageButton
android:id="@+id/nextButton"
android:layout_width="56dp"
android:layout_width="0dp"
android:layout_height="56dp"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/action_next"
android:src="@android:drawable/ic_media_next" />
android:scaleType="center"
android:src="@drawable/ic_skip_next" />
<View
android:layout_width="60dp"
android:layout_height="1dp" />
<ImageButton
android:id="@+id/repeatButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_weight="1"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/pc_repeat"
android:src="@drawable/ic_repeat" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_marginTop="4dp"
android:gravity="center_vertical"
android:orientation="horizontal">
@@ -221,7 +346,7 @@
android:layout_width="24dp"
android:layout_height="24dp"
android:contentDescription="@string/pc_volume"
android:src="@android:drawable/ic_lock_silent_mode_off"
android:src="@drawable/ic_volume_up"
android:tint="@color/text_muted" />
<SeekBar
@@ -230,15 +355,107 @@
android:layout_height="wrap_content"
android:layout_weight="1"
android:max="100"
android:progressTint="@color/brand_from"
android:thumbTint="@color/brand_from" />
android:progressBackgroundTint="#55FFFFFF"
android:progressTint="@color/text"
android:thumbTint="@color/text" />
</LinearLayout>
<Button
android:id="@+id/disconnectButton"
android:layout_width="wrap_content"
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/pc_disconnect" />
android:layout_marginTop="4dp"
android:orientation="horizontal">
<Button
android:id="@+id/queueButton"
style="?android:attr/borderlessButtonStyle"
android:layout_width="0dp"
android:layout_height="44dp"
android:layout_weight="1"
android:background="@drawable/bg_pill"
android:drawableStart="@drawable/ic_queue_music"
android:drawablePadding="8dp"
android:drawableTint="@color/text"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:text="@string/pc_queue"
android:textAllCaps="false"
android:textColor="@color/text"
android:textSize="14sp" />
<Button
android:id="@+id/playlistsButton"
style="?android:attr/borderlessButtonStyle"
android:layout_width="0dp"
android:layout_height="44dp"
android:layout_marginStart="12dp"
android:layout_weight="1"
android:background="@drawable/bg_pill"
android:drawableStart="@drawable/ic_library_music"
android:drawablePadding="8dp"
android:drawableTint="@color/text"
android:paddingStart="16dp"
android:paddingEnd="16dp"
android:text="@string/pc_playlists"
android:textAllCaps="false"
android:textColor="@color/text"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<!-- Vollbild-Liste: Warteschlange oder Playlists -->
<LinearLayout
android:id="@+id/listPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/remote_background"
android:clickable="true"
android:focusable="true"
android:orientation="vertical"
android:visibility="gone">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingStart="8dp"
android:paddingEnd="16dp">
<ImageButton
android:id="@+id/listBack"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/pc_back_to_player"
android:src="@drawable/ic_keyboard_arrow_down" />
<TextView
android:id="@+id/listTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:textColor="@color/text"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
<TextView
android:id="@+id/listMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textColor="@color/text_muted"
android:textSize="15sp"
android:visibility="gone" />
<ListView
android:id="@+id/itemList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="@null"
android:dividerHeight="0dp" />
</LinearLayout>
</FrameLayout>
+47
View File
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="64dp"
android:orientation="horizontal"
android:paddingStart="16dp"
android:paddingTop="8dp"
android:paddingEnd="16dp"
android:paddingBottom="8dp">
<ImageView
android:id="@+id/rowImage"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="@drawable/bg_tile"
android:contentDescription="@null"
android:padding="0dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="14dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/rowTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/text"
android:textSize="16sp" />
<TextView
android:id="@+id/rowSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/text_muted"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
+19
View File
@@ -40,6 +40,25 @@
<string name="pc_like">Gefällt mir</string>
<string name="pc_volume">Lautstärke</string>
<string name="channel_pc_remote">PC steuern</string>
<string name="pc_controlling">Steuert %1$s</string>
<string name="pc_reconnecting">Verbinde neu …</string>
<string name="pc_back_to_player">Zurück zum Player</string>
<string name="pc_close">Schließen</string>
<string name="pc_playing_on">Spielt auf</string>
<string name="pc_devices">Geräte</string>
<string name="pc_shuffle">Zufällige Wiedergabe</string>
<string name="pc_repeat">Wiederholen</string>
<string name="pc_queue">Warteschlange</string>
<string name="pc_playlists">Playlists</string>
<string name="pc_loading">Lade …</string>
<string name="pc_queue_empty">Die Warteschlange ist leer.</string>
<string name="pc_playlists_empty">Keine Playlists gefunden. Bist du in YouTube Music am PC angemeldet?</string>
<string name="pc_update_pc">Am PC Playtube auf 2.1.0 aktualisieren, um die Warteschlange zu sehen.</string>
<string name="pc_list_error">Das hat nicht geklappt: %1$s</string>
<string name="pc_this_pc">Verbunden</string>
<color name="remote_background">#121212</color>
<color name="background">#0F0F0F</color>
<color name="surface">#1F1F1F</color>
<color name="text">#FFFFFF</color>
@@ -92,4 +92,40 @@ class PcRemoteTest {
assertEquals("1:05", PcRemote.formatTime(65.9))
assertEquals("1:01:01", PcRemote.formatTime(3661.0))
}
@Test
fun parsesQueueAndKeepsOrder() {
val reply = JSONObject(
"""{"ok": true, "queue": [
{"title": "A", "subtitle": "X", "thumbnail": "https://lh3.googleusercontent.com/a=w60-h60-l90-rj", "current": true},
{"title": "", "subtitle": "leer"},
{"title": "B", "thumbnail": "http://unsicher", "current": false}
]}""",
)
val queue = PcRemote.parseQueue(reply)
assertEquals(3, queue.size)
assertEquals(QueueItem("A", "X", "https://lh3.googleusercontent.com/a=w226-h226-l90-rj", true), queue[0])
assertEquals(QueueItem("", "leer", "", false), queue[1])
assertEquals(QueueItem("B", "", "", false), queue[2])
assertTrue(PcRemote.parseQueue(JSONObject("""{"ok": true}""")).isEmpty())
}
@Test
fun parsesPlaylists() {
val reply = JSONObject("""{"ok": true, "playlists": [{"id": "LM", "title": "Mag ich"}, {"id": "PL1"}, {"title": "x"}]}""")
assertEquals(listOf(PcPlaylist("LM", "Mag ich"), PcPlaylist("PL1", "PL1")), PcRemote.parsePlaylists(reply))
}
@Test
fun recognisesOldPcsWithoutQueue() {
assertTrue(PcRemote.isUnknownCommand("unbekannter Befehl: queue"))
assertFalse(PcRemote.isUnknownCommand("Falscher Code"))
assertFalse(PcRemote.isUnknownCommand(null))
}
@Test
fun readsRepeatMode() {
val reply = JSONObject("""{"ok": true, "state": {"activeTab": "music", "tabs": {"music": {"repeatMode": "one"}}}}""")
assertEquals("ONE", PcRemote.parseState(reply)!!.repeatMode)
}
}
+10 -8
View File
@@ -1,11 +1,13 @@
## Playtube für Android 1.2.1
## Playtube für Android 1.3.0
- **Korrektur „PC steuern“:** Cover werden jetzt scharf angezeigt. Bisher kam bei YouTube Music oft nur
das 60×60-Pixel-Vorschaubild aus der Player-Leiste an und wirkte stark verpixelt.
- **PC steuern im Spotify-Stil:** komplett neuer Steuerungsbildschirm – dunkel, mit Farbverlauf aus dem Cover,
großem Cover, Zufall / Zurück / Play / Vor / Wiederholen, Herz und Lautstärke.
- **Warteschlange und Playlists:** Die Wiedergabeliste vom PC ansehen und einen Titel antippen, um ihn
abzuspielen; ebenso die Playlists aus YouTube Music. Dafür am PC **Playtube 2.1.0** installieren.
- **Verbindung bleibt bestehen:** Playtube bleibt mit dem PC verbunden, auch wenn du den Bildschirm
verlässt – mit Benachrichtigung „Steuert <PC>“ (Cover, Titel, Zurück / Play-Pause / Vor, Trennen).
Bei Verbindungsverlust verbindet sich die App einige Male automatisch neu. Die Hintergrundwiedergabe auf
dem Handy bleibt unberührt.
Neu seit 1.2.0: **PC steuern** (wie Spotify Connect) – Playtube auf dem PC im selben WLAN fernbedienen.
Am PC Playtube 2.0.0 oder neuer unter *Einstellungen › Steuerung vom Handy* einschalten, speichern,
„Handy koppeln“ wählen und den Code in der App eingeben.
Alles Weitere wie bisher: nur YouTube Music, Hintergrundwiedergabe, Sperrbildschirm-Steuerung,
Alles Weitere wie bisher: YouTube Music, Hintergrundwiedergabe, Sperrbildschirm-Steuerung,
Discord Rich Presence, Updates über diese Releases. Voraussetzung: Android 8.0 oder neuer.