Compare commits

..
Author SHA1 Message Date
FojadrachiandClaude Opus 5.5 968920e7f3 fix: PC steuern zeigt Cover scharf statt 60x60 Pixel (v1.2.1)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 21:21:15 +01:00
FojadrachiandClaude Opus 5.5 7a01655e43 chore: Release-Notizen fuer 1.2.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 20:04:49 +01:00
FojadrachiandClaude Opus 5.5 16bdbe9128 feat: PC steuern - Playtube auf dem PC im WLAN fernbedienen (v1.2.0)
Wie Spotify Connect: PCs mit Playtube im selben WLAN finden (UDP-Broadcast
an Port 47812), einmalig mit dem 6-stelligen Code vom PC koppeln und dann
Titel, Cover, Play/Pause, Vor/Zurueck, Spulen, Lautstaerke, Like und den
Wechsel YouTube/YouTube Music steuern. Erreichbar ueber den runden Knopf
am rechten Rand oder die Verknuepfung "PC steuern" am App-Icon.
Gegenstueck am PC: Playtube 2.0.0 (src/lan.rs).

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

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 19:28:43 +01:00
Fojadrachi e3650a6776 fix: schwarze Systemleisten (Edge-to-Edge), Discord-Statuszeile mit Titel (v1.1.1) 2026-09-27 02:48:39 +02:00
Fojadrachi 7697bcfaee feat: Discord Rich Presence ueber das Discord Social SDK (v1.1.0) 2026-09-27 02:41:46 +02:00
23 changed files with 1488 additions and 24 deletions
+3
View File
@@ -1,5 +1,8 @@
.gradle/ .gradle/
build/ build/
.cxx/
# Discord Social SDK (AAR + Header) wird nicht weiterverteilt: selbst laden, siehe README "Discord-SDK"
libs/
.idea/ .idea/
*.iml *.iml
local.properties local.properties
+43 -4
View File
@@ -1,7 +1,7 @@
# Playtube für Android # Playtube für Android
Android-Version von [Playtube](https://git.fojadrachi.de/Fojadrachi/Playtube) – **nur YouTube Music**, Android-Version von [Playtube](https://github.com/fojadrachi/Playtube) – **nur YouTube Music**,
mit Hintergrundwiedergabe. Ohne YouTube-Tab, ohne Discord und ohne Stream-Dock-Fernsteuerung. mit Hintergrundwiedergabe und Discord Rich Presence. Ohne YouTube-Tab und ohne Stream-Dock-Fernsteuerung.
- **YouTube Music in der App** (`music.youtube.com` in einer WebView), Anmeldung mit deinem - **YouTube Music in der App** (`music.youtube.com` in einer WebView), Anmeldung mit deinem
Google-Konto, Login bleibt gespeichert. Google-Konto, Login bleibt gespeichert.
@@ -11,6 +11,15 @@ mit Hintergrundwiedergabe. Ohne YouTube-Tab, ohne Discord und ohne Stream-Dock-F
Bildschirm und in anderen Apps weiter. Bildschirm und in anderen Apps weiter.
- **Medien-Benachrichtigung und Sperrbildschirm** mit Titel, Interpret, Cover, Vorheriger / - **Medien-Benachrichtigung und Sperrbildschirm** mit Titel, Interpret, Cover, Vorheriger /
Play-Pause / Nächster und Spulen; Kopfhörer-Tasten funktionieren. Play-Pause / Nächster und Spulen; Kopfhörer-Tasten funktionieren.
- **Discord Rich Presence**: Discord zeigt „Hört Playtube" mit Titel, Interpret, Cover und
Fortschritt, solange Musik läuft (nicht bei Pause). Nutzt das offizielle Discord Social SDK und
braucht die installierte Discord-App auf demselben Handy; es wird nichts angemeldet, und es
werden keine Konto-Daten an Playtube gegeben.
- **PC steuern** (wie Spotify Connect): Playtube auf dem PC im selben WLAN fernbedienen – Titel,
Cover, Play/Pause, Vor/Zurück, Spulen, Lautstärke, Like und Wechsel zwischen YouTube und
YouTube Music. Erreichbar über den runden Knopf am rechten Rand oder durch langes Drücken aufs
App-Icon („PC steuern“). Am PC einmalig in Playtube unter *Einstellungen › Steuerung vom Handy*
einschalten und mit dem 6-stelligen Code koppeln (siehe unten).
- **Links** zu `music.youtube.com` öffnen sich in Playtube. - **Links** zu `music.youtube.com` öffnen sich in Playtube.
- **Updates** aus den eigenen Releases (Tag `vX.Y.Z-android`), kein GitHub, kein Play Store. - **Updates** aus den eigenen Releases (Tag `vX.Y.Z-android`), kein GitHub, kein Play Store.
@@ -24,13 +33,38 @@ Voraussetzungen: Android 8.0 (API 26) oder neuer, aktuelles „Android System We
(„Unbekannte Apps installieren") – erlauben. („Unbekannte Apps installieren") – erlauben.
3. Beim ersten Start Benachrichtigungen erlauben (für die Steuerung auf dem Sperrbildschirm). 3. Beim ersten Start Benachrichtigungen erlauben (für die Steuerung auf dem Sperrbildschirm).
### PC steuern einrichten
1. Am PC in Playtube (ab Version 2.0.0) *Einstellungen › Steuerung vom Handy* einschalten und
speichern. Windows fragt einmalig nach der Firewall – für **private Netzwerke** erlauben.
2. Am Handy auf den runden Knopf am rechten Rand tippen. Die App sucht Playtube-PCs im WLAN
(UDP-Broadcast an Port 47812); wird keiner gefunden, die am PC angezeigte IP-Adresse eingeben.
3. Am PC „Handy koppeln“ wählen und den 6-stelligen Code am Handy eingeben. Danach verbindet sich
die App mit diesem PC ohne Code.
Verbindung: TCP-Port 47811 im lokalen Netz, unverschlüsselt (wie im Heimnetz üblich); der PC nimmt
nur Geräte aus privaten Netzen an und nur nach Kopplung. Das Gegenstück am PC ist
`playtube/lan_remote.py`.
Bei Akku-Optimierung des Herstellers (Xiaomi, Samsung, …) Playtube dort von der Optimierung Bei Akku-Optimierung des Herstellers (Xiaomi, Samsung, …) Playtube dort von der Optimierung
ausnehmen, sonst beendet Android die Hintergrundwiedergabe manchmal. ausnehmen, sonst beendet Android die Hintergrundwiedergabe manchmal.
## Bauen ## Bauen
Benötigt JDK 17+ und das Android SDK (Plattform 36, Build-Tools 36); der Pfad steht in Benötigt JDK 17+ und das Android SDK (Plattform 36, Build-Tools 36, NDK 29.0.14206865,
`local.properties` (`sdk.dir=…`, wird von Android Studio bzw. von Hand angelegt, nicht im Repo). CMake 3.31.6); der Pfad steht in `local.properties` (`sdk.dir=…`, wird von Android Studio bzw. von
Hand angelegt, nicht im Repo).
### Discord-SDK
Das Discord Social SDK liegt **nicht im Repo** (es gelten Discords Nutzungsbedingungen für das SDK, daher nicht weiterverteilen). Vor
dem ersten Bauen: im [Developer Portal](https://discord.com/developers/applications) unter
*Spiele › Social SDK* das Paket `DiscordSocialSdk-<Version>.zip` laden und daraus in `libs\` legen:
- `discord_social_sdk\lib\release\discord_partner_sdk.aar` → `libs\discord_partner_sdk.aar`
- `discord_social_sdk\include\` → `libs\include\` (`discordpp.h`, `cdiscord.h`)
Gebaut wird die native Brücke `app\src\main\cpp\discord_presence.cpp` (arm64-v8a, armeabi-v7a).
```powershell ```powershell
.\gradlew.bat :app:testDebugUnitTest # Unit-Tests .\gradlew.bat :app:testDebugUnitTest # Unit-Tests
@@ -72,7 +106,9 @@ von Playtube fragen ein anderes Repo ab und sehen sie nie.
| `MediaScripts.kt` | JavaScript für Stand (Titel, Cover, Zeit) und Steuerung | | `MediaScripts.kt` | JavaScript für Stand (Titel, Cover, Zeit) und Steuerung |
| `NowPlaying.kt` | Datensatz „läuft gerade" | | `NowPlaying.kt` | Datensatz „läuft gerade" |
| `UpdateChecker.kt` | Update-Prüfung über die Gitea-Releases | | `UpdateChecker.kt` | Update-Prüfung über die Gitea-Releases |
| `DiscordPresence.kt`, `PresencePlan.kt`, `cpp/` | Discord Rich Presence: was angezeigt wird, und die Brücke zum SDK |
| `UserAgent.kt` | macht die WebView-Kennung zu einer normalen Chrome-Kennung (Google-Anmeldung) | | `UserAgent.kt` | macht die WebView-Kennung zu einer normalen Chrome-Kennung (Google-Anmeldung) |
| `PcRemote.kt`, `PcRemoteActivity.kt` | „PC steuern“: PCs im WLAN finden, koppeln, Fernbedienung |
## Bekannte Grenzen ## Bekannte Grenzen
@@ -80,6 +116,9 @@ von Playtube fragen ein anderes Repo ab und sehen sie nie.
WebView-Merkmale (User-Agent, `X-Requested-With`); ein Zurückspielen auf „Dieser Browser ist nicht WebView-Merkmale (User-Agent, `X-Requested-With`); ein Zurückspielen auf „Dieser Browser ist nicht
sicher" ist trotzdem möglich – dann hilft Anmelden in Chrome nicht, weil die Sitzung nicht sicher" ist trotzdem möglich – dann hilft Anmelden in Chrome nicht, weil die Sitzung nicht
geteilt wird. geteilt wird.
- Rich Presence: Discord entscheidet, ob es einen Eintrag für eine Musik-App anzeigt; die App
setzt ihn als „Hört …". Ohne Discord-App auf dem Handy oder bei ausgeschalteter
Aktivitätsanzeige in Discord erscheint nichts (die Musik läuft trotzdem normal).
- Wischt du die App aus der Liste der letzten Apps, endet die Wiedergabe (die WebView gehört zur - Wischt du die App aus der Liste der letzten Apps, endet die Wiedergabe (die WebView gehört zur
App-Aktivität). App-Aktivität).
- Kein Like-/Wiederholen-/Zufalls-Knopf in der Benachrichtigung; die Bedienung der Seite selbst - Kein Like-/Wiederholen-/Zufalls-Knopf in der Benachrichtigung; die Bedienung der Seite selbst
+18 -2
View File
@@ -19,12 +19,25 @@ android {
applicationId = "de.fojadrachi.playtube" applicationId = "de.fojadrachi.playtube"
minSdk = 26 minSdk = 26
targetSdk = 36 targetSdk = 36
versionCode = 1 versionCode = 5
versionName = "1.0.0" versionName = "1.2.1"
// Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play). // Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play).
buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"") buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"")
buildConfigField("String", "REPO_SLUG", "\"Fojadrachi/Playtube-Android\"") buildConfigField("String", "REPO_SLUG", "\"Fojadrachi/Playtube-Android\"")
// Discord-Anwendung von Playtube (gleiche wie in der Desktop-Version; die ID ist oeffentlich).
buildConfigField("long", "DISCORD_APPLICATION_ID", "1548023494976086127L")
// Discord liefert nur diese ABIs mit; x86 wird nur von Emulatoren gebraucht.
ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a") }
}
ndkVersion = "29.0.14206865"
externalNativeBuild {
cmake {
path = file("src/main/cpp/CMakeLists.txt")
version = "3.31.6"
}
} }
signingConfigs { signingConfigs {
@@ -47,6 +60,7 @@ android {
buildFeatures { buildFeatures {
buildConfig = true buildConfig = true
prefab = true
} }
compileOptions { compileOptions {
@@ -64,6 +78,8 @@ dependencies {
implementation("androidx.appcompat:appcompat:1.7.0") implementation("androidx.appcompat:appcompat:1.7.0")
implementation("androidx.webkit:webkit:1.12.1") implementation("androidx.webkit:webkit:1.12.1")
implementation("androidx.media:media:1.7.0") implementation("androidx.media:media:1.7.0")
// Discord Social SDK (Rich Presence): nicht im Repo, siehe README "Discord-SDK".
implementation(files("../libs/discord_partner_sdk.aar"))
testImplementation("junit:junit:4.13.2") testImplementation("junit:junit:4.13.2")
// Auf der JVM sind die org.json-Klassen von Android nur Attrappen - echte Bibliothek fuer Tests. // Auf der JVM sind die org.json-Klassen von Android nur Attrappen - echte Bibliothek fuer Tests.
+25 -1
View File
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<!-- Musik laeuft im Hintergrund weiter: Vordergrunddienst mit Medien-Benachrichtigung. --> <!-- Musik laeuft im Hintergrund weiter: Vordergrunddienst mit Medien-Benachrichtigung. -->
@@ -8,6 +9,14 @@
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Das Discord-SDK bringt Sprach-Berechtigungen und eine Login-Activity mit; Playtube nutzt
nur die Rich Presence und braucht davon nichts. -->
<uses-permission android:name="android.permission.RECORD_AUDIO" tools:node="remove" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" tools:node="remove" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" tools:node="remove" />
<uses-permission android:name="android.permission.BLUETOOTH" tools:node="remove" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" tools:node="remove" />
<application <application
android:allowBackup="false" android:allowBackup="false"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
@@ -26,6 +35,10 @@
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
<!-- Langes Druecken aufs App-Icon: "PC steuern". -->
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
<!-- Geteilte/angetippte YouTube-Music-Links oeffnen sich in Playtube. --> <!-- Geteilte/angetippte YouTube-Music-Links oeffnen sich in Playtube. -->
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
@@ -35,9 +48,20 @@
</intent-filter> </intent-filter>
</activity> </activity>
<!-- Playtube auf dem PC im selben WLAN steuern (PcRemote.kt). -->
<activity
android:name=".PcRemoteActivity"
android:exported="false"
android:label="@string/pc_title"
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
android:windowSoftInputMode="adjustResize" />
<service <service
android:name=".PlaybackService" android:name=".PlaybackService"
android:exported="false" android:exported="false"
android:foregroundServiceType="mediaPlayback" /> android:foregroundServiceType="mediaPlayback" />
<activity android:name="com.discord.socialsdk.AuthenticationActivity" tools:node="remove" />
<service android:name="com.discord.socialsdk.ForegroundService" tools:node="remove" />
</application> </application>
</manifest> </manifest>
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 3.22)
project(playtube_discord CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Das Discord Social SDK kommt als Prefab-Paket aus libs/discord_partner_sdk.aar (siehe README).
find_package(discord_partner_sdk REQUIRED CONFIG)
add_library(playtube_discord SHARED discord_presence.cpp)
target_link_libraries(playtube_discord discord_partner_sdk::discord_partner_sdk log)
+96
View File
@@ -0,0 +1,96 @@
// JNI-Bruecke zum Discord Social SDK fuer die Rich Presence (siehe DiscordPresence.kt).
// Alle Funktionen werden vom selben Java-Thread aufgerufen, der auch RunCallbacks() ausfuehrt.
#include <jni.h>
#include <android/log.h>
#include <memory>
#include <optional>
#include <string>
#define DISCORDPP_IMPLEMENTATION
#include "discordpp.h"
namespace {
constexpr const char* kTag = "DiscordPresence";
std::unique_ptr<discordpp::Client> gClient;
std::string toString(JNIEnv* env, jstring value) {
if (value == nullptr) return {};
const char* chars = env->GetStringUTFChars(value, nullptr);
std::string result(chars ? chars : "");
if (chars) env->ReleaseStringUTFChars(value, chars);
return result;
}
// Discord verlangt fuer Details/State mindestens 2 Zeichen.
std::optional<std::string> textOrNone(std::string value) {
if (value.size() < 2) return std::nullopt;
return value;
}
} // namespace
extern "C" {
JNIEXPORT void JNICALL
Java_de_fojadrachi_playtube_DiscordPresence_nativeInit(JNIEnv*, jobject, jlong applicationId) {
if (gClient) return;
gClient = std::make_unique<discordpp::Client>();
gClient->SetApplicationId(static_cast<uint64_t>(applicationId));
__android_log_print(ANDROID_LOG_INFO, kTag, "Client bereit");
}
JNIEXPORT void JNICALL
Java_de_fojadrachi_playtube_DiscordPresence_nativeUpdate(JNIEnv* env, jobject, jstring details,
jstring state, jstring artworkUrl,
jlong startMs, jlong endMs) {
if (!gClient) return;
discordpp::Activity activity;
activity.SetType(discordpp::ActivityTypes::Listening);
// Statuszeile "Hoert <Titel> zu" statt des Namens der Discord-Anwendung.
activity.SetStatusDisplayType(discordpp::StatusDisplayTypes::Details);
activity.SetDetails(textOrNone(toString(env, details)));
activity.SetState(textOrNone(toString(env, state)));
if (artworkUrl != nullptr) {
discordpp::ActivityAssets assets;
assets.SetLargeImage(toString(env, artworkUrl));
activity.SetAssets(assets);
}
if (startMs > 0) {
discordpp::ActivityTimestamps timestamps;
timestamps.SetStart(static_cast<uint64_t>(startMs));
if (endMs > 0) timestamps.SetEnd(static_cast<uint64_t>(endMs));
activity.SetTimestamps(timestamps);
}
gClient->UpdateRichPresence(std::move(activity), [](discordpp::ClientResult result) {
if (!result.Successful()) {
__android_log_print(ANDROID_LOG_WARN, kTag, "UpdateRichPresence: %s",
result.Error().c_str());
}
});
}
JNIEXPORT void JNICALL
Java_de_fojadrachi_playtube_DiscordPresence_nativeClear(JNIEnv*, jobject) {
if (gClient) gClient->ClearRichPresence();
}
JNIEXPORT void JNICALL
Java_de_fojadrachi_playtube_DiscordPresence_nativeRunCallbacks(JNIEnv*, jobject) {
discordpp::RunCallbacks();
}
JNIEXPORT void JNICALL
Java_de_fojadrachi_playtube_DiscordPresence_nativeShutdown(JNIEnv*, jobject) {
if (gClient) gClient->ClearRichPresence();
discordpp::RunCallbacks();
gClient.reset();
}
} // extern "C"
@@ -0,0 +1,77 @@
package de.fojadrachi.playtube
import android.app.Activity
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import com.discord.socialsdk.DiscordSocialSdkInit
/**
* Discord Rich Presence ("Hoert Playtube") ueber das offizielle Discord Social SDK.
*
* Die SDK-Aufrufe (C++, siehe cpp/discord_presence.cpp) laufen alle auf einem eigenen Thread, der
* auch die SDK-Callbacks abarbeitet. Fehlt die native Bibliothek oder die Discord-App, bleibt die
* Presence einfach aus; die Musikwiedergabe ist davon nie betroffen. Es wird nichts angemeldet:
* die Presence geht direkt an die installierte Discord-App.
*/
object DiscordPresence {
private const val TAG = "DiscordPresence"
private const val CALLBACK_INTERVAL_MS = 1_000L
private var handler: Handler? = null
private var lastPlan: PresencePlan? = null
@Synchronized
fun init(activity: Activity) {
if (handler != null) return
try {
DiscordSocialSdkInit.setEngineActivity(activity)
System.loadLibrary("playtube_discord")
} catch (e: UnsatisfiedLinkError) {
Log.w(TAG, "Native Bibliothek fehlt - keine Discord-Presence", e)
return
}
val thread = HandlerThread("discord-presence").also { it.start() }
val worker = Handler(thread.looper)
handler = worker
worker.post {
nativeInit(BuildConfig.DISCORD_APPLICATION_ID)
worker.post(object : Runnable {
override fun run() {
nativeRunCallbacks()
worker.postDelayed(this, CALLBACK_INTERVAL_MS)
}
})
}
}
/** null blendet die Presence aus (Pause, nichts laeuft). Gleiche Inhalte werden nicht neu gesendet. */
@Synchronized
fun update(plan: PresencePlan?) {
val worker = handler ?: return
if (plan == null && lastPlan == null) return
if (plan != null && plan.sameAs(lastPlan)) return
lastPlan = plan
worker.post {
if (plan == null) nativeClear()
else nativeUpdate(plan.details, plan.state, plan.artworkUrl, plan.startMs, plan.endMs)
}
}
@Synchronized
fun shutdown() {
val worker = handler ?: return
handler = null
lastPlan = null
worker.post {
nativeShutdown()
worker.looper.quitSafely()
}
}
private external fun nativeInit(applicationId: Long)
private external fun nativeUpdate(details: String, state: String, artworkUrl: String?, startMs: Long, endMs: Long)
private external fun nativeClear()
private external fun nativeRunCallbacks()
private external fun nativeShutdown()
}
@@ -23,6 +23,9 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.webkit.WebSettingsCompat import androidx.webkit.WebSettingsCompat
import androidx.webkit.WebViewCompat import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature import androidx.webkit.WebViewFeature
@@ -48,6 +51,8 @@ class MainActivity : AppCompatActivity() {
setContentView(R.layout.activity_main) setContentView(R.layout.activity_main)
webView = findViewById(R.id.webView) webView = findViewById(R.id.webView)
progress = findViewById(R.id.progress) progress = findViewById(R.id.progress)
keepContentBetweenSystemBars()
findViewById<View>(R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) }
configureWebView() configureWebView()
onBackPressedDispatcher.addCallback( onBackPressedDispatcher.addCallback(
@@ -64,6 +69,7 @@ class MainActivity : AppCompatActivity() {
runOnUiThread { webView.evaluateJavascript(MediaScripts.forCommand(command), null) } runOnUiThread { webView.evaluateJavascript(MediaScripts.forCommand(command), null) }
} }
requestNotificationPermission() requestNotificationPermission()
DiscordPresence.init(this)
PlaybackService.start(this) PlaybackService.start(this)
webView.loadUrl(startUrl(intent)) webView.loadUrl(startUrl(intent))
@@ -83,6 +89,21 @@ class MainActivity : AppCompatActivity() {
super.onPause() super.onPause()
} }
/**
* Ab Android 15 zeichnet jede App unter Status- und Navigationsleiste. Die Seite bekommt deshalb
* Abstand oben/unten (und fuer die Tastatur); dahinter bleiben schwarze Balken stehen.
*/
private fun keepContentBetweenSystemBars() {
val insetsController = WindowCompat.getInsetsController(window, window.decorView)
insetsController.isAppearanceLightStatusBars = false
insetsController.isAppearanceLightNavigationBars = false
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.root)) { view, insets ->
val space = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
view.setPadding(space.left, space.top, space.right, space.bottom)
WindowInsetsCompat.CONSUMED
}
}
override fun onDestroy() { override fun onDestroy() {
handler.removeCallbacksAndMessages(null) handler.removeCallbacksAndMessages(null)
PlaybackHub.commandHandler = null PlaybackHub.commandHandler = null
@@ -0,0 +1,190 @@
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 = largeCover(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),
)
}
private val GOOGLE_IMAGE_SIZE = Regex("=(w\\d+-h\\d+|s\\d+)[^/=]*$")
private val YTIMG_SMALL = Regex("/(default|mqdefault)\\.jpg$")
/**
* 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 {
url.contains("googleusercontent.com") || url.contains("ggpht.com") ->
url.replace(GOOGLE_IMAGE_SIZE, "=w544-h544-l90-rj")
url.contains("ytimg.com") -> url.replace(YTIMG_SMALL, "/hqdefault.jpg")
else -> url
}
/** Textfeld ohne JSON-null ("null" als Text waere sonst sichtbar). */
private fun JSONObject?.text(key: String): String =
if (this == null || isNull(key)) "" else optString(key)
/** Sekunden -> "m:ss" bzw. "h:mm:ss". */
fun formatTime(seconds: Double): String {
val total = seconds.coerceAtLeast(0.0).toLong()
val h = total / 3600
val m = (total % 3600) / 60
val s = total % 60
return if (h > 0) "%d:%02d:%02d".format(h, m, s) else "%d:%02d".format(m, s)
}
/**
* Sucht Playtube-PCs im WLAN (blockiert bis [timeoutMs] - nicht auf dem Hauptthread aufrufen).
* Mehrere Antworten desselben PCs werden zusammengefasst.
*/
fun discover(timeoutMs: Int = 1500): List<PcDevice> {
val found = LinkedHashMap<String, PcDevice>()
try {
DatagramSocket().use { socket ->
socket.broadcast = true
socket.soTimeout = 300
val request = DISCOVERY_REQUEST.toByteArray()
val broadcast = InetAddress.getByName("255.255.255.255")
socket.send(DatagramPacket(request, request.size, broadcast, DISCOVERY_PORT))
val deadline = System.currentTimeMillis() + timeoutMs
val buffer = ByteArray(1024)
while (System.currentTimeMillis() < deadline) {
val packet = DatagramPacket(buffer, buffer.size)
try {
socket.receive(packet)
} catch (_: SocketTimeoutException) {
continue
}
val host = packet.address.hostAddress ?: continue
val text = String(packet.data, 0, packet.length, Charsets.UTF_8)
parseDiscoveryReply(text, host)?.let { found["${it.host}:${it.port}"] = it }
}
}
} catch (_: IOException) {
// Kein WLAN o.ae. -> leere Liste; die IP-Adresse laesst sich von Hand eingeben.
}
return found.values.toList()
}
/** Fehlermeldung des PCs (z.B. "Falscher Code"). */
class RemoteException(message: String) : IOException(message)
/** Eine offene Verbindung zum PC. Alle Aufrufe blockieren - nur auf einem Hintergrundthread nutzen. */
class Connection private constructor(private val socket: Socket) : Closeable {
private val reader: BufferedReader = socket.getInputStream().bufferedReader(Charsets.UTF_8)
private val writer: BufferedWriter = socket.getOutputStream().bufferedWriter(Charsets.UTF_8)
private var nextId = 1
/** Schickt eine Anfrage und wartet auf die Antwort mit derselben id. */
fun request(command: String, fill: JSONObject.() -> Unit = {}): JSONObject {
val id = nextId++
val message = JSONObject().put("id", id).put("cmd", command).apply(fill)
writer.write(message.toString())
writer.write("\n")
writer.flush()
while (true) {
val line = reader.readLine() ?: throw IOException("Verbindung getrennt")
val reply = try {
JSONObject(line)
} catch (_: Exception) {
continue
}
if (reply.optInt("id", -1) != id) continue
if (!reply.optBoolean("ok")) throw RemoteException(reply.optString("error", "Fehler"))
return reply
}
}
override fun close() {
try {
socket.close()
} catch (_: IOException) {
}
}
companion object {
fun open(device: PcDevice): Connection {
val socket = Socket()
try {
socket.connect(InetSocketAddress(device.host, device.port), CONNECT_TIMEOUT_MS)
socket.soTimeout = READ_TIMEOUT_MS
socket.tcpNoDelay = true
} catch (e: IOException) {
socket.close()
throw e
}
return Connection(socket)
}
}
}
}
@@ -0,0 +1,464 @@
package de.fojadrachi.playtube
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.InputFilter
import android.text.InputType
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ListView
import android.widget.SeekBar
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.atomic.AtomicBoolean
/**
* "PC steuern": findet Playtube auf dem PC im selben WLAN und steuert es wie eine Fernbedienung
* (Titel, Cover, Play/Pause, Spulen, Lautstaerke, Like, YouTube/YouTube Music). Protokoll siehe
* [PcRemote]. Gekoppelte PCs merkt sich die App (Token in den App-Einstellungen).
*/
class PcRemoteActivity : AppCompatActivity() {
private val main = Handler(Looper.getMainLooper())
/** Alle Netzwerkaufrufe an den PC laufen nacheinander auf diesem Thread. */
private val worker: ExecutorService = Executors.newSingleThreadExecutor()
/** Nur auf [worker] benutzen. */
@Volatile private var connection: PcRemote.Connection? = null
private val statusPending = AtomicBoolean(false)
private var device: PcDevice? = null
private var state = PcState.EMPTY
private var coverUrl = ""
private var draggingPosition = false
private var draggingVolume = false
private val devices = mutableListOf<PcDevice>()
private lateinit var status: TextView
private lateinit var devicePanel: View
private lateinit var playerPanel: View
private lateinit var deviceAdapter: ArrayAdapter<String>
private lateinit var cover: ImageView
private lateinit var trackTitle: TextView
private lateinit var trackSubtitle: TextView
private lateinit var positionBar: SeekBar
private lateinit var positionText: TextView
private lateinit var durationText: TextView
private lateinit var playPause: ImageButton
private lateinit var like: ImageButton
private lateinit var volumeBar: SeekBar
private lateinit var tabYoutube: Button
private lateinit var tabMusic: Button
private val pollLoop = object : Runnable {
override fun run() {
requestStatus()
main.postDelayed(this, POLL_INTERVAL_MS)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pc_remote)
keepContentBetweenSystemBars()
status = findViewById(R.id.remoteStatus)
devicePanel = findViewById(R.id.devicePanel)
playerPanel = findViewById(R.id.playerPanel)
cover = findViewById(R.id.cover)
trackTitle = findViewById(R.id.trackTitle)
trackSubtitle = findViewById(R.id.trackSubtitle)
positionBar = findViewById(R.id.positionBar)
positionText = findViewById(R.id.positionText)
durationText = findViewById(R.id.durationText)
playPause = findViewById(R.id.playPauseButton)
like = findViewById(R.id.likeButton)
volumeBar = findViewById(R.id.volumeBar)
tabYoutube = findViewById(R.id.tabYoutube)
tabMusic = findViewById(R.id.tabMusic)
deviceAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, mutableListOf())
findViewById<ListView>(R.id.deviceList).apply {
adapter = deviceAdapter
setOnItemClickListener { _, _, position, _ -> devices.getOrNull(position)?.let(::connect) }
}
findViewById<Button>(R.id.searchButton).setOnClickListener { search() }
findViewById<Button>(R.id.manualButton).setOnClickListener { askForAddress() }
findViewById<Button>(R.id.disconnectButton).setOnClickListener { disconnect() }
findViewById<ImageButton>(R.id.previousButton).setOnClickListener { send("previous") }
findViewById<ImageButton>(R.id.nextButton).setOnClickListener { send("next") }
playPause.setOnClickListener {
state = state.copy(playing = !state.playing) // sofort umschalten, der naechste Status bestaetigt
render()
send("play_pause")
}
like.setOnClickListener { send("like") }
tabYoutube.setOnClickListener { send("switch_tab", target = "youtube") }
tabMusic.setOnClickListener { send("switch_tab", target = "music") }
positionBar.setOnSeekBarChangeListener(object : SeekBarListener() {
override fun onStartTrackingTouch(bar: SeekBar) {
draggingPosition = true
}
override fun onProgressChanged(bar: SeekBar, progress: Int, fromUser: Boolean) {
if (fromUser) positionText.text = PcRemote.formatTime(progress.toDouble())
}
override fun onStopTrackingTouch(bar: SeekBar) {
draggingPosition = false
// Der PC spult relativ ("seek" = Sekunden vor/zurueck).
val delta = (bar.progress - state.position).coerceIn(-3600.0, 3600.0)
state = state.copy(position = bar.progress.toDouble())
send("seek", value = delta)
}
})
volumeBar.setOnSeekBarChangeListener(object : SeekBarListener() {
override fun onStartTrackingTouch(bar: SeekBar) {
draggingVolume = true
}
override fun onStopTrackingTouch(bar: SeekBar) {
draggingVolume = false
state = state.copy(volume = bar.progress)
send("set_volume", value = bar.progress.toDouble())
}
})
search()
}
override fun onStart() {
super.onStart()
if (device != null) main.post(pollLoop)
}
override fun onStop() {
main.removeCallbacks(pollLoop)
super.onStop()
}
override fun onDestroy() {
main.removeCallbacksAndMessages(null)
onWorker { closeConnection() }
worker.shutdown()
super.onDestroy()
}
private fun keepContentBetweenSystemBars() {
val root = findViewById<View>(R.id.remoteRoot)
val base = root.paddingLeft
ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets ->
val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
view.setPadding(base + bars.left, base + bars.top, base + bars.right, base + bars.bottom)
WindowInsetsCompat.CONSUMED
}
}
// ------------------------------------------------------------------ PCs finden
private fun search() {
status.setText(R.string.pc_searching)
Thread {
val found = PcRemote.discover()
main.post {
if (isFinishing) return@post
devices.clear()
devices.addAll(found)
deviceAdapter.clear()
deviceAdapter.addAll(found.map { "${it.name}\n${it.host}" })
status.setText(if (found.isEmpty()) R.string.pc_none_found else R.string.pc_found)
}
}.start()
}
private fun askForAddress() {
val input = EditText(this).apply {
hint = getString(R.string.pc_manual_hint)
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
setText(prefs().getString(KEY_LAST_HOST, ""))
}
AlertDialog.Builder(this)
.setTitle(R.string.pc_manual)
.setView(padded(input))
.setPositiveButton(R.string.pc_connect) { _, _ ->
val host = input.text.toString().trim()
if (host.isNotEmpty()) {
connect(PcDevice(prefs().getString(KEY_NAME_FOR + host, null) ?: host, host))
}
}
.setNegativeButton(R.string.pc_cancel, null)
.show()
}
// ------------------------------------------------------------------ Verbinden / Koppeln
private fun connect(target: PcDevice) {
val token = prefs().getString(KEY_TOKEN_FOR + target.name, null)
if (token == null) {
askForCode(target)
return
}
status.text = getString(R.string.pc_connecting, target.name)
onWorker {
try {
closeConnection()
val conn = PcRemote.Connection.open(target)
val reply = try {
conn.request("hello") { put("token", token) }
} catch (e: IOException) {
conn.close()
throw e
}
connection = conn
main.post { onConnected(target, reply.optString("name")) }
} catch (e: PcRemote.RemoteException) {
// Kopplung am PC entfernt -> neu koppeln.
main.post {
prefs().edit().remove(KEY_TOKEN_FOR + target.name).apply()
askForCode(target)
}
} catch (e: IOException) {
main.post { status.text = getString(R.string.pc_error, e.message ?: e.javaClass.simpleName) }
}
}
}
private fun askForCode(target: PcDevice) {
val input = EditText(this).apply {
hint = getString(R.string.pc_pair_hint)
inputType = InputType.TYPE_CLASS_NUMBER
filters = arrayOf(InputFilter.LengthFilter(6))
}
AlertDialog.Builder(this)
.setTitle(getString(R.string.pc_pair_title, target.name))
.setMessage(R.string.pc_pair_message)
.setView(padded(input))
.setPositiveButton(R.string.pc_pair) { _, _ -> pair(target, input.text.toString().trim()) }
.setNegativeButton(R.string.pc_cancel, null)
.show()
}
private fun pair(target: PcDevice, code: String) {
status.text = getString(R.string.pc_connecting, target.name)
onWorker {
try {
closeConnection()
val conn = PcRemote.Connection.open(target)
val reply = try {
conn.request("pair") {
put("code", code)
put("device", Build.MODEL ?: "Android")
}
} catch (e: IOException) {
conn.close()
throw e
}
connection = conn
val token = reply.optString("token")
main.post {
prefs().edit().putString(KEY_TOKEN_FOR + target.name, token).apply()
onConnected(target, reply.optString("name"))
}
} catch (e: IOException) {
main.post { status.text = getString(R.string.pc_error, e.message ?: e.javaClass.simpleName) }
}
}
}
private fun onConnected(target: PcDevice, reportedName: String) {
// Der PC meldet seinen Namen - unter dem merken wir uns Token und Adresse.
val name = reportedName.ifBlank { target.name }
val token = prefs().getString(KEY_TOKEN_FOR + target.name, null)
prefs().edit().apply {
if (token != null) putString(KEY_TOKEN_FOR + name, token)
putString(KEY_NAME_FOR + target.host, name)
putString(KEY_LAST_HOST, target.host)
}.apply()
device = target.copy(name = name)
status.text = getString(R.string.pc_connected, name)
devicePanel.visibility = View.GONE
playerPanel.visibility = View.VISIBLE
main.removeCallbacks(pollLoop)
main.post(pollLoop)
}
private fun disconnect() {
main.removeCallbacks(pollLoop)
onWorker { closeConnection() }
device = null
state = PcState.EMPTY
coverUrl = ""
cover.setImageDrawable(null)
playerPanel.visibility = View.GONE
devicePanel.visibility = View.VISIBLE
search()
}
private fun onConnectionLost() {
val name = device?.name ?: return
disconnect()
status.text = getString(R.string.pc_lost, name)
}
/** Fuehrt [block] auf [worker] aus - nach dem Schliessen der Activity nicht mehr. */
private fun onWorker(block: () -> Unit) {
try {
worker.execute(block)
} catch (_: RejectedExecutionException) {
}
}
/** Nur auf [worker] aufrufen. */
private fun closeConnection() {
connection?.close()
connection = null
}
// ------------------------------------------------------------------ Befehle und Stand
private fun requestStatus() {
// Bei langsamem WLAN nicht eine Abfrage pro Sekunde aufstauen.
if (!statusPending.compareAndSet(false, true)) return
onWorker {
try {
val conn = connection ?: return@onWorker
val next = PcRemote.parseState(conn.request("status")) ?: return@onWorker
main.post {
if (device == null) return@post
state = next
render()
}
} catch (_: IOException) {
closeConnection()
main.post { onConnectionLost() }
} finally {
statusPending.set(false)
}
}
}
private fun send(command: String, target: String = "auto", value: Double? = null) {
onWorker {
val conn = connection ?: return@onWorker
try {
conn.request(command) {
put("target", target)
if (value != null) put("value", value)
}
} catch (_: PcRemote.RemoteException) {
// Befehl abgelehnt (z.B. nichts geladen) - Verbindung bleibt.
} catch (_: IOException) {
closeConnection()
main.post { onConnectionLost() }
return@onWorker
}
main.post { requestStatus() }
}
}
private fun render() {
trackTitle.text = state.title.ifBlank { getString(R.string.pc_nothing_playing) }
trackSubtitle.text = state.subtitle
playPause.setImageResource(
if (state.playing) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play,
)
playPause.contentDescription = getString(if (state.playing) R.string.action_pause else R.string.action_play)
val duration = state.duration.toInt().coerceAtLeast(0)
positionBar.max = duration
positionBar.isEnabled = duration > 0
durationText.text = PcRemote.formatTime(state.duration)
if (!draggingPosition) {
positionBar.progress = state.position.toInt().coerceIn(0, duration)
positionText.text = PcRemote.formatTime(state.position)
}
if (!draggingVolume) volumeBar.progress = state.volume
val likeColor = if (state.liked) R.color.brand_to else R.color.text_muted
like.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(this, likeColor))
tabYoutube.alpha = if (state.visibleTab == "youtube") 1f else 0.5f
tabMusic.alpha = if (state.visibleTab == "music") 1f else 0.5f
if (state.thumbnail != coverUrl) loadCover(state.thumbnail)
}
private fun loadCover(url: String) {
coverUrl = url
if (url.isEmpty()) {
cover.setImageDrawable(null)
return
}
Thread {
val bitmap = downloadBitmap(url)
main.post { if (coverUrl == url) cover.setImageBitmap(bitmap) }
}.start()
}
private fun downloadBitmap(url: String): Bitmap? =
try {
val connection = URL(url).openConnection() as HttpURLConnection
connection.connectTimeout = 8_000
connection.readTimeout = 8_000
try {
connection.inputStream.use(BitmapFactory::decodeStream)
} finally {
connection.disconnect()
}
} catch (_: Exception) {
null
}
// ------------------------------------------------------------------ Hilfen
private fun prefs() = getSharedPreferences(PREFS, Context.MODE_PRIVATE)
private fun padded(view: View): View =
LinearLayout(this).apply {
val pad = (20 * resources.displayMetrics.density).toInt()
setPadding(pad, pad / 2, pad, 0)
addView(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
}
/** SeekBar-Listener mit leeren Standardmethoden. */
private open class SeekBarListener : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(bar: SeekBar, progress: Int, fromUser: Boolean) {}
override fun onStartTrackingTouch(bar: SeekBar) {}
override fun onStopTrackingTouch(bar: SeekBar) {}
}
companion object {
private const val POLL_INTERVAL_MS = 1000L
private const val PREFS = "pc_remote"
private const val KEY_TOKEN_FOR = "token:"
private const val KEY_NAME_FOR = "name:"
private const val KEY_LAST_HOST = "last_host"
fun start(context: Context) {
context.startActivity(Intent(context, PcRemoteActivity::class.java))
}
}
}
@@ -84,6 +84,7 @@ class PlaybackService : Service() {
PlaybackHub.listener = null PlaybackHub.listener = null
main.removeCallbacksAndMessages(null) main.removeCallbacksAndMessages(null)
releaseWakeLock() releaseWakeLock()
DiscordPresence.shutdown()
session.release() session.release()
super.onDestroy() super.onDestroy()
} }
@@ -113,6 +114,7 @@ class PlaybackService : Service() {
manager.notify(NOTIFICATION_ID, buildNotification(info)) manager.notify(NOTIFICATION_ID, buildNotification(info))
} }
if (info.playing) acquireWakeLock() else releaseWakeLock() if (info.playing) acquireWakeLock() else releaseWakeLock()
DiscordPresence.update(PresencePlan.from(info, System.currentTimeMillis()))
} }
private fun playbackState(info: NowPlaying): PlaybackStateCompat { private fun playbackState(info: NowPlaying): PlaybackStateCompat {
@@ -0,0 +1,40 @@
package de.fojadrachi.playtube
import kotlin.math.abs
/** Was in Discord als "Hoert gerade" angezeigt werden soll. */
data class PresencePlan(
val details: String,
val state: String,
val artworkUrl: String?,
/** Beginn/Ende in ms seit 1970; ergibt in Discord den Fortschrittsbalken. 0 = unbekannt. */
val startMs: Long,
val endMs: Long,
) {
/** Gleicher Inhalt wie [other]? Ein verschobener Startzeitpunkt (Spulen) zaehlt als Aenderung. */
fun sameAs(other: PresencePlan?): Boolean =
other != null &&
details == other.details && state == other.state && artworkUrl == other.artworkUrl &&
abs(startMs - other.startMs) <= SEEK_TOLERANCE_MS
companion object {
/** Schwankung des Startzeitpunkts durch die 1,5-s-Abfrage, die noch kein Spulen ist. */
const val SEEK_TOLERANCE_MS = 4_000L
/** Discord akzeptiert Bildadressen nur bis 300 Zeichen. */
const val MAX_IMAGE_URL_LENGTH = 300
/** null = nichts anzeigen (nichts laeuft oder Pause). */
fun from(info: NowPlaying, nowMs: Long): PresencePlan? {
if (!info.hasTrack || !info.playing) return null
val start = nowMs - info.positionMs
return PresencePlan(
details = info.title,
state = info.artist,
artworkUrl = info.artworkUrl?.takeIf { it.length <= MAX_IMAGE_URL_LENGTH },
startMs = start,
endMs = if (info.durationMs > 0) start + info.durationMs else 0L,
)
}
}
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<gradient
android:angle="135"
android:endColor="@color/brand_to"
android:startColor="@color/brand_from" />
</shape>
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Daumen hoch (Material "thumb_up"). Farbe setzt PcRemoteActivity je nach Like-Status. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M1,21h4L5,9L1,9v12zM23,10c0,-1.1 -0.9,-2 -2,-2h-6.31l0.95,-4.57 0.03,-0.32c0,-0.41 -0.17,-0.79 -0.44,-1.06L14.17,1 7.59,7.59C7.22,7.95 7,8.45 7,9v10c0,1.1 0.9,2 2,2h9c0.83,0 1.54,-0.5 1.84,-1.22l3.02,-7.05c0.09,-0.23 0.14,-0.47 0.14,-0.73v-2z" />
</vector>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Bildschirm mit Wellen (Material "cast"): "Auf dem PC steuern". -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M21,3L3,3c-1.1,0 -2,0.9 -2,2v3h2L3,5h18v14h-7v2h7c1.1,0 2,-0.9 2,-2L23,5c0,-1.1 -0.9,-2 -2,-2zM1,18v3h3c0,-1.66 -1.34,-3 -3,-3zM1,14v2c2.76,0 5,2.24 5,5h2c0,-3.87 -3.13,-7 -7,-7zM1,10v2c4.97,0 9,4.03 9,9h2c0,-6.08 -4.93,-11 -11,-11z" />
</vector>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Icon der Verknuepfung "PC steuern": weisses Symbol auf dem Playtube-Verlauf. -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_play_button" />
<item
android:bottom="12dp"
android:drawable="@drawable/ic_pc_remote"
android:left="12dp"
android:right="12dp"
android:top="12dp" />
</layer-list>
+17 -1
View File
@@ -1,8 +1,9 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent" android:layout_height="match_parent"
android:background="@color/background"> android:background="@color/system_bars">
<WebView <WebView
android:id="@+id/webView" android:id="@+id/webView"
@@ -18,4 +19,19 @@
android:max="100" android:max="100"
android:progressTint="@color/brand_to" android:progressTint="@color/brand_to"
android:visibility="gone" /> android:visibility="gone" />
<!-- "PC steuern" (PcRemoteActivity). Am rechten Rand mittig: dort liegen bei YouTube Music
keine festen Bedienelemente (oben Kopfzeile, unten Player und Navigation). -->
<ImageButton
android:id="@+id/pcRemoteButton"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_gravity="end|center_vertical"
android:layout_marginEnd="6dp"
android:alpha="0.85"
android:background="@drawable/bg_play_button"
android:contentDescription="@string/pc_open"
android:padding="10dp"
android:scaleType="fitCenter"
android:src="@drawable/ic_pc_remote" />
</FrameLayout> </FrameLayout>
@@ -0,0 +1,244 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/remoteRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:id="@+id/remoteHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/pc_title"
android:textColor="@color/text"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="@+id/remoteStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:textColor="@color/text_muted"
android:textSize="14sp" />
<!-- Geraeteliste: PCs im WLAN -->
<LinearLayout
android:id="@+id/devicePanel"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:orientation="vertical">
<ListView
android:id="@+id/deviceList"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="@color/surface"
android:dividerHeight="1dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="@string/pc_hint"
android:textColor="@color/text_muted"
android:textSize="13sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:orientation="horizontal">
<Button
android:id="@+id/searchButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/pc_search" />
<Button
android:id="@+id/manualButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="@string/pc_manual" />
</LinearLayout>
</LinearLayout>
<!-- Fernbedienung fuer den verbundenen PC -->
<LinearLayout
android:id="@+id/playerPanel"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical"
android:visibility="gone">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/tabYoutube"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="YouTube" />
<Button
android:id="@+id/tabMusic"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_weight="1"
android:text="YouTube Music" />
</LinearLayout>
<ImageView
android:id="@+id/cover"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:layout_weight="1"
android:adjustViewBounds="true"
android:contentDescription="@string/pc_cover"
android:scaleType="fitCenter" />
<TextView
android:id="@+id/trackTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ellipsize="end"
android:maxLines="2"
android:textColor="@color/text"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="@+id/trackSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textColor="@color/text_muted"
android:textSize="15sp" />
<SeekBar
android:id="@+id/positionBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:progressTint="@color/brand_to"
android:thumbTint="@color/brand_to" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/positionText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="@color/text_muted"
android:textSize="12sp" />
<TextView
android:id="@+id/durationText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/text_muted"
android:textSize="12sp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="@+id/likeButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/pc_like"
android:src="@drawable/ic_like" />
<ImageButton
android:id="@+id/previousButton"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_marginStart="12dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/action_previous"
android:src="@android:drawable/ic_media_previous" />
<ImageButton
android:id="@+id/playPauseButton"
android:layout_width="72dp"
android:layout_height="72dp"
android:layout_marginStart="12dp"
android:layout_marginEnd="12dp"
android:background="@drawable/bg_play_button"
android:contentDescription="@string/action_play"
android:src="@android:drawable/ic_media_play" />
<ImageButton
android:id="@+id/nextButton"
android:layout_width="56dp"
android:layout_height="56dp"
android:background="?attr/selectableItemBackgroundBorderless"
android:contentDescription="@string/action_next"
android:src="@android:drawable/ic_media_next" />
<View
android:layout_width="60dp"
android:layout_height="1dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:contentDescription="@string/pc_volume"
android:src="@android:drawable/ic_lock_silent_mode_off"
android:tint="@color/text_muted" />
<SeekBar
android:id="@+id/volumeBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:max="100"
android:progressTint="@color/brand_from"
android:thumbTint="@color/brand_from" />
</LinearLayout>
<Button
android:id="@+id/disconnectButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="@string/pc_disconnect" />
</LinearLayout>
</LinearLayout>
+33 -2
View File
@@ -13,14 +13,45 @@
<string name="update_download">Herunterladen</string> <string name="update_download">Herunterladen</string>
<string name="update_later">Später</string> <string name="update_later">Später</string>
<!-- PC steuern (PcRemoteActivity) -->
<string name="pc_title">PC steuern</string>
<string name="pc_shortcut">PC steuern</string>
<string name="pc_open">Playtube auf dem PC steuern</string>
<string name="pc_searching">Suche Playtube-PCs im WLAN …</string>
<string name="pc_found">Tippe auf einen PC, um ihn zu steuern.</string>
<string name="pc_none_found">Kein PC gefunden.</string>
<string name="pc_hint">Am PC in Playtube unter Einstellungen › „Steuerung vom Handy“ einschalten. Handy und PC müssen im selben WLAN sein.</string>
<string name="pc_search">Erneut suchen</string>
<string name="pc_manual">IP-Adresse eingeben</string>
<string name="pc_manual_hint">z. B. 192.168.178.20</string>
<string name="pc_connect">Verbinden</string>
<string name="pc_cancel">Abbrechen</string>
<string name="pc_pair_title">Mit %1$s koppeln</string>
<string name="pc_pair_message">Am PC in Playtube unter Einstellungen › „Steuerung vom Handy“ auf „Handy koppeln“ tippen und den 6-stelligen Code hier eingeben.</string>
<string name="pc_pair_hint">Code</string>
<string name="pc_pair">Koppeln</string>
<string name="pc_connecting">Verbinde mit %1$s …</string>
<string name="pc_connected">Verbunden mit %1$s</string>
<string name="pc_error">Verbindung fehlgeschlagen: %1$s</string>
<string name="pc_lost">Verbindung zu %1$s verloren.</string>
<string name="pc_nothing_playing">Gerade läuft nichts</string>
<string name="pc_disconnect">Trennen</string>
<string name="pc_cover">Cover</string>
<string name="pc_like">Gefällt mir</string>
<string name="pc_volume">Lautstärke</string>
<color name="background">#0F0F0F</color> <color name="background">#0F0F0F</color>
<color name="surface">#1F1F1F</color>
<color name="text">#FFFFFF</color>
<color name="text_muted">#AAAAAA</color>
<color name="system_bars">#000000</color>
<color name="brand_from">#7C3AED</color> <color name="brand_from">#7C3AED</color>
<color name="brand_to">#EC4899</color> <color name="brand_to">#EC4899</color>
<style name="Theme.Playtube" parent="Theme.AppCompat.NoActionBar"> <style name="Theme.Playtube" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@color/background</item> <item name="android:windowBackground">@color/background</item>
<item name="android:statusBarColor">@color/background</item> <item name="android:statusBarColor">@color/system_bars</item>
<item name="android:navigationBarColor">@color/background</item> <item name="android:navigationBarColor">@color/system_bars</item>
<item name="colorPrimary">@color/brand_from</item> <item name="colorPrimary">@color/brand_from</item>
<item name="colorAccent">@color/brand_to</item> <item name="colorAccent">@color/brand_to</item>
</style> </style>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
android:enabled="true"
android:icon="@drawable/ic_shortcut_pc_remote"
android:shortcutId="pc_remote"
android:shortcutShortLabel="@string/pc_shortcut">
<intent
android:action="android.intent.action.VIEW"
android:targetClass="de.fojadrachi.playtube.PcRemoteActivity"
android:targetPackage="de.fojadrachi.playtube" />
</shortcut>
</shortcuts>
@@ -0,0 +1,95 @@
package de.fojadrachi.playtube
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class PcRemoteTest {
@Test
fun parsesDiscoveryReply() {
val device = PcRemote.parseDiscoveryReply(
"""{"service": "playtube", "protocol": 1, "name": "MEIN-PC", "port": 47811}""",
"192.168.1.20",
)
assertEquals(PcDevice("MEIN-PC", "192.168.1.20", 47811), device)
}
@Test
fun ignoresForeignOrBrokenDiscoveryReplies() {
assertNull(PcRemote.parseDiscoveryReply("""{"service": "other", "port": 1}""", "1.2.3.4"))
assertNull(PcRemote.parseDiscoveryReply("""{"service": "playtube", "port": 70000}""", "1.2.3.4"))
assertNull(PcRemote.parseDiscoveryReply("kein json", "1.2.3.4"))
}
@Test
fun usesHostWhenNameIsMissing() {
val device = PcRemote.parseDiscoveryReply("""{"service": "playtube"}""", "10.0.0.2")
assertEquals(PcDevice("10.0.0.2", "10.0.0.2", PcRemote.DEFAULT_PORT), device)
}
@Test
fun parsesStateOfTheActiveTab() {
val reply = JSONObject(
"""
{"id": 3, "ok": true, "state": {
"protocol": 1, "visibleTab": "youtube", "activeTab": "music",
"tabs": {
"youtube": null,
"music": {"title": "Song", "subtitle": "Artist", "thumbnail": "https://i.ytimg.com/x.jpg",
"playing": true, "currentTime": 61.5, "duration": 200, "volume": 42,
"likeStatus": "LIKE"}
}}}
""".trimIndent(),
)
val state = PcRemote.parseState(reply)!!
assertEquals("music", state.activeTab)
assertEquals("youtube", state.visibleTab)
assertEquals("Song", state.title)
assertEquals("Artist", state.subtitle)
assertEquals("https://i.ytimg.com/x.jpg", state.thumbnail)
assertTrue(state.playing)
assertEquals(61.5, state.position, 0.001)
assertEquals(200.0, state.duration, 0.001)
assertEquals(42, state.volume)
assertTrue(state.liked)
}
@Test
fun handlesEmptyTabsAndNulls() {
val reply = JSONObject(
"""{"ok": true, "state": {"activeTab": "youtube", "tabs": {"youtube": {"title": null,
"thumbnail": "http://unsicher", "currentTime": null}, "music": null}}}""",
)
val state = PcRemote.parseState(reply)!!
assertEquals("", state.title)
assertEquals("", state.thumbnail)
assertEquals(0.0, state.position, 0.001)
assertFalse(state.playing)
assertNull(PcRemote.parseState(JSONObject("""{"ok": true}""")))
}
@Test
fun requestsLargeCovers() {
assertEquals(
"https://lh3.googleusercontent.com/abc=w544-h544-l90-rj",
PcRemote.largeCover("https://lh3.googleusercontent.com/abc=w60-h60-l90-rj"),
)
assertEquals(
"https://yt3.ggpht.com/xyz=w544-h544-l90-rj",
PcRemote.largeCover("https://yt3.ggpht.com/xyz=s88-c-k-c0x00ffffff-no-rj"),
)
assertEquals("https://i.ytimg.com/vi/id/hqdefault.jpg", PcRemote.largeCover("https://i.ytimg.com/vi/id/default.jpg"))
assertEquals("https://i.ytimg.com/vi/id/hqdefault.jpg", PcRemote.largeCover("https://i.ytimg.com/vi/id/hqdefault.jpg"))
assertEquals("https://example.com/a.png", PcRemote.largeCover("https://example.com/a.png"))
}
@Test
fun formatsTimes() {
assertEquals("0:00", PcRemote.formatTime(-5.0))
assertEquals("1:05", PcRemote.formatTime(65.9))
assertEquals("1:01:01", PcRemote.formatTime(3661.0))
}
}
@@ -0,0 +1,48 @@
package de.fojadrachi.playtube
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class PresencePlanTest {
private val now = 1_800_000_000_000L
private val playing = NowPlaying("Song", "Band", "https://i.ytimg.com/a.jpg", true, 30_000L, 200_000L)
@Test
fun `laufender Titel ergibt Details, Interpret, Cover und Zeitraum`() {
val plan = PresencePlan.from(playing, now)!!
assertEquals("Song", plan.details)
assertEquals("Band", plan.state)
assertEquals("https://i.ytimg.com/a.jpg", plan.artworkUrl)
assertEquals(now - 30_000L, plan.startMs)
assertEquals(now - 30_000L + 200_000L, plan.endMs)
}
@Test
fun `Pause und leerer Player zeigen nichts an`() {
assertNull(PresencePlan.from(playing.copy(playing = false), now))
assertNull(PresencePlan.from(NowPlaying.EMPTY, now))
}
@Test
fun `unbekannte Laenge ergibt kein Ende`() {
assertEquals(0L, PresencePlan.from(playing.copy(durationMs = 0L), now)!!.endMs)
}
@Test
fun `normales Weiterlaufen ist keine Aenderung`() {
val first = PresencePlan.from(playing, now)!!
val later = PresencePlan.from(playing.copy(positionMs = 31_800L), now + 1_500L)!!
assertTrue(later.sameAs(first))
}
@Test
fun `Spulen, neuer Titel und null sind Aenderungen`() {
val first = PresencePlan.from(playing, now)!!
assertFalse(PresencePlan.from(playing.copy(positionMs = 120_000L), now + 1_500L)!!.sameAs(first))
assertFalse(PresencePlan.from(playing.copy(title = "Anderer"), now)!!.sameAs(first))
assertFalse(first.sameAs(null))
}
}
+8 -14
View File
@@ -1,17 +1,11 @@
## Playtube für Android – YouTube Music mit Hintergrundwiedergabe ## Playtube für Android 1.2.1
Die Android-Version von Playtube: **nur YouTube Music**, ohne YouTube-Tab, Discord und - **Korrektur „PC steuern“:** Cover werden jetzt scharf angezeigt. Bisher kam bei YouTube Music oft nur
Stream-Dock-Fernsteuerung. das 60×60-Pixel-Vorschaubild aus der Player-Leiste an und wirkte stark verpixelt.
- Musik läuft im Hintergrund und bei ausgeschaltetem Bildschirm weiter. Neu seit 1.2.0: **PC steuern** (wie Spotify Connect) – Playtube auf dem PC im selben WLAN fernbedienen.
- Medien-Benachrichtigung und Sperrbildschirm-Steuerung mit Titel, Interpret und Cover. Am PC Playtube 2.0.0 oder neuer unter *Einstellungen › Steuerung vom Handy* einschalten, speichern,
- **Eigene, hochgeladene Songs** lassen sich abspielen. „Handy koppeln“ wählen und den Code in der App eingeben.
- Updates über diese Releases (Tag `…-android`), kein GitHub, kein Play Store.
### Installieren Alles Weitere wie bisher: nur YouTube Music, Hintergrundwiedergabe, Sperrbildschirm-Steuerung,
1. `Playtube-Android-vX.Y.Z.apk` herunterladen und öffnen. Discord Rich Presence, Updates über diese Releases. Voraussetzung: Android 8.0 oder neuer.
2. Einmalig „Unbekannte Apps installieren" für den Browser/Dateimanager erlauben.
3. Beim ersten Start Benachrichtigungen erlauben.
Voraussetzung: Android 8.0 oder neuer. Bei Akku-Optimierung des Herstellers Playtube ausnehmen,
sonst kann Android die Hintergrundwiedergabe beenden.