57 lines
2.2 KiB
Kotlin
57 lines
2.2 KiB
Kotlin
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 likeStatus: String? = null,
|
|
) {
|
|
val hasTrack: Boolean get() = title.isNotBlank()
|
|
|
|
companion object {
|
|
val EMPTY = NowPlaying("", "", null, playing = false, positionMs = 0L, durationMs = 0L, likeStatus = null)
|
|
|
|
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)),
|
|
likeStatus = json.optString("likeStatus").takeIf { it.isNotBlank() && it != "null" },
|
|
)
|
|
}
|
|
|
|
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()
|
|
}
|
|
}
|