commit f76ceb3c755866a32bea01a2215e3a54ca8c3445 Author: fojadrachi Date: Sun Sep 27 02:07:38 2026 +0200 feat: Playtube fuer Android - nur YouTube Music, Hintergrundwiedergabe, Updates ueber Gitea diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6dedb83 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +.gradle/ +build/ +.idea/ +*.iml +local.properties +*.log +# Signierschluessel und Passwoerter gehoeren NIE ins Repo (siehe README "Release bauen") +keystore/ +*.jks +*.keystore +keystore.properties diff --git a/README.md b/README.md new file mode 100644 index 0000000..c8b6ae7 --- /dev/null +++ b/README.md @@ -0,0 +1,86 @@ +# Playtube für Android + +Android-Version von [Playtube](https://git.fojadrachi.de/Fojadrachi/Playtube) – **nur YouTube Music**, +mit Hintergrundwiedergabe. Ohne YouTube-Tab, ohne Discord und ohne Stream-Dock-Fernsteuerung. + +- **YouTube Music in der App** (`music.youtube.com` in einer WebView), Anmeldung mit deinem + Google-Konto, Login bleibt gespeichert. +- **Eigene, hochgeladene Songs** laufen (Android-WebView spielt AAC ab – anders als die + Qt-Variante von Playtube auf dem Desktop). +- **Hintergrundwiedergabe** über einen Vordergrunddienst: Musik läuft bei ausgeschaltetem + Bildschirm und in anderen Apps weiter. +- **Medien-Benachrichtigung und Sperrbildschirm** mit Titel, Interpret, Cover, Vorheriger / + Play-Pause / Nächster und Spulen; Kopfhörer-Tasten funktionieren. +- **Links** zu `music.youtube.com` öffnen sich in Playtube. +- **Updates** aus den eigenen Releases (Tag `vX.Y.Z-android`), kein GitHub, kein Play Store. + +Voraussetzungen: Android 8.0 (API 26) oder neuer, aktuelles „Android System WebView"/Chrome. + +## Installieren + +1. Auf der [Releases-Seite](https://git.fojadrachi.de/Fojadrachi/Playtube/releases) das Release + `Playtube Android vX.Y.Z-android` öffnen und `Playtube-Android-vX.Y.Z.apk` laden. +2. APK öffnen; Android fragt einmalig, ob dein Browser/Dateimanager Apps installieren darf + („Unbekannte Apps installieren") – erlauben. +3. Beim ersten Start Benachrichtigungen erlauben (für die Steuerung auf dem Sperrbildschirm). + +Bei Akku-Optimierung des Herstellers (Xiaomi, Samsung, …) Playtube dort von der Optimierung +ausnehmen, sonst beendet Android die Hintergrundwiedergabe manchmal. + +## Bauen + +Benötigt JDK 17+ und das Android SDK (Plattform 36, Build-Tools 36); der Pfad steht in +`local.properties` (`sdk.dir=…`, wird von Android Studio bzw. von Hand angelegt, nicht im Repo). + +```powershell +.\gradlew.bat :app:testDebugUnitTest # Unit-Tests +.\gradlew.bat :app:assembleDebug # Test-APK: app\build\outputs\apk\debug\ +``` + +## Release bauen und veröffentlichen + +Releases müssen mit **immer demselben Schlüssel** signiert sein, sonst lässt sich eine Version nicht +über die vorherige installieren. Der Schlüssel liegt nur bei dir, **nicht im Repo**: + +```powershell +powershell -ExecutionPolicy Bypass -File scripts\build-release.ps1 +``` + +Das Skript legt beim ersten Mal `keystore\playtube.jks` samt `keystore.properties` an (beides in +`.gitignore`) und baut `app\build\outputs\apk\release\Playtube-Android-vX.Y.Z.apk`. **Sichere den +Ordner `keystore\` an einem zweiten Ort** – ohne ihn lässt sich die App nie wieder aktualisieren. + +Hochladen als Vorabversion auf dein Gitea (Token wie in der Desktop-Version, siehe +`scripts\publish_release.ps1`): + +```powershell +powershell -ExecutionPolicy Bypass -File scripts\publish_release.ps1 -Tag v1.0.0-android -Prerelease ` + -Title "Playtube Android v1.0.0-android" -NotesFile scripts\release_notes.md ` + -Files app\build\outputs\apk\release\Playtube-Android-v1.0.0.apk +``` + +Das Release ist eine Vorabversion mit Tag `-android`; die Desktop-Versionen von Playtube ignorieren +es, und der Updater der App ignoriert deren Releases. + +## Aufbau + +| Datei | Aufgabe | +|---|---| +| `MainActivity.kt` | WebView mit YouTube Music, Anmeldung, Links, Update-Hinweis | +| `PlaybackService.kt` | Vordergrunddienst: Benachrichtigung, MediaSession, Wachhalten | +| `PlaybackHub.kt` | Verbindung Activity ↔ Dienst (Stand und Befehle) | +| `MediaScripts.kt` | JavaScript für Stand (Titel, Cover, Zeit) und Steuerung | +| `NowPlaying.kt` | Datensatz „läuft gerade" | +| `UpdateChecker.kt` | Update-Prüfung über die Gitea-Releases | +| `UserAgent.kt` | macht die WebView-Kennung zu einer normalen Chrome-Kennung (Google-Anmeldung) | + +## Bekannte Grenzen + +- Google kann die Anmeldung in eingebetteten Browsern blockieren. Die App verbirgt dafür die + 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 + geteilt wird. +- Wischt du die App aus der Liste der letzten Apps, endet die Wiedergabe (die WebView gehört zur + App-Aktivität). +- Kein Like-/Wiederholen-/Zufalls-Knopf in der Benachrichtigung; die Bedienung der Seite selbst + funktioniert normal. diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..ce7eee9 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,71 @@ +import java.util.Properties + +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +// Signierdaten liegen lokal in keystore.properties (nicht im Repo, siehe README). +val keystoreProperties = Properties().apply { + val file = rootProject.file("keystore.properties") + if (file.exists()) file.inputStream().use { load(it) } +} + +android { + namespace = "de.fojadrachi.playtube" + compileSdk = 36 + + defaultConfig { + applicationId = "de.fojadrachi.playtube" + minSdk = 26 + targetSdk = 36 + versionCode = 1 + versionName = "1.0.0" + + // Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play). + buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"") + buildConfigField("String", "REPO_SLUG", "\"Fojadrachi/Playtube\"") + } + + signingConfigs { + if (keystoreProperties.containsKey("storeFile")) { + create("release") { + storeFile = rootProject.file(keystoreProperties.getProperty("storeFile")) + storePassword = keystoreProperties.getProperty("storePassword") + keyAlias = keystoreProperties.getProperty("keyAlias") + keyPassword = keystoreProperties.getProperty("keyPassword") + } + } + } + + buildTypes { + release { + isMinifyEnabled = false + signingConfigs.findByName("release")?.let { signingConfig = it } + } + } + + buildFeatures { + buildConfig = true + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + kotlinOptions { + jvmTarget = "17" + } +} + +dependencies { + implementation("androidx.core:core-ktx:1.15.0") + implementation("androidx.appcompat:appcompat:1.7.0") + implementation("androidx.webkit:webkit:1.12.1") + implementation("androidx.media:media:1.7.0") + + testImplementation("junit:junit:4.13.2") + // Auf der JVM sind die org.json-Klassen von Android nur Attrappen - echte Bibliothek fuer Tests. + testImplementation("org.json:json:20240303") +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6f34877 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/de/fojadrachi/playtube/MainActivity.kt b/app/src/main/java/de/fojadrachi/playtube/MainActivity.kt new file mode 100644 index 0000000..d07b324 --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/MainActivity.kt @@ -0,0 +1,209 @@ +package de.fojadrachi.playtube + +import android.Manifest +import android.annotation.SuppressLint +import android.content.Intent +import android.content.pm.PackageManager +import android.graphics.Bitmap +import android.net.Uri +import android.os.Build +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.view.View +import android.webkit.CookieManager +import android.webkit.PermissionRequest +import android.webkit.WebChromeClient +import android.webkit.WebResourceRequest +import android.webkit.WebView +import android.webkit.WebViewClient +import android.widget.ProgressBar +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.webkit.WebSettingsCompat +import androidx.webkit.WebViewCompat +import androidx.webkit.WebViewFeature + +/** Playtube fuer Android: YouTube Music in einer WebView, mit Hintergrundwiedergabe. */ +class MainActivity : AppCompatActivity() { + private lateinit var webView: WebView + private lateinit var progress: ProgressBar + private val handler = Handler(Looper.getMainLooper()) + + private val probeLoop = object : Runnable { + override fun run() { + probe() + handler.postDelayed(this, PROBE_INTERVAL_MS) + } + } + + private val notificationPermission = + registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* ohne Erlaubnis: nur keine Benachrichtigung */ } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + webView = findViewById(R.id.webView) + progress = findViewById(R.id.progress) + + configureWebView() + onBackPressedDispatcher.addCallback( + this, + object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + // Zurueck navigiert in der Seite; ganz vorn geht die App in den Hintergrund (Musik laeuft weiter). + if (webView.canGoBack()) webView.goBack() else moveTaskToBack(true) + } + }, + ) + + PlaybackHub.commandHandler = { command -> + runOnUiThread { webView.evaluateJavascript(MediaScripts.forCommand(command), null) } + } + requestNotificationPermission() + PlaybackService.start(this) + + webView.loadUrl(startUrl(intent)) + handler.post(probeLoop) + checkForUpdate() + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + intent.data?.takeIf(::isMusicLink)?.let { webView.loadUrl(it.toString()) } + } + + override fun onPause() { + // WebView bewusst NICHT pausieren (webView.onPause()), sonst stoppt die Musik im Hintergrund. + CookieManager.getInstance().flush() + super.onPause() + } + + override fun onDestroy() { + handler.removeCallbacksAndMessages(null) + PlaybackHub.commandHandler = null + if (isFinishing) PlaybackService.stop(this) + webView.destroy() + super.onDestroy() + } + + // ------------------------------------------------------------------ WebView + + @SuppressLint("SetJavaScriptEnabled") + private fun configureWebView() { + val settings = webView.settings + settings.javaScriptEnabled = true + settings.domStorageEnabled = true + settings.mediaPlaybackRequiresUserGesture = false + settings.javaScriptCanOpenWindowsAutomatically = false + settings.userAgentString = UserAgent.chromeLike(settings.userAgentString) + + CookieManager.getInstance().apply { + setAcceptCookie(true) + setAcceptThirdPartyCookies(webView, true) + } + // Ohne diesen Header erkennt Google die App nicht als eingebettete WebView (Anmeldung). + if (WebViewFeature.isFeatureSupported(WebViewFeature.REQUESTED_WITH_HEADER_ALLOW_LIST)) { + WebSettingsCompat.setRequestedWithHeaderOriginAllowList(settings, emptySet()) + } + if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { + WebViewCompat.addDocumentStartJavaScript(webView, MediaScripts.DOCUMENT_START, setOf(MUSIC_ORIGIN)) + } + // Renderer auch bei unsichtbarer App wichtig halten - sonst wird die Wiedergabe gedrosselt. + webView.setRendererPriorityPolicy(WebView.RENDERER_PRIORITY_IMPORTANT, false) + + webView.webViewClient = object : WebViewClient() { + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { + val url = request.url + val web = url.scheme == "https" || url.scheme == "http" + if (web && isTrustedHost(url.host)) return false + // Fremde Links im Standardbrowser oeffnen; andere Schemata (intent:, market:) ignorieren. + if (web) startActivity(Intent(Intent.ACTION_VIEW, url)) + return true + } + + override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) { + if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) { + view.evaluateJavascript(MediaScripts.DOCUMENT_START, null) + } + } + } + webView.webChromeClient = object : WebChromeClient() { + override fun onProgressChanged(view: WebView, newProgress: Int) { + progress.progress = newProgress + progress.visibility = if (newProgress < 100) View.VISIBLE else View.GONE + } + + // Mikrofon/Kamera braucht YouTube Music nicht. + override fun onPermissionRequest(request: PermissionRequest) = request.deny() + } + } + + private fun probe() { + webView.evaluateJavascript(MediaScripts.PROBE) { raw -> + NowPlaying.parse(raw)?.let(PlaybackHub::publish) + } + } + + // ------------------------------------------------------------------ Start, Rechte, Updates + + private fun startUrl(intent: Intent?): String = + intent?.data?.takeIf(::isMusicLink)?.toString() ?: HOME_URL + + private fun isMusicLink(uri: Uri): Boolean = uri.scheme == "https" && uri.host == MUSIC_HOST + + private fun requestNotificationPermission() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && + ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED + ) { + notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS) + } + } + + private fun checkForUpdate() { + Thread { + val release = UpdateChecker.fetchLatest(BuildConfig.UPDATE_SERVER, BuildConfig.REPO_SLUG) ?: return@Thread + val installed = UpdateChecker.parseVersion(BuildConfig.VERSION_NAME) + if (UpdateChecker.isNewer(release.version, installed)) { + runOnUiThread { if (!isFinishing) showUpdateDialog(release) } + } + }.start() + } + + private fun showUpdateDialog(release: UpdateChecker.Release) { + val prefs = getSharedPreferences(PREFS, MODE_PRIVATE) + if (prefs.getString(KEY_DISMISSED_UPDATE, null) == release.tag) return + AlertDialog.Builder(this) + .setTitle(R.string.update_title) + .setMessage(getString(R.string.update_message, release.tag, BuildConfig.VERSION_NAME)) + .setPositiveButton(R.string.update_download) { _, _ -> + startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(release.url))) + } + .setNegativeButton(R.string.update_later) { _, _ -> + prefs.edit().putString(KEY_DISMISSED_UPDATE, release.tag).apply() + } + .show() + } + + private fun isTrustedHost(host: String?): Boolean = + host != null && TRUSTED_DOMAINS.any { host == it || host.endsWith(".$it") } + + companion object { + private const val MUSIC_HOST = "music.youtube.com" + private const val MUSIC_ORIGIN = "https://music.youtube.com" + private const val HOME_URL = "https://music.youtube.com/" + private const val PROBE_INTERVAL_MS = 1500L + private const val PREFS = "playtube" + private const val KEY_DISMISSED_UPDATE = "dismissed_update" + + // Seiten, die in der App bleiben duerfen (YouTube Music samt Google-Anmeldung). + private val TRUSTED_DOMAINS = listOf( + "youtube.com", "google.com", "gstatic.com", "googleusercontent.com", + "googleapis.com", "ggpht.com", "ytimg.com", + ) + } +} diff --git a/app/src/main/java/de/fojadrachi/playtube/MediaScripts.kt b/app/src/main/java/de/fojadrachi/playtube/MediaScripts.kt new file mode 100644 index 0000000..b1e2279 --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/MediaScripts.kt @@ -0,0 +1,99 @@ +package de.fojadrachi.playtube + +/** + * JavaScript, das in die YouTube-Music-Seite eingeschleust wird (Ableger von media_probe.py und + * media_control.py der Desktop-App, nur fuer YouTube Music). + */ +object MediaScripts { + /** + * Laeuft vor allen Seitenskripten: + * - merkt sich die "MediaSession"-Handler der Seite (Play, Pause, Naechster, Vorheriger, Spulen), + * damit sich die Seite unabhaengig vom Layout steuern laesst; + * - verbirgt der Seite, dass sie im Hintergrund ist - sonst pausiert YouTube Music, sobald die + * App nicht mehr sichtbar ist. + */ + const val DOCUMENT_START = """ +(function () { + if (window.__playtube) { return; } + var handlers = {}; + try { + var session = navigator.mediaSession; + var original = session.setActionHandler.bind(session); + session.setActionHandler = function (action, callback) { + handlers[action] = callback; + return original(action, callback); + }; + } catch (e) {} + window.__playtube = { handlers: handlers }; + try { + Object.defineProperty(document, 'hidden', { get: function () { return false; }, configurable: true }); + Object.defineProperty(document, 'webkitHidden', { get: function () { return false; }, configurable: true }); + Object.defineProperty(document, 'visibilityState', { get: function () { return 'visible'; }, configurable: true }); + } catch (e) {} + var swallow = function (event) { event.stopImmediatePropagation(); }; + document.addEventListener('visibilitychange', swallow, true); + window.addEventListener('pagehide', swallow, true); + window.addEventListener('blur', swallow, true); +})(); +""" + + /** + * Liefert (als JSON-Text) Titel, Interpret, Cover, Wiedergabestatus und Position. Titel/Interpret/ + * Cover kommen aus der MediaSession der Seite, der Zeitstand wie in der Desktop-App aus dem + * sichtbaren Fortschrittsbalken (video.currentTime springt bei nahtlosem Titelwechsel nicht zurueck). + */ + const val PROBE = """ +(function () { + var video = document.querySelector('video'); + var meta = navigator.mediaSession ? navigator.mediaSession.metadata : null; + function text(selector) { + var el = document.querySelector(selector); + return el ? el.textContent.trim() : null; + } + var title = meta && meta.title ? meta.title : text('ytmusic-player-bar .title'); + var artist = meta && meta.artist ? meta.artist : text('ytmusic-player-bar .byline'); + var artwork = null; + if (meta && meta.artwork && meta.artwork.length) { + artwork = meta.artwork[meta.artwork.length - 1].src; + } + var slider = document.querySelector('#progress-bar'); + var now = slider ? parseFloat(slider.getAttribute('aria-valuenow')) : NaN; + var max = slider ? parseFloat(slider.getAttribute('aria-valuemax')) : NaN; + var sliderOk = isFinite(now) && isFinite(max) && max > 0; + var current = sliderOk ? now : (video ? video.currentTime : 0); + var duration = sliderOk ? max : ((video && isFinite(video.duration)) ? video.duration : 0); + return JSON.stringify({ + title: title || '', + artist: artist || '', + artwork: artwork, + playing: !!video && !video.paused && !video.ended && video.readyState > 2, + currentTime: current || 0, + duration: duration || 0 + }); +})(); +""" + + /** Skript fuer einen Befehl. Der einzige variable Teil ist eine Zahl (Sekunden beim Spulen). */ + fun forCommand(command: PlayerCommand): String = when (command) { + PlayerCommand.PlayPause -> + "(function(){var v=document.querySelector('video');if(v){if(v.paused){v.play();}else{v.pause();}}})();" + PlayerCommand.Play -> + "(function(){var v=document.querySelector('video');if(v&&v.paused){v.play();}})();" + PlayerCommand.Pause -> + "(function(){var v=document.querySelector('video');if(v&&!v.paused){v.pause();}})();" + PlayerCommand.Next -> + action("nexttrack", "['ytmusic-player-bar .next-button','.next-button']") + PlayerCommand.Previous -> + action("previoustrack", "['ytmusic-player-bar .previous-button','.previous-button']") + is PlayerCommand.SeekTo -> { + val seconds = command.positionMs / 1000.0 + "(function(){var v=document.querySelector('video');if(v){v.currentTime=$seconds;}})();" + } + } + + /** Erst den MediaSession-Handler der Seite aufrufen, sonst den passenden Knopf anklicken. */ + private fun action(name: String, selectors: String): String = + "(function(){var h=window.__playtube&&window.__playtube.handlers['$name'];" + + "if(h){h({action:'$name'});return;}" + + "var s=$selectors;for(var i=0;i null. + */ + fun parse(raw: String?): NowPlaying? { + if (raw.isNullOrBlank() || raw == "null") return null + val json = toJsonObject(raw) ?: return null + return NowPlaying( + title = json.optString("title").trim(), + // YouTube Music liefert "Interpret • Album • Jahr" - hier nur der Interpret. + artist = json.optString("artist").substringBefore(ARTIST_SEPARATOR).trim(), + artworkUrl = json.optString("artwork").takeIf { it.startsWith("http") }, + playing = json.optBoolean("playing", false), + positionMs = seconds(json.optDouble("currentTime", 0.0)), + durationMs = seconds(json.optDouble("duration", 0.0)), + ) + } + + private fun toJsonObject(raw: String): JSONObject? = + try { + when (val value = JSONTokener(raw).nextValue()) { + is String -> JSONObject(value) + is JSONObject -> value + else -> null + } + } catch (_: Exception) { + null + } + + private fun seconds(value: Double): Long = + if (value.isNaN() || value.isInfinite() || value < 0) 0L else (value * 1000).toLong() + } +} diff --git a/app/src/main/java/de/fojadrachi/playtube/PlaybackHub.kt b/app/src/main/java/de/fojadrachi/playtube/PlaybackHub.kt new file mode 100644 index 0000000..01f7895 --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/PlaybackHub.kt @@ -0,0 +1,35 @@ +package de.fojadrachi.playtube + +/** Befehle an den Player in der Seite (von Benachrichtigung, Sperrbildschirm, Kopfhoerer-Tasten). */ +sealed class PlayerCommand { + data object PlayPause : PlayerCommand() + data object Play : PlayerCommand() + data object Pause : PlayerCommand() + data object Next : PlayerCommand() + data object Previous : PlayerCommand() + data class SeekTo(val positionMs: Long) : PlayerCommand() +} + +/** + * Verbindung zwischen [MainActivity] (besitzt die WebView) und [PlaybackService] (Benachrichtigung + * und MediaSession). Beides laeuft im selben Prozess; alle Aufrufe passieren auf dem Hauptthread. + */ +object PlaybackHub { + /** Gesetzt von der Activity: fuehrt einen Befehl in der WebView aus. */ + var commandHandler: ((PlayerCommand) -> Unit)? = null + + /** Gesetzt vom Dienst: wird bei jedem neuen Stand aufgerufen. */ + var listener: ((NowPlaying) -> Unit)? = null + + var nowPlaying: NowPlaying = NowPlaying.EMPTY + private set + + fun publish(info: NowPlaying) { + nowPlaying = info + listener?.invoke(info) + } + + fun send(command: PlayerCommand) { + commandHandler?.invoke(command) + } +} diff --git a/app/src/main/java/de/fojadrachi/playtube/PlaybackService.kt b/app/src/main/java/de/fojadrachi/playtube/PlaybackService.kt new file mode 100644 index 0000000..40137d7 --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/PlaybackService.kt @@ -0,0 +1,216 @@ +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.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.os.Handler +import android.os.IBinder +import android.os.Looper +import android.os.PowerManager +import android.support.v4.media.MediaMetadataCompat +import android.support.v4.media.session.MediaSessionCompat +import android.support.v4.media.session.PlaybackStateCompat +import androidx.core.app.NotificationCompat +import androidx.core.app.ServiceCompat +import androidx.core.content.ContextCompat +import androidx.media.app.NotificationCompat.MediaStyle +import java.net.URL + +/** + * Haelt die App im Hintergrund am Leben (Vordergrunddienst) und zeigt die Medien-Benachrichtigung + * samt Sperrbildschirm-Steuerung. Die eigentliche Wiedergabe laeuft in der WebView der + * [MainActivity]; der Dienst bekommt den Stand ueber [PlaybackHub] und gibt Befehle dorthin zurueck. + */ +class PlaybackService : Service() { + private lateinit var session: MediaSessionCompat + private lateinit var manager: NotificationManager + private val main = Handler(Looper.getMainLooper()) + private var wakeLock: PowerManager.WakeLock? = null + + private var artwork: Bitmap? = null + private var artworkUrl: String? = null + private var notificationKey: List? = null + private var metadataKey: List? = null + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onCreate() { + super.onCreate() + manager = getSystemService(NotificationManager::class.java) + manager.createNotificationChannel( + NotificationChannel(CHANNEL_ID, getString(R.string.channel_playback), NotificationManager.IMPORTANCE_LOW), + ) + session = MediaSessionCompat(this, "Playtube").apply { + setCallback(object : MediaSessionCompat.Callback() { + override fun onPlay() = PlaybackHub.send(PlayerCommand.Play) + override fun onPause() = PlaybackHub.send(PlayerCommand.Pause) + override fun onSkipToNext() = PlaybackHub.send(PlayerCommand.Next) + override fun onSkipToPrevious() = PlaybackHub.send(PlayerCommand.Previous) + override fun onSeekTo(pos: Long) = PlaybackHub.send(PlayerCommand.SeekTo(pos)) + }) + isActive = true + } + ServiceCompat.startForeground( + this, + NOTIFICATION_ID, + buildNotification(PlaybackHub.nowPlaying), + ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK, + ) + PlaybackHub.listener = ::render + render(PlaybackHub.nowPlaying) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + ACTION_PLAY_PAUSE -> PlaybackHub.send(PlayerCommand.PlayPause) + ACTION_NEXT -> PlaybackHub.send(PlayerCommand.Next) + ACTION_PREVIOUS -> PlaybackHub.send(PlayerCommand.Previous) + } + return START_NOT_STICKY + } + + override fun onTaskRemoved(rootIntent: Intent?) { + stopSelf() + } + + override fun onDestroy() { + PlaybackHub.listener = null + main.removeCallbacksAndMessages(null) + releaseWakeLock() + session.release() + super.onDestroy() + } + + // ------------------------------------------------------------------ Anzeige + + private fun render(info: NowPlaying) { + updateArtwork(info.artworkUrl) + + val metadata = listOf(info.title, info.artist, info.durationMs, artwork != null) + if (metadata != metadataKey) { + metadataKey = metadata + session.setMetadata( + MediaMetadataCompat.Builder() + .putString(MediaMetadataCompat.METADATA_KEY_TITLE, info.title) + .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, info.artist) + .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, info.durationMs) + .apply { artwork?.let { putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, it) } } + .build(), + ) + } + session.setPlaybackState(playbackState(info)) + + val notification = listOf(info.title, info.artist, info.playing, artwork != null) + if (notification != notificationKey) { + notificationKey = notification + manager.notify(NOTIFICATION_ID, buildNotification(info)) + } + if (info.playing) acquireWakeLock() else releaseWakeLock() + } + + private fun playbackState(info: NowPlaying): PlaybackStateCompat { + val state = when { + !info.hasTrack -> PlaybackStateCompat.STATE_NONE + info.playing -> PlaybackStateCompat.STATE_PLAYING + else -> PlaybackStateCompat.STATE_PAUSED + } + return PlaybackStateCompat.Builder() + .setActions( + PlaybackStateCompat.ACTION_PLAY or PlaybackStateCompat.ACTION_PAUSE or + PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or + PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or PlaybackStateCompat.ACTION_SEEK_TO, + ) + .setState(state, info.positionMs, if (info.playing) 1f else 0f) + .build() + } + + private fun buildNotification(info: NowPlaying): Notification { + val open = PendingIntent.getActivity( + this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE, + ) + val playPauseIcon = if (info.playing) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play + val playPauseLabel = getString(if (info.playing) R.string.action_pause else R.string.action_play) + return NotificationCompat.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(info.title.ifBlank { getString(R.string.notif_idle_title) }) + .setContentText(info.artist.ifBlank { getString(R.string.notif_idle_text) }) + .setLargeIcon(artwork) + .setContentIntent(open) + .setOnlyAlertOnce(true) + .setOngoing(info.playing) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .addAction(android.R.drawable.ic_media_previous, getString(R.string.action_previous), actionIntent(ACTION_PREVIOUS, 1)) + .addAction(playPauseIcon, playPauseLabel, actionIntent(ACTION_PLAY_PAUSE, 2)) + .addAction(android.R.drawable.ic_media_next, getString(R.string.action_next), actionIntent(ACTION_NEXT, 3)) + .setStyle(MediaStyle().setMediaSession(session.sessionToken).setShowActionsInCompactView(0, 1, 2)) + .build() + } + + private fun actionIntent(action: String, requestCode: Int): PendingIntent = + PendingIntent.getService( + this, + requestCode, + Intent(this, PlaybackService::class.java).setAction(action), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, + ) + + // ------------------------------------------------------------------ Cover + + private fun updateArtwork(url: String?) { + if (url == artworkUrl) return + artworkUrl = url + artwork = null + if (url == null) return + Thread { + val bitmap = try { + URL(url).openStream().use { BitmapFactory.decodeStream(it) } + } catch (_: Exception) { + null + } + main.post { + if (artworkUrl == url) { + artwork = bitmap + render(PlaybackHub.nowPlaying) + } + } + }.start() + } + + // ------------------------------------------------------------------ Wachhalten + + private fun acquireWakeLock() { + if (wakeLock?.isHeld == true) return + val power = getSystemService(Context.POWER_SERVICE) as PowerManager + wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "playtube:playback") + .apply { acquire(WAKE_LOCK_TIMEOUT_MS) } + } + + private fun releaseWakeLock() { + wakeLock?.takeIf { it.isHeld }?.release() + wakeLock = null + } + + companion object { + private const val CHANNEL_ID = "playback" + private const val NOTIFICATION_ID = 1 + private const val ACTION_PLAY_PAUSE = "de.fojadrachi.playtube.PLAY_PAUSE" + private const val ACTION_NEXT = "de.fojadrachi.playtube.NEXT" + private const val ACTION_PREVIOUS = "de.fojadrachi.playtube.PREVIOUS" + private const val WAKE_LOCK_TIMEOUT_MS = 6 * 60 * 60 * 1000L + + fun start(context: Context) { + ContextCompat.startForegroundService(context, Intent(context, PlaybackService::class.java)) + } + + fun stop(context: Context) { + context.stopService(Intent(context, PlaybackService::class.java)) + } + } +} diff --git a/app/src/main/java/de/fojadrachi/playtube/UpdateChecker.kt b/app/src/main/java/de/fojadrachi/playtube/UpdateChecker.kt new file mode 100644 index 0000000..b55a060 --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/UpdateChecker.kt @@ -0,0 +1,73 @@ +package de.fojadrachi.playtube + +import org.json.JSONArray +import java.net.HttpURLConnection +import java.net.URL + +/** + * Update-Pruefung ueber die Releases des eigenen Gitea-Servers (kein GitHub, kein Play Store). + * Releases der Android-App tragen den Tag "vX.Y.Z-android"; die Desktop-Versionen von Playtube + * (Tags "vX.Y.Z" bzw. "vX.Y.Z-edge") werden hier ignoriert. + */ +object UpdateChecker { + private const val TAG_SUFFIX = "-android" + private const val TIMEOUT_MS = 10_000 + private val VERSION = Regex("(\\d+)\\.(\\d+)\\.(\\d+)") + + data class Release(val tag: String, val version: List, val url: String) + + /** "v1.2.3-android" -> [1, 2, 3]; ohne Versionsnummer leer. */ + fun parseVersion(text: String): List = + VERSION.find(text)?.groupValues?.drop(1)?.map { it.toInt() } ?: emptyList() + + fun isNewer(remote: List, local: List): Boolean { + for (index in 0 until maxOf(remote.size, local.size)) { + val r = remote.getOrElse(index) { 0 } + val l = local.getOrElse(index) { 0 } + if (r != l) return r > l + } + return false + } + + /** Neuestes Android-Release aus der JSON-Liste der Gitea-API (Entwuerfe werden uebersprungen). */ + fun pickLatest(releasesJson: String, server: String, slug: String): Release? { + val releases = try { + JSONArray(releasesJson) + } catch (_: Exception) { + return null + } + var best: Release? = null + for (index in 0 until releases.length()) { + val entry = releases.optJSONObject(index) ?: continue + val tag = entry.optString("tag_name") + if (entry.optBoolean("draft") || !tag.endsWith(TAG_SUFFIX)) continue + val version = parseVersion(tag) + if (version.isEmpty()) continue + val url = entry.optString("html_url").ifBlank { "$server/$slug/releases/tag/$tag" } + val current = best + if (current == null || isNewer(version, current.version)) best = Release(tag, version, url) + } + return best + } + + /** Fragt den Server ab (Netzwerk - nicht auf dem Hauptthread aufrufen). */ + fun fetchLatest(server: String, slug: String): Release? = + try { + val connection = URL("$server/api/v1/repos/$slug/releases?limit=30").openConnection() as HttpURLConnection + connection.connectTimeout = TIMEOUT_MS + connection.readTimeout = TIMEOUT_MS + connection.setRequestProperty("Accept", "application/json") + connection.setRequestProperty("User-Agent", "Playtube-Android-Updater") + try { + if (connection.responseCode == HttpURLConnection.HTTP_OK) { + pickLatest(connection.inputStream.bufferedReader().use { it.readText() }, server, slug) + } else { + null + } + } finally { + connection.disconnect() + } + } catch (_: Exception) { + null + } +} diff --git a/app/src/main/java/de/fojadrachi/playtube/UserAgent.kt b/app/src/main/java/de/fojadrachi/playtube/UserAgent.kt new file mode 100644 index 0000000..4af8d0a --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/UserAgent.kt @@ -0,0 +1,13 @@ +package de.fojadrachi.playtube + +/** + * Google blockiert die Anmeldung in eingebetteten Browsern ("Dieser Browser oder diese App ist + * unter Umstaenden nicht sicher"). Die Android-WebView verraet sich im User-Agent durch "; wv" + * und "Version/4.0" - beides wird entfernt, damit sie wie ein normales mobiles Chrome meldet. + */ +object UserAgent { + private val VERSION_TOKEN = Regex("Version/\\d+(\\.\\d+)*\\s") + + fun chromeLike(webViewUserAgent: String): String = + webViewUserAgent.replace("; wv", "").replace(VERSION_TOKEN, "") +} diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..4ca8f78 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.xml b/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..4c4f662 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/drawable/ic_notification.xml b/app/src/main/res/drawable/ic_notification.xml new file mode 100644 index 0000000..30ae04d --- /dev/null +++ b/app/src/main/res/drawable/ic_notification.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml new file mode 100644 index 0000000..c4591e0 --- /dev/null +++ b/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,21 @@ + + + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6b78462 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..6b78462 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/src/main/res/values/values.xml b/app/src/main/res/values/values.xml new file mode 100644 index 0000000..e6f2a85 --- /dev/null +++ b/app/src/main/res/values/values.xml @@ -0,0 +1,27 @@ + + + Playtube + Wiedergabe + Playtube + YouTube Music + Vorheriger Titel + Wiedergabe + Pause + Nächster Titel + Update verfügbar + Eine neue Version von Playtube ist verfügbar: %1$s (installiert: %2$s). + Herunterladen + Später + + #0F0F0F + #7C3AED + #EC4899 + + + diff --git a/app/src/test/java/de/fojadrachi/playtube/NowPlayingTest.kt b/app/src/test/java/de/fojadrachi/playtube/NowPlayingTest.kt new file mode 100644 index 0000000..4bdd3c9 --- /dev/null +++ b/app/src/test/java/de/fojadrachi/playtube/NowPlayingTest.kt @@ -0,0 +1,54 @@ +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 NowPlayingTest { + // So liefert WebView.evaluateJavascript das Ergebnis: der JSON-Text nochmal als String kodiert. + private fun encoded(json: String) = "\"" + json.replace("\\", "\\\\").replace("\"", "\\\"") + "\"" + + @Test + fun `liest Titel, Interpret, Cover, Status und Zeit`() { + val json = """{"title":"Song","artist":"Band • Album • 2024","artwork":"https://i.ytimg.com/a.jpg","playing":true,"currentTime":12.5,"duration":200}""" + val info = NowPlaying.parse(encoded(json))!! + assertEquals("Song", info.title) + assertEquals("Band", info.artist) + assertEquals("https://i.ytimg.com/a.jpg", info.artworkUrl) + assertTrue(info.playing) + assertEquals(12_500L, info.positionMs) + assertEquals(200_000L, info.durationMs) + assertTrue(info.hasTrack) + } + + @Test + fun `null und Muell ergeben null`() { + assertNull(NowPlaying.parse(null)) + assertNull(NowPlaying.parse("null")) + assertNull(NowPlaying.parse("")) + assertNull(NowPlaying.parse("kein json")) + assertNull(NowPlaying.parse("42")) + } + + @Test + fun `negative Zeiten werden zu null Millisekunden`() { + val info = NowPlaying.parse(encoded("""{"title":"x","currentTime":-5,"duration":-1}"""))!! + assertEquals(0L, info.positionMs) + assertEquals(0L, info.durationMs) + } + + @Test + fun `Cover nur bei http-Adressen`() { + val json = """{"title":"x","artwork":"data:image/png;base64,AAAA"}""" + assertNull(NowPlaying.parse(encoded(json))!!.artworkUrl) + } + + @Test + fun `ohne Titel gilt kein Titel als laufend`() { + val info = NowPlaying.parse(encoded("""{"title":" ","playing":false}"""))!! + assertFalse(info.hasTrack) + assertEquals(NowPlaying.EMPTY.hasTrack, info.hasTrack) + } +} diff --git a/app/src/test/java/de/fojadrachi/playtube/UpdateCheckerTest.kt b/app/src/test/java/de/fojadrachi/playtube/UpdateCheckerTest.kt new file mode 100644 index 0000000..5da720f --- /dev/null +++ b/app/src/test/java/de/fojadrachi/playtube/UpdateCheckerTest.kt @@ -0,0 +1,53 @@ +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 UpdateCheckerTest { + private val server = "https://git.example.test" + private val slug = "owner/Playtube" + + @Test + fun `liest die Versionsnummer aus dem Tag`() { + assertEquals(listOf(1, 2, 3), UpdateChecker.parseVersion("v1.2.3-android")) + assertEquals(emptyList(), UpdateChecker.parseVersion("nightly")) + } + + @Test + fun `vergleicht Versionen numerisch`() { + assertTrue(UpdateChecker.isNewer(listOf(1, 0, 10), listOf(1, 0, 9))) + assertTrue(UpdateChecker.isNewer(listOf(2, 0, 0), listOf(1, 9, 9))) + assertFalse(UpdateChecker.isNewer(listOf(1, 0, 0), listOf(1, 0, 0))) + assertFalse(UpdateChecker.isNewer(listOf(1, 0, 0), listOf(1, 0, 1))) + } + + @Test + fun `nimmt nur Android-Releases und das neueste davon`() { + val json = """[ + {"tag_name":"v4.5.1","draft":false,"html_url":"https://x/desktop"}, + {"tag_name":"v1.0.0-edge","draft":false,"html_url":"https://x/edge"}, + {"tag_name":"v1.0.0-android","draft":false,"html_url":"https://x/a100"}, + {"tag_name":"v1.2.0-android","draft":false,"html_url":"https://x/a120"}, + {"tag_name":"v2.0.0-android","draft":true,"html_url":"https://x/draft"} + ]""" + val release = UpdateChecker.pickLatest(json, server, slug)!! + assertEquals("v1.2.0-android", release.tag) + assertEquals("https://x/a120", release.url) + } + + @Test + fun `ohne Android-Release oder bei Muell kommt null`() { + assertNull(UpdateChecker.pickLatest("""[{"tag_name":"v4.5.1","draft":false}]""", server, slug)) + assertNull(UpdateChecker.pickLatest("kein json", server, slug)) + assertNull(UpdateChecker.pickLatest("[]", server, slug)) + } + + @Test + fun `fehlt html_url, wird die Release-Seite gebaut`() { + val release = UpdateChecker.pickLatest("""[{"tag_name":"v1.0.0-android"}]""", server, slug)!! + assertEquals("https://git.example.test/owner/Playtube/releases/tag/v1.0.0-android", release.url) + } +} diff --git a/app/src/test/java/de/fojadrachi/playtube/UserAgentTest.kt b/app/src/test/java/de/fojadrachi/playtube/UserAgentTest.kt new file mode 100644 index 0000000..d5efac8 --- /dev/null +++ b/app/src/test/java/de/fojadrachi/playtube/UserAgentTest.kt @@ -0,0 +1,33 @@ +package de.fojadrachi.playtube + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Test + +class UserAgentTest { + private val webView = + "Mozilla/5.0 (Linux; Android 14; Pixel 8 Build/AP1A; wv) AppleWebKit/537.36 (KHTML, like Gecko) " + + "Version/4.0 Chrome/140.0.0.0 Mobile Safari/537.36" + + @Test + fun `entfernt die WebView-Merkmale`() { + val chrome = UserAgent.chromeLike(webView) + assertFalse(chrome.contains("; wv")) + assertFalse(chrome.contains("Version/")) + } + + @Test + fun `laesst den Rest unveraendert`() { + assertEquals( + "Mozilla/5.0 (Linux; Android 14; Pixel 8 Build/AP1A) AppleWebKit/537.36 (KHTML, like Gecko) " + + "Chrome/140.0.0.0 Mobile Safari/537.36", + UserAgent.chromeLike(webView), + ) + } + + @Test + fun `ein normaler Chrome-User-Agent bleibt gleich`() { + val chrome = "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/140.0.0.0 Mobile Safari/537.36" + assertEquals(chrome, UserAgent.chromeLike(chrome)) + } +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..1d1d68c --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.13.1" apply false + id("org.jetbrains.kotlin.android") version "2.1.21" apply false +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..5f4cff3 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +android.useAndroidX=true +android.nonTransitiveRClass=true +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ca025c8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..0262dcb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/b631911858264c0b6e4d6603d677ff5218766cee/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/scripts/build-release.ps1 b/scripts/build-release.ps1 new file mode 100644 index 0000000..fe18901 --- /dev/null +++ b/scripts/build-release.ps1 @@ -0,0 +1,50 @@ +# Baut die signierte Release-APK von Playtube fuer Android. +# +# powershell -ExecutionPolicy Bypass -File scripts\build-release.ps1 +# +# Beim ersten Aufruf wird ein Signierschluessel angelegt (keystore\playtube.jks) und das zufaellige +# Passwort in keystore.properties gespeichert. BEIDES liegt nur lokal (steht in .gitignore). +# WICHTIG: keystore\ und keystore.properties an einem zweiten Ort sichern - jede Version muss mit +# demselben Schluessel signiert sein, sonst laesst sie sich nicht ueber die vorherige installieren. + +$ErrorActionPreference = "Stop" +$root = Split-Path -Parent $PSScriptRoot +Set-Location $root + +$keystoreDir = Join-Path $root "keystore" +$keystore = Join-Path $keystoreDir "playtube.jks" +$properties = Join-Path $root "keystore.properties" + +if (-not (Test-Path $properties)) { + Write-Host "==> Lege Signierschluessel an (einmalig) ..." -ForegroundColor Cyan + $keytool = (Get-Command keytool -ErrorAction SilentlyContinue).Source + if (-not $keytool -and $env:JAVA_HOME) { $keytool = Join-Path $env:JAVA_HOME "bin\keytool.exe" } + if (-not $keytool -or -not (Test-Path $keytool)) { throw "keytool nicht gefunden (JDK installieren / JAVA_HOME setzen)." } + + New-Item -ItemType Directory -Path $keystoreDir -ErrorAction SilentlyContinue | Out-Null + $bytes = New-Object byte[] 48 + [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes) + $password = ([Convert]::ToBase64String($bytes) -replace '[^A-Za-z0-9]', '').Substring(0, 32) + + & $keytool -genkeypair -keystore $keystore -alias playtube -keyalg RSA -keysize 4096 -validity 10000 ` + -storepass $password -keypass $password -dname "CN=Playtube, O=Playtube" + if ($LASTEXITCODE -ne 0) { throw "Schluessel konnte nicht angelegt werden." } + + Set-Content -Path $properties -Encoding ASCII -Value @( + "storeFile=keystore/playtube.jks", + "storePassword=$password", + "keyAlias=playtube", + "keyPassword=$password" + ) + Write-Host "Schluessel angelegt. SICHERE den Ordner keystore\ und die Datei keystore.properties!" -ForegroundColor Yellow +} + +Write-Host "==> Baue Release-APK ..." -ForegroundColor Cyan +& .\gradlew.bat :app:testDebugUnitTest :app:assembleRelease +if ($LASTEXITCODE -ne 0) { throw "Build fehlgeschlagen." } + +$version = (Select-String -Path (Join-Path $root "app\build.gradle.kts") -Pattern 'versionName = "([^"]+)"').Matches[0].Groups[1].Value +$outDir = Join-Path $root "app\build\outputs\apk\release" +$apk = Join-Path $outDir "Playtube-Android-v$version.apk" +Copy-Item (Join-Path $outDir "app-release.apk") $apk -Force +Write-Host "Fertig: $apk" -ForegroundColor Green diff --git a/scripts/publish_release.ps1 b/scripts/publish_release.ps1 new file mode 100644 index 0000000..c2785a1 --- /dev/null +++ b/scripts/publish_release.ps1 @@ -0,0 +1,73 @@ +# Veroeffentlicht ein Release auf dem eigenen Gitea-Server (Installer, ZIP, Patch als Anhaenge). +# Wird von der Pipeline (.gitea/workflows/release.yml) benutzt und laesst sich auch von Hand +# aufrufen, z.B. nach einem lokalen Build (packaging\build.ps1): +# +# $env:GITEA_TOKEN = "" +# powershell -ExecutionPolicy Bypass -File packaging\publish_release.ps1 ` +# -Tag v4.6.0 -Files dist\installer\Playtube-Setup-v4.6.0.exe,Playtube-v4.6.0-win64.zip +# +# Der Token wird in Gitea unter Einstellungen > Anwendungen erzeugt (Recht "repository: Lesen und +# Schreiben"). Er steht NIE im Skript, sondern nur in der Umgebungsvariable GITEA_TOKEN. +# Gab es zum selben Tag schon ein Release, wird es vorher entfernt (der Git-Tag bleibt). + +param( + [Parameter(Mandatory = $true)] [string]$Tag, + [Parameter(Mandatory = $true)] [string[]]$Files, + [string]$Title = "", + [string]$NotesFile = "", + [switch]$Prerelease, + [string]$Server = "https://git.fojadrachi.de", + [string]$Repo = "Fojadrachi/Playtube" +) + +$ErrorActionPreference = "Stop" + +$token = $env:GITEA_TOKEN +if (-not $token) { + # Alternativ aus einer lokalen Datei (nur fuer deinen Benutzer): %USERPROFILE%\.gitea-token + $tokenFile = Join-Path $env:USERPROFILE ".gitea-token" + if (Test-Path $tokenFile) { $token = (Get-Content -Raw $tokenFile).Trim() } +} +if (-not $token) { + throw "Kein Token: GITEA_TOKEN setzen oder ihn in %USERPROFILE%\.gitea-token ablegen (Zugriffstoken aus Gitea > Einstellungen > Anwendungen)." +} +if (-not $Title) { $Title = $Tag } +foreach ($file in $Files) { + if (-not (Test-Path $file)) { throw "Datei nicht gefunden: $file" } +} + +$api = "$Server/api/v1/repos/$Repo" +$headers = @{ Authorization = "token $token" } + +# Vorhandenes Release zum selben Tag entfernen (404 = gab keins). +try { + $old = Invoke-RestMethod -Headers $headers -Uri "$api/releases/tags/$Tag" + Invoke-RestMethod -Method Delete -Headers $headers -Uri "$api/releases/$($old.id)" | Out-Null + Write-Host "Vorhandenes Release zu $Tag ersetzt." +} catch { + if ($_.Exception.Response -and [int]$_.Exception.Response.StatusCode -ne 404) { throw } +} + +$notes = "" +# [string]: sonst serialisiert ConvertTo-Json die PowerShell-Zusatzeigenschaften mit (Objekt statt Text). +if ($NotesFile -and (Test-Path $NotesFile)) { $notes = [string](Get-Content -Raw -Encoding UTF8 $NotesFile) } + +$payload = @{ + tag_name = $Tag + name = $Title + body = $notes + draft = $false + prerelease = [bool]$Prerelease +} | ConvertTo-Json +$release = Invoke-RestMethod -Method Post -Headers $headers -Uri "$api/releases" ` + -ContentType "application/json; charset=utf-8" -Body ([Text.Encoding]::UTF8.GetBytes($payload)) + +foreach ($file in $Files) { + $name = Split-Path $file -Leaf + Write-Host "Lade hoch: $name" + & curl.exe -sS --fail -X POST -H "Authorization: token $token" -F "attachment=@$file" ` + "$api/releases/$($release.id)/assets?name=$([uri]::EscapeDataString($name))" | Out-Null + if ($LASTEXITCODE -ne 0) { throw "Upload fehlgeschlagen: $name" } +} + +Write-Host "Fertig: $Server/$Repo/releases/tag/$Tag" -ForegroundColor Green diff --git a/scripts/release_notes.md b/scripts/release_notes.md new file mode 100644 index 0000000..e115112 --- /dev/null +++ b/scripts/release_notes.md @@ -0,0 +1,17 @@ +## Playtube für Android – YouTube Music mit Hintergrundwiedergabe + +Die Android-Version von Playtube: **nur YouTube Music**, ohne YouTube-Tab, Discord und +Stream-Dock-Fernsteuerung. + +- Musik läuft im Hintergrund und bei ausgeschaltetem Bildschirm weiter. +- Medien-Benachrichtigung und Sperrbildschirm-Steuerung mit Titel, Interpret und Cover. +- **Eigene, hochgeladene Songs** lassen sich abspielen. +- Updates über diese Releases (Tag `…-android`), kein GitHub, kein Play Store. + +### Installieren +1. `Playtube-Android-vX.Y.Z.apk` herunterladen und öffnen. +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. diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..629d3f3 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "playtube-android" +include(":app")