feat: Jam mit YouTube Music – stoebern ohne Neuladen, angetippte Songs landen im Jam (1.4.1)

Jam liest den Player ueber die Player-API (Video-ID, Zeit, Laenge, Status per MediaSession)
und steuert ueber playVideo/pauseVideo/seekTo. In YouTube Music gestartete Songs kommen
wie bei Spotify Jam in die Warteschlange.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-08 12:27:14 +01:00
co-authored by Claude Opus 5.5
parent 12f8f33d9e
commit 5ae9bc4431
6 changed files with 110 additions and 22 deletions
@@ -70,6 +70,9 @@ object JamHub {
private var pendingLoad: Pair<String, Long>? = null
private var stuckSince: Pair<String, Long>? = null
private var diverge = 0
/** Song beim Beitreten ("" = keiner) - zaehlt nicht als Wunsch; beim Starten null = noch offen. */
private var baseline: String? = null
private val picked = HashSet<String>()
var lastDuration = 0.0
private set
@@ -160,6 +163,8 @@ object JamHub {
state = null
unplayable.clear()
reported.clear()
picked.clear()
baseline = null
pendingLoad = null
stuckSince = null
prefs().edit().putString(KEY_CODE, joinCode).putString(KEY_TOKEN, savedToken ?: "").apply()
@@ -366,8 +371,20 @@ object JamHub {
val duration = probe.optDouble("d", 0.0)
val scripts = ArrayList<String>()
var load: String? = null
val pause = MediaScripts.forCommand(PlayerCommand.Pause)
val pause = JamSync.playScript(false)
val matches = want != null && local.videoId == want.videoId
// In YouTube Music selbst einen Song gestartet: ab in den Jam (wie bei Spotify Jam).
if (baseline == null) baseline = local.videoId ?: ""
if (!probe.optBoolean("ad")) {
JamSync.userPick(s, want, local, baseline)?.let { id ->
if (picked.add(id)) {
val title = probe.optString("title").takeIf { it.isNotEmpty() && !probe.isNull("title") }
val artist = probe.optString("artist").takeIf { it.isNotEmpty() && !probe.isNull("artist") }
addVideo(id, title, artist)
setStatus(str(R.string.jam_added, title ?: id))
}
}
}
if (matches) {
pendingLoad = null
if (duration > 0) lastDuration = duration
@@ -430,11 +447,11 @@ object JamHub {
}
is JamSync.Step.Seek -> {
expectUntil = now + 3000
scripts.add(MediaScripts.forCommand(PlayerCommand.SeekTo((step.pos * 1000).toLong())))
scripts.add(JamSync.seekScript(step.pos))
}
JamSync.Step.Play -> {
expectUntil = now + 3000
scripts.add(MediaScripts.forCommand(PlayerCommand.Play))
scripts.add(JamSync.playScript(true))
}
JamSync.Step.Pause -> {
expectUntil = now + 3000
@@ -220,25 +220,71 @@ object JamSync {
fun reachedEnd(local: Local, duration: Double, ended: Boolean): Boolean =
ended || (duration > 0 && local.pos >= duration - 0.6)
/** JavaScript: Stand des Players auf music.youtube.com (wie jam_probe.js am PC). */
/**
* JavaScript: Stand des Players auf music.youtube.com (wie jam_probe.js am PC). Video-ID, Zeit und
* Laenge kommen von der Player-API - so darf man in YouTube Music weiter stoebern, und von
* mehreren <video>-Elementen wird nicht das falsche gelesen.
*/
const val PROBE = """
(function () {
var video = document.querySelector('video');
var player = document.getElementById('movie_player');
function api(fn) { return player && typeof player[fn] === 'function'; }
var video = (player && player.querySelector('video')) || document.querySelector('video');
var id = null;
try { if (location.pathname === '/watch') { id = new URL(location.href).searchParams.get('v'); } } catch (e) { id = null; }
try { var data = api('getVideoData') ? player.getVideoData() : null; id = data && data.video_id ? data.video_id : null; } catch (e) { id = null; }
if (!id) { try { if (location.pathname === '/watch') { id = new URL(location.href).searchParams.get('v'); } } catch (e) { id = null; } }
var state = api('getPlayerState') ? player.getPlayerState() : null;
var session = navigator.mediaSession ? navigator.mediaSession.playbackState : 'none';
var paused;
if (state === 1 || state === 3) { paused = false; }
else if (state === 2) { paused = true; }
else if (session === 'playing' || session === 'paused') { paused = session === 'paused'; }
else { paused = video ? video.paused : true; }
var meta = navigator.mediaSession ? navigator.mediaSession.metadata : null;
var ad = !!document.querySelector('.ad-showing, .ad-interrupting');
var error = !!document.querySelector('.ytp-error, yt-playability-error-supported-renderers:not([hidden]) .reason');
return JSON.stringify({
id: id,
t: video ? video.currentTime : 0,
d: (video && isFinite(video.duration)) ? video.duration : 0,
paused: video ? video.paused : true,
ended: video ? video.ended : false,
t: api('getCurrentTime') ? player.getCurrentTime() : (video ? video.currentTime : 0),
d: api('getDuration') && player.getDuration() > 0 ? player.getDuration() : ((video && isFinite(video.duration)) ? video.duration : 0),
paused: paused,
ended: state === 0 || (video ? video.ended : false),
ad: ad,
error: error
error: error,
title: meta && meta.title ? meta.title : null,
artist: meta && meta.artist ? meta.artist : null
});
})();
"""
/** Abspielen/Pausieren/Spulen ueber die Player-API (Rueckfall: das <video> des Players). */
fun playScript(play: Boolean): String {
val method = if (play) "playVideo" else "pauseVideo"
val prop = if (play) "play" else "pause"
return "(function(){var p=document.getElementById('movie_player');" +
"if(p&&typeof p.$method==='function'){p.$method();return;}" +
"var v=p&&p.querySelector('video')||document.querySelector('video');if(v){v.$prop();}})();"
}
fun seekScript(seconds: Double): String {
val s = if (seconds.isFinite()) max(0.0, seconds) else 0.0
return "(function(){var p=document.getElementById('movie_player');var s=$s;" +
"if(p&&typeof p.seekTo==='function'){p.seekTo(s,true);return;}" +
"var v=p&&p.querySelector('video')||document.querySelector('video');if(v){v.currentTime=s;}})();"
}
/**
* Hat man in YouTube Music selbst einen anderen Song gestartet? Dann kommt er wie bei Spotify Jam
* in den Jam. Nicht dazu zaehlen: der Song beim Beitreten ([baseline]), Autoplay am Titelende,
* der Start-Vorlauf und Songs, die der Jam schon kennt.
*/
fun userPick(state: State, want: Target?, local: Local, baseline: String?): String? {
val id = local.videoId ?: return null
if (local.paused || id == baseline || !VIDEO_ID.matches(id)) return null
if (want != null && (want.videoId == id || want.pos < 0 || (want.dur != null && want.pos > want.dur - 3))) return null
val known = (listOfNotNull(state.current) + state.queue + state.history).any { it.videoId == id }
return if (known) null else id
}
fun watchUrl(videoId: String): String = "https://music.youtube.com/watch?v=$videoId"
}