feat: Playtube fuer Android - nur YouTube Music, Hintergrundwiedergabe, Updates ueber Gitea
This commit is contained in:
@@ -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")
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<!-- Musik laeuft im Hintergrund weiter: Vordergrunddienst mit Medien-Benachrichtigung. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
|
||||
<application
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.Playtube"
|
||||
android:usesCleartextTraffic="false">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTask"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<!-- Geteilte/angetippte YouTube-Music-Links oeffnen sich in Playtube. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="https" android:host="music.youtube.com" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".PlaybackService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="mediaPlayback" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -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",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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<s.length;i++){var e=document.querySelector(s[i]);if(e){e.click();return;}}})();"
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package de.fojadrachi.playtube
|
||||
|
||||
import org.json.JSONObject
|
||||
import org.json.JSONTokener
|
||||
|
||||
/** Was gerade in YouTube Music laeuft - gelesen aus der Seite (siehe [MediaScripts.PROBE]). */
|
||||
data class NowPlaying(
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val artworkUrl: String?,
|
||||
val playing: Boolean,
|
||||
val positionMs: Long,
|
||||
val durationMs: Long,
|
||||
) {
|
||||
val hasTrack: Boolean get() = title.isNotBlank()
|
||||
|
||||
companion object {
|
||||
val EMPTY = NowPlaying("", "", null, playing = false, positionMs = 0L, durationMs = 0L)
|
||||
|
||||
private const val ARTIST_SEPARATOR = " • "
|
||||
|
||||
/**
|
||||
* Wertet das Ergebnis von `WebView.evaluateJavascript` aus: ein JSON-kodierter String
|
||||
* (das Skript gibt selbst einen JSON-Text zurueck) oder "null". Ungueltiges -> 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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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<Any?>? = null
|
||||
private var metadataKey: List<Any?>? = 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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Int>, val url: String)
|
||||
|
||||
/** "v1.2.3-android" -> [1, 2, 3]; ohne Versionsnummer leer. */
|
||||
fun parseVersion(text: String): List<Int> =
|
||||
VERSION.find(text)?.groupValues?.drop(1)?.map { it.toInt() } ?: emptyList()
|
||||
|
||||
fun isNewer(remote: List<Int>, local: List<Int>): 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
|
||||
}
|
||||
}
|
||||
@@ -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, "")
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:shape="rectangle">
|
||||
<!-- Playtube-Marke: diagonaler Verlauf violett -> pink -->
|
||||
<gradient
|
||||
android:angle="315"
|
||||
android:endColor="#EC4899"
|
||||
android:startColor="#7C3AED"
|
||||
android:type="linear" />
|
||||
</shape>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M43,32L43,76L79,54Z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="24dp"
|
||||
android:height="24dp"
|
||||
android:viewportWidth="24"
|
||||
android:viewportHeight="24">
|
||||
<path
|
||||
android:fillColor="#FFFFFFFF"
|
||||
android:pathData="M8,5v14l11,-7z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/background">
|
||||
|
||||
<WebView
|
||||
android:id="@+id/webView"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent" />
|
||||
|
||||
<ProgressBar
|
||||
android:id="@+id/progress"
|
||||
style="?android:attr/progressBarStyleHorizontal"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="3dp"
|
||||
android:layout_gravity="top"
|
||||
android:max="100"
|
||||
android:progressTint="@color/brand_to"
|
||||
android:visibility="gone" />
|
||||
</FrameLayout>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<background android:drawable="@drawable/ic_launcher_background" />
|
||||
<foreground android:drawable="@drawable/ic_launcher_foreground" />
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,27 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<string name="app_name">Playtube</string>
|
||||
<string name="channel_playback">Wiedergabe</string>
|
||||
<string name="notif_idle_title">Playtube</string>
|
||||
<string name="notif_idle_text">YouTube Music</string>
|
||||
<string name="action_previous">Vorheriger Titel</string>
|
||||
<string name="action_play">Wiedergabe</string>
|
||||
<string name="action_pause">Pause</string>
|
||||
<string name="action_next">Nächster Titel</string>
|
||||
<string name="update_title">Update verfügbar</string>
|
||||
<string name="update_message">Eine neue Version von Playtube ist verfügbar: %1$s (installiert: %2$s).</string>
|
||||
<string name="update_download">Herunterladen</string>
|
||||
<string name="update_later">Später</string>
|
||||
|
||||
<color name="background">#0F0F0F</color>
|
||||
<color name="brand_from">#7C3AED</color>
|
||||
<color name="brand_to">#EC4899</color>
|
||||
|
||||
<style name="Theme.Playtube" parent="Theme.AppCompat.NoActionBar">
|
||||
<item name="android:windowBackground">@color/background</item>
|
||||
<item name="android:statusBarColor">@color/background</item>
|
||||
<item name="android:navigationBarColor">@color/background</item>
|
||||
<item name="colorPrimary">@color/brand_from</item>
|
||||
<item name="colorAccent">@color/brand_to</item>
|
||||
</style>
|
||||
</resources>
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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<Int>(), 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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user