feat: Playtube Jam – gemeinsam hoeren, synchron auf dem eigenen Handy (1.4.0)
Jam starten (laufender Song wird der erste) oder per Code/Link beitreten, Jam-Ansicht im Stil von "PC steuern": Teilnehmer, Warteschlange, Einladen per Teilen/Kopieren, Host-Rechte. Die YouTube-Music-WebView gleicht sich mit dem Jam ab; Benachrichtigung und Kopfhoerertasten steuern im Jam den Jam. App-Links jam.fojadrachi.de, playtube://jam/<CODE> und "Teilen" von YouTube-Links. OkHttp fuer den WebSocket. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,383 @@
|
||||
package de.fojadrachi.playtube
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.KeyEvent
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.Button
|
||||
import android.widget.EditText
|
||||
import android.widget.ImageButton
|
||||
import android.widget.ImageView
|
||||
import android.widget.LinearLayout
|
||||
import android.widget.SeekBar
|
||||
import android.widget.TextView
|
||||
import android.widget.Toast
|
||||
import androidx.appcompat.app.AlertDialog
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.appcompat.widget.SwitchCompat
|
||||
import androidx.core.view.ViewCompat
|
||||
import androidx.core.view.WindowInsetsCompat
|
||||
import org.json.JSONObject
|
||||
|
||||
/**
|
||||
* Playtube Jam: starten, beitreten (auch ueber Einladungslinks), Warteschlange, Teilnehmer.
|
||||
* Abgespielt wird in der WebView von [MainActivity]; Verbindung und Zustand haelt [JamHub].
|
||||
*/
|
||||
class JamActivity : AppCompatActivity() {
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private lateinit var status: TextView
|
||||
private lateinit var setup: View
|
||||
private lateinit var panel: View
|
||||
private lateinit var leave: Button
|
||||
private lateinit var nameInput: EditText
|
||||
private lateinit var codeInput: EditText
|
||||
private lateinit var addInput: EditText
|
||||
private lateinit var addButton: Button
|
||||
private lateinit var seek: SeekBar
|
||||
private lateinit var allControl: SwitchCompat
|
||||
private var seeking = false
|
||||
/** Per "Teilen" empfangenes Video, solange noch kein Jam laeuft. */
|
||||
private var pendingVideoId: String? = null
|
||||
private var results: List<JamHub.SearchResult> = emptyList()
|
||||
|
||||
private val listener: () -> Unit = { render() }
|
||||
private val ticker = object : Runnable {
|
||||
override fun run() {
|
||||
renderProgress()
|
||||
handler.postDelayed(this, 500)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
JamHub.init(this)
|
||||
setContentView(R.layout.activity_jam)
|
||||
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.jamRoot)) { view, insets ->
|
||||
val space = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
|
||||
view.setPadding(space.left, space.top, space.right, space.bottom)
|
||||
WindowInsetsCompat.CONSUMED
|
||||
}
|
||||
status = findViewById(R.id.jamStatus)
|
||||
setup = findViewById(R.id.jamSetup)
|
||||
panel = findViewById(R.id.jamPanel)
|
||||
leave = findViewById(R.id.jamLeave)
|
||||
nameInput = findViewById(R.id.jamName)
|
||||
codeInput = findViewById(R.id.jamCode)
|
||||
addInput = findViewById(R.id.jamAddInput)
|
||||
addButton = findViewById(R.id.jamAddButton)
|
||||
seek = findViewById(R.id.jamSeek)
|
||||
allControl = findViewById(R.id.jamAllControl)
|
||||
|
||||
nameInput.setText(JamHub.savedName())
|
||||
findViewById<View>(R.id.jamBack).setOnClickListener { finish() }
|
||||
findViewById<View>(R.id.jamStart).setOnClickListener { startJam() }
|
||||
findViewById<View>(R.id.jamJoin).setOnClickListener { joinJam(codeInput.text.toString()) }
|
||||
codeInput.setOnEditorActionListener { _, _, _ -> joinJam(codeInput.text.toString()); true }
|
||||
leave.setOnClickListener { JamHub.leave() }
|
||||
findViewById<View>(R.id.jamPlayPause).setOnClickListener { JamHub.playPause() }
|
||||
findViewById<View>(R.id.jamNext).setOnClickListener { JamHub.send("skip") }
|
||||
findViewById<View>(R.id.jamPrevious).setOnClickListener { JamHub.send("previous") }
|
||||
addButton.setOnClickListener { add() }
|
||||
addInput.setOnEditorActionListener { _, actionId, event ->
|
||||
if (actionId == EditorInfo.IME_ACTION_GO || event?.keyCode == KeyEvent.KEYCODE_ENTER) { add(); true } else false
|
||||
}
|
||||
findViewById<View>(R.id.jamShare).setOnClickListener { share() }
|
||||
findViewById<View>(R.id.jamCopy).setOnClickListener { copy() }
|
||||
findViewById<View>(R.id.jamEnd).setOnClickListener {
|
||||
AlertDialog.Builder(this)
|
||||
.setMessage(R.string.jam_end_confirm)
|
||||
.setPositiveButton(R.string.jam_end) { _, _ -> JamHub.send("end") }
|
||||
.setNegativeButton(R.string.pc_cancel, null)
|
||||
.show()
|
||||
}
|
||||
allControl.setOnCheckedChangeListener { button, checked ->
|
||||
if (button.isPressed) JamHub.send("settings", "allControl" to checked)
|
||||
}
|
||||
seek.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
|
||||
override fun onProgressChanged(bar: SeekBar, progress: Int, fromUser: Boolean) {}
|
||||
override fun onStartTrackingTouch(bar: SeekBar) { seeking = true }
|
||||
override fun onStopTrackingTouch(bar: SeekBar) {
|
||||
seeking = false
|
||||
JamHub.seekFraction(bar.progress / 1000.0)
|
||||
}
|
||||
})
|
||||
handleIntent(intent)
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
handleIntent(intent)
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
JamHub.listeners.add(listener)
|
||||
handler.post(ticker)
|
||||
render()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
JamHub.listeners.remove(listener)
|
||||
handler.removeCallbacks(ticker)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Einladungen und Teilen
|
||||
|
||||
private fun handleIntent(intent: Intent?) {
|
||||
when (intent?.action) {
|
||||
Intent.ACTION_VIEW -> JamSync.normalizeCode(intent.data?.toString())?.let { code ->
|
||||
codeInput.setText(code)
|
||||
if (nameInput.text.isNotBlank()) joinJam(code) else nameInput.requestFocus()
|
||||
}
|
||||
Intent.ACTION_SEND -> {
|
||||
val videoId = JamSync.videoIdFromSharedText(intent.getStringExtra(Intent.EXTRA_TEXT)) ?: return
|
||||
if (JamHub.active) {
|
||||
JamHub.addVideo(videoId)
|
||||
Toast.makeText(this, R.string.jam_added_shared, Toast.LENGTH_SHORT).show()
|
||||
} else {
|
||||
pendingVideoId = videoId
|
||||
status.setText(R.string.jam_share_no_jam)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun takeName(): String? {
|
||||
val name = nameInput.text.toString().trim()
|
||||
if (name.isEmpty()) {
|
||||
status.setText(R.string.jam_status_need_name)
|
||||
nameInput.requestFocus()
|
||||
return null
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
private fun startJam() {
|
||||
val name = takeName() ?: return
|
||||
// Erster Song: per "Teilen" empfangen oder das, was gerade in Playtube laeuft.
|
||||
val first = pendingVideoId?.let { JSONObject().put("t", "add").put("videoId", it) }
|
||||
?: JamHub.pageVideo?.let { page ->
|
||||
JSONObject().put("t", "add").put("videoId", page.videoId).put("title", page.title).put("artist", page.artist)
|
||||
}
|
||||
pendingVideoId = null
|
||||
JamHub.start(name, first)
|
||||
}
|
||||
|
||||
private fun joinJam(raw: String) {
|
||||
val name = takeName() ?: return
|
||||
JamHub.join(raw, name)
|
||||
pendingVideoId?.let { id -> handler.postDelayed({ if (JamHub.active) JamHub.addVideo(id) }, 2500) }
|
||||
pendingVideoId = null
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Bedienung
|
||||
|
||||
private fun add() {
|
||||
val text = addInput.text.toString().trim()
|
||||
if (text.isEmpty()) return
|
||||
val videoId = JamSync.parseVideoId(text)
|
||||
if (videoId != null) {
|
||||
JamHub.addVideo(videoId)
|
||||
addInput.setText("")
|
||||
status.text = getString(R.string.jam_added, videoId)
|
||||
return
|
||||
}
|
||||
if (JamHub.state?.search != true) {
|
||||
status.setText(R.string.jam_error_bad_video)
|
||||
return
|
||||
}
|
||||
JamHub.search(text) { found ->
|
||||
if (found == null) {
|
||||
status.setText(R.string.jam_error_search)
|
||||
} else {
|
||||
results = found
|
||||
renderResults()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun inviteLink(): String? = JamHub.code?.let { "${JamHub.server}/$it" }
|
||||
|
||||
private fun share() {
|
||||
val link = inviteLink() ?: return
|
||||
val send = Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, getString(R.string.jam_share_text, link))
|
||||
startActivity(Intent.createChooser(send, getString(R.string.jam_invite)))
|
||||
}
|
||||
|
||||
private fun copy() {
|
||||
val link = inviteLink() ?: return
|
||||
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("Playtube Jam", link))
|
||||
Toast.makeText(this, R.string.jam_copied, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Anzeige
|
||||
|
||||
private fun render() {
|
||||
status.text = JamHub.status
|
||||
val active = JamHub.active
|
||||
setup.visibility = if (active) View.GONE else View.VISIBLE
|
||||
panel.visibility = if (active) View.VISIBLE else View.GONE
|
||||
leave.visibility = if (active) View.VISIBLE else View.GONE
|
||||
if (!active) return
|
||||
val code = JamHub.code ?: return
|
||||
findViewById<TextView>(R.id.jamInviteCode).text = JamSync.prettyCode(code)
|
||||
findViewById<TextView>(R.id.jamInviteLink).text = inviteLink()
|
||||
val state = JamHub.state ?: return
|
||||
|
||||
val item = state.current
|
||||
findViewById<TextView>(R.id.jamNowTitle).text = item?.title ?: getString(R.string.jam_nothing)
|
||||
findViewById<TextView>(R.id.jamNowArtist).text = item?.let { subtitle(it) } ?: ""
|
||||
val cover = findViewById<ImageView>(R.id.jamCover)
|
||||
cover.setImageDrawable(null)
|
||||
item?.thumb?.takeIf { it.startsWith("https://") }?.let { url ->
|
||||
ImageCache.load(url, (96 * resources.displayMetrics.density).toInt()) { bitmap ->
|
||||
if (JamHub.state?.current?.thumb == url) cover.setImageBitmap(bitmap)
|
||||
}
|
||||
}
|
||||
findViewById<View>(R.id.jamCantPlay).visibility = if (JamHub.isUnplayable(item?.id)) View.VISIBLE else View.GONE
|
||||
findViewById<ImageButton>(R.id.jamPlayPause).setImageResource(if (state.playback.paused) R.drawable.ic_play else R.drawable.ic_pause)
|
||||
for (id in listOf(R.id.jamPlayPause, R.id.jamNext, R.id.jamPrevious)) {
|
||||
findViewById<View>(id).apply {
|
||||
isEnabled = state.canControl
|
||||
alpha = if (state.canControl) 1f else 0.4f
|
||||
}
|
||||
}
|
||||
seek.isEnabled = state.canControl && item != null
|
||||
findViewById<View>(R.id.jamHostBox).visibility = if (state.isHost) View.VISIBLE else View.GONE
|
||||
allControl.isChecked = state.allControl
|
||||
addInput.setHint(if (state.search) R.string.jam_search_hint else R.string.jam_add_hint)
|
||||
addButton.setText(if (state.search) R.string.jam_search else R.string.jam_add)
|
||||
|
||||
val queue = findViewById<LinearLayout>(R.id.jamQueue)
|
||||
queue.removeAllViews()
|
||||
if (state.queue.isEmpty()) queue.addView(emptyText(R.string.jam_queue_empty))
|
||||
for (q in state.queue) {
|
||||
queue.addView(
|
||||
row(
|
||||
q.title, subtitle(q), image = q.thumb, initial = null,
|
||||
action1 = if (state.canControl) R.drawable.ic_play to { JamHub.send("jump", "itemId" to q.id) } else null,
|
||||
action2 = if (state.canControl || q.by == state.you) R.drawable.ic_close to { JamHub.send("remove", "itemId" to q.id) } else null,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
val members = findViewById<LinearLayout>(R.id.jamMembers)
|
||||
members.removeAllViews()
|
||||
for (m in state.members) {
|
||||
val info = buildList {
|
||||
if (m.host) add(getString(R.string.jam_host))
|
||||
add(getString(when (m.client) { "pc" -> R.string.jam_client_pc; "android" -> R.string.jam_client_android; else -> R.string.jam_client_web }))
|
||||
if (!m.online) add(getString(R.string.jam_offline))
|
||||
if (m.cantPlay) add(getString(R.string.jam_cant_play))
|
||||
}.joinToString(" · ")
|
||||
val name = if (m.id == state.you) getString(R.string.jam_you, m.name) else m.name
|
||||
val kick = if (state.isHost && m.id != state.you) {
|
||||
R.drawable.ic_close to {
|
||||
AlertDialog.Builder(this)
|
||||
.setMessage(getString(R.string.jam_kick_confirm, m.name))
|
||||
.setPositiveButton(R.string.jam_kick) { _, _ -> JamHub.send("kick", "memberId" to m.id) }
|
||||
.setNegativeButton(R.string.pc_cancel, null)
|
||||
.show()
|
||||
Unit
|
||||
}
|
||||
} else null
|
||||
members.addView(row(name, info, image = null, initial = m.name.take(1).uppercase(), action1 = null, action2 = kick).apply {
|
||||
alpha = if (m.online) 1f else 0.5f
|
||||
})
|
||||
}
|
||||
renderProgress()
|
||||
}
|
||||
|
||||
private fun renderResults() {
|
||||
val box = findViewById<LinearLayout>(R.id.jamResults)
|
||||
box.removeAllViews()
|
||||
for (r in results) {
|
||||
box.addView(
|
||||
row(
|
||||
r.title, r.artist, image = r.thumb, initial = null,
|
||||
action1 = R.drawable.ic_queue_music to {
|
||||
JamHub.addVideo(r.videoId, r.title, r.artist, r.thumb, next = true)
|
||||
status.text = getString(R.string.jam_added, r.title)
|
||||
},
|
||||
action2 = R.drawable.ic_add to {
|
||||
JamHub.addVideo(r.videoId, r.title, r.artist, r.thumb)
|
||||
status.text = getString(R.string.jam_added, r.title)
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun renderProgress() {
|
||||
val state = JamHub.state ?: return
|
||||
val want = JamSync.target(state, JamHub.clock.serverNow(System.currentTimeMillis().toDouble()))
|
||||
val dur = want?.dur ?: JamHub.lastDuration
|
||||
val pos = (want?.pos ?: 0.0).coerceAtLeast(0.0).let { if (dur > 0) it.coerceAtMost(dur) else it }
|
||||
findViewById<TextView>(R.id.jamTime).text = JamSync.formatTime(pos)
|
||||
findViewById<TextView>(R.id.jamDuration).text = JamSync.formatTime(dur)
|
||||
if (!seeking) seek.progress = if (dur > 0) (pos / dur * 1000).toInt() else 0
|
||||
}
|
||||
|
||||
private fun subtitle(item: JamSync.Item): String {
|
||||
val by = getString(R.string.jam_by, item.byName)
|
||||
return if (item.artist.isBlank()) by else "${item.artist} · $by"
|
||||
}
|
||||
|
||||
private fun emptyText(text: Int) = TextView(this).apply {
|
||||
setText(text)
|
||||
setTextColor(getColor(R.color.text_muted))
|
||||
setPadding(0, 12, 0, 12)
|
||||
}
|
||||
|
||||
private fun row(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
image: String?,
|
||||
initial: String?,
|
||||
action1: Pair<Int, () -> Unit>?,
|
||||
action2: Pair<Int, () -> Unit>?,
|
||||
): View {
|
||||
val view = LayoutInflater.from(this).inflate(R.layout.item_jam_row, null, false)
|
||||
view.findViewById<TextView>(R.id.jamRowTitle).text = title
|
||||
view.findViewById<TextView>(R.id.jamRowSubtitle).text = subtitle
|
||||
val imageView = view.findViewById<ImageView>(R.id.jamRowImage)
|
||||
val avatar = view.findViewById<TextView>(R.id.jamRowAvatar)
|
||||
if (initial != null) {
|
||||
imageView.visibility = View.GONE
|
||||
avatar.visibility = View.VISIBLE
|
||||
avatar.text = initial
|
||||
} else if (image != null && image.startsWith("https://")) {
|
||||
ImageCache.load(image, (64 * resources.displayMetrics.density).toInt()) { bitmap -> imageView.setImageBitmap(bitmap) }
|
||||
}
|
||||
for ((id, action) in listOf(R.id.jamRowAction1 to action1, R.id.jamRowAction2 to action2)) {
|
||||
val button = view.findViewById<ImageButton>(id)
|
||||
if (action != null) {
|
||||
button.visibility = View.VISIBLE
|
||||
button.setImageResource(action.first)
|
||||
button.setOnClickListener { action.second() }
|
||||
}
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun start(context: Context) {
|
||||
context.startActivity(Intent(context, JamActivity::class.java))
|
||||
}
|
||||
|
||||
fun open(context: Context, uri: Uri) {
|
||||
context.startActivity(Intent(Intent.ACTION_VIEW, uri, context, JamActivity::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
package de.fojadrachi.playtube
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import okhttp3.Call
|
||||
import okhttp3.Callback
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrl
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.Response
|
||||
import okhttp3.WebSocket
|
||||
import okhttp3.WebSocketListener
|
||||
import org.json.JSONObject
|
||||
import java.io.IOException
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* Playtube Jam: Verbindung zum Jam-Server und gemeinsamer Zustand fuer [JamActivity] (Anzeige)
|
||||
* und [MainActivity] (spielt in ihrer YouTube-Music-WebView ab). Alles auf dem Hauptthread.
|
||||
*/
|
||||
object JamHub {
|
||||
private const val PREFS = "playtube"
|
||||
private const val KEY_NAME = "jam_name"
|
||||
private const val KEY_CODE = "jam_last_code"
|
||||
private const val KEY_TOKEN = "jam_last_token"
|
||||
/** Spielt ein Titel so lange nicht an, gilt er hier als nicht abspielbar. */
|
||||
private const val STUCK_LIMIT_MS = 15_000L
|
||||
|
||||
val server: String get() = BuildConfig.JAM_SERVER
|
||||
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val http = OkHttpClient.Builder()
|
||||
.connectTimeout(10, TimeUnit.SECONDS)
|
||||
.readTimeout(0, TimeUnit.SECONDS)
|
||||
.pingInterval(20, TimeUnit.SECONDS)
|
||||
.build()
|
||||
|
||||
private var appContext: Context? = null
|
||||
private var socket: WebSocket? = null
|
||||
private var reconnectDelay = 1000L
|
||||
private var pings = 0
|
||||
private var name = ""
|
||||
private var token: String? = null
|
||||
|
||||
var code: String? = null
|
||||
private set
|
||||
var state: JamSync.State? = null
|
||||
private set
|
||||
var status: String = ""
|
||||
private set
|
||||
val clock = JamSync.Clock()
|
||||
|
||||
/** Anzeige (JamActivity) - wird bei jeder Aenderung aufgerufen. */
|
||||
val listeners = LinkedHashSet<() -> Unit>()
|
||||
|
||||
val active: Boolean get() = code != null
|
||||
|
||||
/** Was gerade in Playtube laeuft (von MainActivity) - wird beim Starten der erste Song. */
|
||||
data class PageVideo(val videoId: String, val title: String, val artist: String)
|
||||
var pageVideo: PageVideo? = null
|
||||
|
||||
// Abgleich-Zustand des eigenen Players
|
||||
private val unplayable = HashSet<String>()
|
||||
private val reported = HashSet<String>()
|
||||
private var expectUntil = 0L
|
||||
private var pendingLoad: Pair<String, Long>? = null
|
||||
private var stuckSince: Pair<String, Long>? = null
|
||||
private var diverge = 0
|
||||
var lastDuration = 0.0
|
||||
private set
|
||||
|
||||
fun init(context: Context) {
|
||||
appContext = context.applicationContext
|
||||
}
|
||||
|
||||
private fun prefs() = appContext!!.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
fun savedName(): String = prefs().getString(KEY_NAME, "") ?: ""
|
||||
|
||||
private fun notifyListeners() = listeners.toList().forEach { it() }
|
||||
|
||||
private fun setStatus(text: String) {
|
||||
status = text
|
||||
notifyListeners()
|
||||
}
|
||||
|
||||
private fun str(id: Int, vararg args: Any): String = appContext!!.getString(id, *args)
|
||||
|
||||
fun isUnplayable(itemId: String?): Boolean = itemId != null && itemId in unplayable
|
||||
|
||||
// ------------------------------------------------------------------ Starten, Beitreten, Verlassen
|
||||
|
||||
fun start(displayName: String, firstSong: JSONObject?) {
|
||||
if (active) return
|
||||
rememberName(displayName)
|
||||
setStatus(str(R.string.jam_status_creating))
|
||||
val body = JSONObject().put("name", displayName).put("client", "android").toString()
|
||||
val request = Request.Builder().url("$server/api/jam").post(body.toRequestBody("application/json".toMediaType())).build()
|
||||
http.newCall(request).enqueue(object : Callback {
|
||||
override fun onFailure(call: Call, e: IOException) { main.post { setStatus(str(R.string.jam_status_failed)) } }
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
val text = response.use { if (it.isSuccessful) it.body?.string() else null }
|
||||
main.post {
|
||||
val json = text?.let { runCatching { JSONObject(it) }.getOrNull() }
|
||||
if (json == null) {
|
||||
setStatus(str(R.string.jam_status_failed))
|
||||
} else {
|
||||
connect(json.getString("code"), json.getString("token"))
|
||||
firstSong?.let { send(it) }
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fun join(rawCode: String, displayName: String) {
|
||||
val joinCode = JamSync.normalizeCode(rawCode)
|
||||
if (joinCode == null) {
|
||||
setStatus(str(R.string.jam_status_bad_code))
|
||||
return
|
||||
}
|
||||
if (active) {
|
||||
if (code != joinCode) setStatus(str(R.string.jam_status_in_other))
|
||||
return
|
||||
}
|
||||
rememberName(displayName)
|
||||
setStatus(str(R.string.jam_status_joining))
|
||||
val request = Request.Builder().url("$server/api/jam/$joinCode").build()
|
||||
http.newCall(request).enqueue(object : Callback {
|
||||
override fun onFailure(call: Call, e: IOException) { main.post { setStatus(str(R.string.jam_status_failed)) } }
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
val status = response.use { it.code }
|
||||
main.post {
|
||||
when (status) {
|
||||
200 -> {
|
||||
val prefs = prefs()
|
||||
val saved = if (prefs.getString(KEY_CODE, null) == joinCode) prefs.getString(KEY_TOKEN, null) else null
|
||||
connect(joinCode, saved)
|
||||
}
|
||||
404 -> setStatus(str(R.string.jam_status_not_found))
|
||||
else -> setStatus(str(R.string.jam_status_failed))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private fun rememberName(displayName: String) {
|
||||
name = displayName
|
||||
prefs().edit().putString(KEY_NAME, displayName).apply()
|
||||
}
|
||||
|
||||
private fun connect(joinCode: String, savedToken: String?) {
|
||||
code = joinCode
|
||||
token = savedToken
|
||||
state = null
|
||||
unplayable.clear()
|
||||
reported.clear()
|
||||
pendingLoad = null
|
||||
stuckSince = null
|
||||
prefs().edit().putString(KEY_CODE, joinCode).putString(KEY_TOKEN, savedToken ?: "").apply()
|
||||
openSocket()
|
||||
notifyListeners()
|
||||
}
|
||||
|
||||
private fun openSocket() {
|
||||
val joinCode = code ?: return
|
||||
val wsUrl = server.replaceFirst("https://", "wss://").replaceFirst("http://", "ws://") + "/api/jam/$joinCode/ws"
|
||||
socket = http.newWebSocket(Request.Builder().url(wsUrl).build(), object : WebSocketListener() {
|
||||
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||
main.post {
|
||||
if (socket !== webSocket) return@post
|
||||
reconnectDelay = 1000L
|
||||
val hello = JSONObject().put("t", "hello").put("name", name).put("client", "android")
|
||||
token?.let { hello.put("token", it) }
|
||||
webSocket.send(hello.toString())
|
||||
pings = 0
|
||||
ping()
|
||||
setStatus(str(R.string.jam_status_connected))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||
val receivedAt = System.currentTimeMillis().toDouble()
|
||||
main.post { if (socket === webSocket) handle(text, receivedAt) }
|
||||
}
|
||||
|
||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||
main.post { if (socket === webSocket) lost() }
|
||||
}
|
||||
|
||||
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||
main.post { if (socket === webSocket) lost() }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private val pingTask = Runnable { ping() }
|
||||
|
||||
private fun ping() {
|
||||
main.removeCallbacks(pingTask)
|
||||
val ws = socket ?: return
|
||||
ws.send(JSONObject().put("t", "ping").put("c", System.currentTimeMillis().toDouble()).toString())
|
||||
pings++
|
||||
main.postDelayed(pingTask, if (pings < 6) 800L else 15_000L)
|
||||
}
|
||||
|
||||
private fun lost() {
|
||||
socket = null
|
||||
main.removeCallbacks(pingTask)
|
||||
if (!active) return
|
||||
setStatus(str(R.string.jam_status_reconnecting))
|
||||
main.postDelayed({ if (active && socket == null) openSocket() }, reconnectDelay)
|
||||
reconnectDelay = (reconnectDelay * 2).coerceAtMost(20_000L)
|
||||
}
|
||||
|
||||
private fun handle(text: String, receivedAt: Double) {
|
||||
val msg = runCatching { JSONObject(text) }.getOrNull() ?: return
|
||||
when (msg.optString("t")) {
|
||||
"pong" -> clock.add(msg.optDouble("c"), msg.optDouble("s"), receivedAt)
|
||||
"welcome" -> {
|
||||
token = msg.optString("token")
|
||||
prefs().edit().putString(KEY_TOKEN, token).apply()
|
||||
}
|
||||
"state" -> {
|
||||
val parsed = JamSync.parseState(msg)
|
||||
clock.hint(parsed.serverNow, System.currentTimeMillis().toDouble())
|
||||
state = parsed
|
||||
notifyListeners()
|
||||
}
|
||||
"ended" -> close(endedText(msg.optString("reason")), forget = true)
|
||||
"error" -> when (val error = msg.optString("error")) {
|
||||
"not_found", "kicked", "full" -> close(endedText(error), forget = true)
|
||||
else -> setStatus(errorText(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun endedText(reason: String): String = str(
|
||||
when (reason) {
|
||||
"host_ended" -> R.string.jam_ended_host
|
||||
"expired" -> R.string.jam_ended_expired
|
||||
"kicked" -> R.string.jam_ended_kicked
|
||||
"left" -> R.string.jam_ended_left
|
||||
"full" -> R.string.jam_ended_full
|
||||
"not_found" -> R.string.jam_status_not_found
|
||||
else -> R.string.jam_ended_over
|
||||
},
|
||||
)
|
||||
|
||||
fun errorText(error: String): String = when (error) {
|
||||
"not_allowed" -> str(R.string.jam_error_not_allowed)
|
||||
"queue_full" -> str(R.string.jam_error_queue_full)
|
||||
"bad_video" -> str(R.string.jam_error_bad_video)
|
||||
"rate_limited" -> str(R.string.jam_error_rate_limited)
|
||||
else -> str(R.string.jam_error_other, error)
|
||||
}
|
||||
|
||||
/** Jam lokal beenden. */
|
||||
private fun close(message: String, forget: Boolean) {
|
||||
val ws = socket
|
||||
socket = null
|
||||
code = null
|
||||
state = null
|
||||
main.removeCallbacks(pingTask)
|
||||
ws?.close(1000, null)
|
||||
if (forget) prefs().edit().remove(KEY_CODE).remove(KEY_TOKEN).apply()
|
||||
// Den letzten Jam-Titel nicht einfach weiterlaufen lassen.
|
||||
PlaybackHub.send(PlayerCommand.Pause)
|
||||
setStatus(message)
|
||||
}
|
||||
|
||||
fun leave() {
|
||||
if (!active) return
|
||||
send(JSONObject().put("t", "leave"))
|
||||
main.postDelayed({ if (active) close(str(R.string.jam_ended_left), forget = true) }, 800)
|
||||
}
|
||||
|
||||
fun send(msg: JSONObject) {
|
||||
socket?.send(msg.toString())
|
||||
}
|
||||
|
||||
fun send(type: String, vararg pairs: Pair<String, Any?>) {
|
||||
val msg = JSONObject().put("t", type)
|
||||
for ((k, v) in pairs) msg.put(k, v ?: JSONObject.NULL)
|
||||
send(msg)
|
||||
}
|
||||
|
||||
fun playPause() {
|
||||
val s = state ?: return
|
||||
send(if (s.playback.paused) "play" else "pause")
|
||||
}
|
||||
|
||||
fun seekFraction(fraction: Double) {
|
||||
val dur = state?.current?.dur ?: lastDuration.takeIf { it > 0 } ?: return
|
||||
send("seek", "pos" to Math.round(fraction.coerceIn(0.0, 1.0) * dur).toDouble())
|
||||
}
|
||||
|
||||
fun addVideo(videoId: String, title: String? = null, artist: String? = null, thumb: String? = null, next: Boolean = false) {
|
||||
val msg = JSONObject().put("t", "add").put("videoId", videoId).put("next", next)
|
||||
title?.let { msg.put("title", it) }
|
||||
artist?.let { msg.put("artist", it) }
|
||||
thumb?.let { msg.put("thumb", it) }
|
||||
send(msg)
|
||||
}
|
||||
|
||||
data class SearchResult(val videoId: String, val title: String, val artist: String, val thumb: String)
|
||||
|
||||
fun search(query: String, done: (List<SearchResult>?) -> Unit) {
|
||||
val url = "$server/api/search".toHttpUrl().newBuilder().addQueryParameter("q", query).build()
|
||||
http.newCall(Request.Builder().url(url).build()).enqueue(object : Callback {
|
||||
override fun onFailure(call: Call, e: IOException) { main.post { done(null) } }
|
||||
override fun onResponse(call: Call, response: Response) {
|
||||
val text = response.use { if (it.isSuccessful) it.body?.string() else null }
|
||||
val results = text?.let {
|
||||
runCatching {
|
||||
val array = JSONObject(it).getJSONArray("results")
|
||||
(0 until array.length()).map { i ->
|
||||
val o = array.getJSONObject(i)
|
||||
SearchResult(o.optString("videoId"), o.optString("title"), o.optString("artist"), o.optString("thumb"))
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
main.post { done(results) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Wiedergabe-Befehle (Benachrichtigung, Kopfhoerer, "PC steuern" nicht) an den Jam umleiten.
|
||||
* true = erledigt.
|
||||
*/
|
||||
fun intercept(command: PlayerCommand): Boolean {
|
||||
val s = state ?: return false
|
||||
if (!s.canControl) return true
|
||||
when (command) {
|
||||
PlayerCommand.PlayPause -> playPause()
|
||||
PlayerCommand.Play -> send("play")
|
||||
PlayerCommand.Pause -> send("pause")
|
||||
PlayerCommand.Next -> send("skip")
|
||||
PlayerCommand.Previous -> send("previous")
|
||||
is PlayerCommand.SeekTo -> send("seek", "pos" to command.positionMs / 1000.0)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Abgleich des Players
|
||||
|
||||
/** Was die WebView tun soll: neue URL laden und/oder Skripte ausfuehren. */
|
||||
data class Actions(val loadUrl: String?, val scripts: List<String>)
|
||||
|
||||
/** Wertet das Ergebnis von [JamSync.PROBE] aus (MainActivity ruft das alle 700 ms). */
|
||||
fun syncPlayer(probe: JSONObject): Actions {
|
||||
val s = state ?: return Actions(null, emptyList())
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val want = JamSync.target(s, clock.serverNow(System.currentTimeMillis().toDouble()))
|
||||
val local = JamSync.Local(
|
||||
videoId = probe.optString("id").takeIf { it.isNotEmpty() && it != "null" && !probe.isNull("id") },
|
||||
pos = probe.optDouble("t", 0.0),
|
||||
paused = probe.optBoolean("paused", true),
|
||||
)
|
||||
val duration = probe.optDouble("d", 0.0)
|
||||
val scripts = ArrayList<String>()
|
||||
var load: String? = null
|
||||
val pause = MediaScripts.forCommand(PlayerCommand.Pause)
|
||||
val matches = want != null && local.videoId == want.videoId
|
||||
if (matches) {
|
||||
pendingLoad = null
|
||||
if (duration > 0) lastDuration = duration
|
||||
}
|
||||
if (want == null) {
|
||||
if (JamSync.decide(null, local).isNotEmpty()) scripts.add(pause)
|
||||
return Actions(null, scripts)
|
||||
}
|
||||
if (want.itemId in unplayable) {
|
||||
if (!local.paused) scripts.add(pause)
|
||||
return Actions(null, scripts)
|
||||
}
|
||||
if (probe.optBoolean("ad")) return Actions(null, scripts)
|
||||
if (matches) {
|
||||
if (duration > 0 && want.dur == null && reported.add("d" + want.itemId)) {
|
||||
send("duration", "itemId" to want.itemId, "dur" to Math.round(duration).toDouble())
|
||||
}
|
||||
if (want.pos > 5 && JamSync.reachedEnd(local, duration, probe.optBoolean("ended")) && reported.add("e" + want.itemId)) {
|
||||
send("ended", "itemId" to want.itemId)
|
||||
}
|
||||
}
|
||||
// Mit Steuerrecht selbst in der Seite pausiert/fortgesetzt: fuer alle uebernehmen.
|
||||
if (s.canControl && matches && now > expectUntil && want.pos >= 1 && duration > 0 && local.pos < duration - 2) {
|
||||
diverge = if (local.paused != want.paused) diverge + 1 else 0
|
||||
if (diverge >= 2) {
|
||||
diverge = 0
|
||||
expectUntil = now + 3000
|
||||
send(if (local.paused) "pause" else "play")
|
||||
return Actions(null, scripts)
|
||||
}
|
||||
} else {
|
||||
diverge = 0
|
||||
}
|
||||
// Spielt der Titel hier nicht an (gesperrt, Region, privat): ueberspringen.
|
||||
val error = probe.optBoolean("error")
|
||||
if (!want.paused && want.pos >= 1 && (!matches || local.paused || error)) {
|
||||
val since = stuckSince
|
||||
if (since == null || since.first != want.itemId) {
|
||||
stuckSince = want.itemId to now
|
||||
} else if (now - since.second > if (error) 3000 else STUCK_LIMIT_MS) {
|
||||
unplayable.add(want.itemId)
|
||||
send("unplayable", "itemId" to want.itemId)
|
||||
scripts.add(pause)
|
||||
notifyListeners()
|
||||
return Actions(null, scripts)
|
||||
}
|
||||
} else {
|
||||
stuckSince = null
|
||||
}
|
||||
for (step in JamSync.decide(want, local)) {
|
||||
when (step) {
|
||||
is JamSync.Step.Load -> {
|
||||
val pending = pendingLoad
|
||||
if (pending == null || pending.first != step.videoId || now - pending.second > 12_000) {
|
||||
pendingLoad = step.videoId to now
|
||||
expectUntil = now + 8000
|
||||
load = JamSync.watchUrl(step.videoId)
|
||||
}
|
||||
break
|
||||
}
|
||||
is JamSync.Step.Seek -> {
|
||||
expectUntil = now + 3000
|
||||
scripts.add(MediaScripts.forCommand(PlayerCommand.SeekTo((step.pos * 1000).toLong())))
|
||||
}
|
||||
JamSync.Step.Play -> {
|
||||
expectUntil = now + 3000
|
||||
scripts.add(MediaScripts.forCommand(PlayerCommand.Play))
|
||||
}
|
||||
JamSync.Step.Pause -> {
|
||||
expectUntil = now + 3000
|
||||
scripts.add(pause)
|
||||
}
|
||||
}
|
||||
}
|
||||
return Actions(load, scripts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package de.fojadrachi.playtube
|
||||
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.max
|
||||
|
||||
/**
|
||||
* Playtube Jam: Protokoll und reine Sync-Logik (ohne Android-Klassen, mit JUnit getestet).
|
||||
* Dieselben Regeln gelten in Playtube am PC (src/jam.rs) und im Web-Client (public/sync.js).
|
||||
*
|
||||
* Wiedergabe-Modell des Servers: playback = { paused, position, ref }. Position zur Serverzeit T:
|
||||
* paused ? position : position + (T - ref) / 1000. Negativ heisst "startet gleich".
|
||||
*/
|
||||
object JamSync {
|
||||
const val TOLERANCE_S = 1.5
|
||||
private const val CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||
private val VIDEO_ID = Regex("^[A-Za-z0-9_-]{11}$")
|
||||
|
||||
data class Item(
|
||||
val id: String,
|
||||
val videoId: String,
|
||||
val title: String,
|
||||
val artist: String,
|
||||
val thumb: String,
|
||||
val dur: Double?,
|
||||
val by: String,
|
||||
val byName: String,
|
||||
)
|
||||
|
||||
data class Member(
|
||||
val id: String,
|
||||
val name: String,
|
||||
val client: String,
|
||||
val online: Boolean,
|
||||
val host: Boolean,
|
||||
val cantPlay: Boolean,
|
||||
)
|
||||
|
||||
data class Playback(val paused: Boolean, val position: Double, val ref: Double)
|
||||
|
||||
data class State(
|
||||
val code: String,
|
||||
val you: String,
|
||||
val hostId: String,
|
||||
val allControl: Boolean,
|
||||
val canControl: Boolean,
|
||||
val search: Boolean,
|
||||
val members: List<Member>,
|
||||
val current: Item?,
|
||||
val queue: List<Item>,
|
||||
val history: List<Item>,
|
||||
val playback: Playback,
|
||||
val serverNow: Double,
|
||||
) {
|
||||
val isHost: Boolean get() = you == hostId
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Codes und Links
|
||||
|
||||
/** "abc-234", "ABC 234" oder Einladungslink -> "ABC234", sonst null. */
|
||||
fun normalizeCode(input: String?): String? {
|
||||
if (input == null) return null
|
||||
var text = input.trim().substringBefore('?').substringBefore('#').trimEnd('/')
|
||||
if (text.contains('/')) text = text.substringAfterLast('/')
|
||||
val code = text.filter { !it.isWhitespace() && it != '-' }.uppercase()
|
||||
return if (code.length == 6 && code.all { it in CODE_ALPHABET }) code else null
|
||||
}
|
||||
|
||||
/** Video-ID aus ID oder YouTube-/YouTube-Music-Link. */
|
||||
fun parseVideoId(input: String?): String? {
|
||||
val text = input?.trim() ?: return null
|
||||
if (VIDEO_ID.matches(text)) return text
|
||||
val rest = text.substringAfter("://", text)
|
||||
val host = rest.substringBefore('/').lowercase().removePrefix("www.").removePrefix("m.").removePrefix("music.")
|
||||
val path = rest.substringAfter('/', "").substringBefore('#')
|
||||
val pathOnly = path.substringBefore('?')
|
||||
val query = path.substringAfter('?', "")
|
||||
val id = when (host) {
|
||||
"youtu.be" -> pathOnly.substringBefore('/')
|
||||
"youtube.com", "youtube-nocookie.com" ->
|
||||
query.split('&').firstOrNull { it.startsWith("v=") }?.removePrefix("v=")
|
||||
?: pathOnly.split('/').let { parts ->
|
||||
if (parts.size >= 2 && parts[0] in setOf("shorts", "embed", "live", "v")) parts[1] else null
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
return id?.takeIf { VIDEO_ID.matches(it) }
|
||||
}
|
||||
|
||||
/** Sucht in einem geteilten Text (z. B. aus der YouTube-App) den ersten YouTube-Link. */
|
||||
fun videoIdFromSharedText(text: String?): String? =
|
||||
text?.split(Regex("\\s+"))?.firstNotNullOfOrNull { parseVideoId(it) }
|
||||
|
||||
fun prettyCode(code: String): String = if (code.length == 6) code.substring(0, 3) + " " + code.substring(3) else code
|
||||
|
||||
fun formatTime(seconds: Double): String {
|
||||
val total = if (seconds.isFinite() && seconds > 0) seconds.toLong() else 0L
|
||||
val h = total / 3600
|
||||
val m = (total / 60) % 60
|
||||
val s = total % 60
|
||||
return if (h > 0) String.format("%d:%02d:%02d", h, m, s) else String.format("%d:%02d", m, s)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Zustand lesen
|
||||
|
||||
fun parseState(json: JSONObject): State {
|
||||
fun item(o: JSONObject?): Item? = o?.let {
|
||||
Item(
|
||||
id = it.optString("id"),
|
||||
videoId = it.optString("videoId"),
|
||||
title = it.optString("title"),
|
||||
artist = it.optString("artist"),
|
||||
thumb = it.optString("thumb"),
|
||||
dur = if (it.isNull("dur") || !it.has("dur")) null else it.optDouble("dur").takeIf { d -> d.isFinite() },
|
||||
by = it.optString("by"),
|
||||
byName = it.optString("byName"),
|
||||
)
|
||||
}
|
||||
fun items(a: JSONArray?): List<Item> =
|
||||
if (a == null) emptyList() else (0 until a.length()).mapNotNull { item(a.optJSONObject(it)) }
|
||||
val members = json.optJSONArray("members")?.let { a ->
|
||||
(0 until a.length()).mapNotNull { a.optJSONObject(it) }.map {
|
||||
Member(
|
||||
id = it.optString("id"),
|
||||
name = it.optString("name"),
|
||||
client = it.optString("client"),
|
||||
online = it.optBoolean("online"),
|
||||
host = it.optBoolean("host"),
|
||||
cantPlay = it.optBoolean("cantPlay"),
|
||||
)
|
||||
}
|
||||
} ?: emptyList()
|
||||
val pb = json.optJSONObject("playback")
|
||||
return State(
|
||||
code = json.optString("code"),
|
||||
you = json.optString("you"),
|
||||
hostId = json.optString("hostId"),
|
||||
allControl = json.optBoolean("allControl"),
|
||||
canControl = json.optBoolean("canControl"),
|
||||
search = json.optJSONObject("features")?.optBoolean("search") ?: false,
|
||||
members = members,
|
||||
current = item(json.optJSONObject("current")),
|
||||
queue = items(json.optJSONArray("queue")),
|
||||
history = items(json.optJSONArray("history")),
|
||||
playback = Playback(
|
||||
paused = pb?.optBoolean("paused", true) ?: true,
|
||||
position = pb?.optDouble("position", 0.0) ?: 0.0,
|
||||
ref = pb?.optDouble("ref", 0.0) ?: 0.0,
|
||||
),
|
||||
serverNow = json.optDouble("serverNow", 0.0),
|
||||
)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Zeit und Abgleich
|
||||
|
||||
/** Zeitabgleich ueber ping/pong: die Messung mit der kuerzesten Laufzeit zaehlt. */
|
||||
class Clock {
|
||||
private val samples = ArrayList<Pair<Double, Double>>()
|
||||
var offset = 0.0
|
||||
private set
|
||||
|
||||
fun add(c: Double, s: Double, r: Double) {
|
||||
val rtt = r - c
|
||||
if (rtt < 0 || rtt > 30_000) return
|
||||
samples.add(rtt to s - (c + rtt / 2))
|
||||
if (samples.size > 10) samples.removeAt(0)
|
||||
offset = samples.minByOrNull { it.first }!!.second
|
||||
}
|
||||
|
||||
fun hint(serverNow: Double, localNow: Double) {
|
||||
if (samples.isEmpty()) offset = serverNow - localNow
|
||||
}
|
||||
|
||||
fun serverNow(localNow: Double): Double = localNow + offset
|
||||
}
|
||||
|
||||
fun positionAt(playback: Playback, serverNow: Double): Double =
|
||||
if (playback.paused) playback.position else playback.position + (serverNow - playback.ref) / 1000.0
|
||||
|
||||
data class Target(val videoId: String, val itemId: String, val pos: Double, val paused: Boolean, val dur: Double?)
|
||||
|
||||
fun target(state: State?, serverNow: Double): Target? {
|
||||
val item = state?.current ?: return null
|
||||
return Target(item.videoId, item.id, positionAt(state.playback, serverNow), state.playback.paused, item.dur)
|
||||
}
|
||||
|
||||
data class Local(val videoId: String?, val pos: Double, val paused: Boolean)
|
||||
|
||||
sealed class Step {
|
||||
data class Load(val videoId: String, val pos: Double) : Step()
|
||||
data class Seek(val pos: Double) : Step()
|
||||
data object Play : Step()
|
||||
data object Pause : Step()
|
||||
}
|
||||
|
||||
/** Was der eigene Player tun soll, damit er zum Jam passt. */
|
||||
fun decide(want: Target?, local: Local, tolerance: Double = TOLERANCE_S): List<Step> {
|
||||
if (want == null) return if (local.videoId != null && !local.paused) listOf(Step.Pause) else emptyList()
|
||||
val nearEnd = want.dur != null && want.pos > want.dur - 3
|
||||
if (local.videoId != want.videoId) {
|
||||
// Am Titelende springt YouTube Music von selbst weiter - nicht den alten Titel neu laden.
|
||||
if (nearEnd) return if (local.paused) emptyList() else listOf(Step.Pause)
|
||||
val steps = mutableListOf<Step>(Step.Load(want.videoId, max(0.0, want.pos)))
|
||||
if (want.paused || want.pos < 0) steps.add(Step.Pause)
|
||||
return steps
|
||||
}
|
||||
val steps = mutableListOf<Step>()
|
||||
if (want.pos < 0) {
|
||||
if (!local.paused) steps.add(Step.Pause)
|
||||
if (local.pos > 0.5) steps.add(Step.Seek(0.0))
|
||||
return steps
|
||||
}
|
||||
if (abs(local.pos - want.pos) > tolerance && !(nearEnd && local.pos > want.pos)) steps.add(Step.Seek(want.pos))
|
||||
if (want.paused && !local.paused) steps.add(Step.Pause)
|
||||
if (!want.paused && local.paused) steps.add(Step.Play)
|
||||
return steps
|
||||
}
|
||||
|
||||
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). */
|
||||
const val PROBE = """
|
||||
(function () {
|
||||
var video = document.querySelector('video');
|
||||
var id = null;
|
||||
try { if (location.pathname === '/watch') { id = new URL(location.href).searchParams.get('v'); } } catch (e) { id = 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,
|
||||
ad: ad,
|
||||
error: error
|
||||
});
|
||||
})();
|
||||
"""
|
||||
|
||||
fun watchUrl(videoId: String): String = "https://music.youtube.com/watch?v=$videoId"
|
||||
}
|
||||
@@ -29,6 +29,8 @@ import androidx.core.view.WindowInsetsCompat
|
||||
import androidx.webkit.WebSettingsCompat
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import org.json.JSONObject
|
||||
import org.json.JSONTokener
|
||||
|
||||
/** Playtube fuer Android: YouTube Music in einer WebView, mit Hintergrundwiedergabe. */
|
||||
class MainActivity : AppCompatActivity() {
|
||||
@@ -43,6 +45,14 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
// Playtube Jam: eigenen Player alle 700 ms mit dem Jam abgleichen (JamHub).
|
||||
private val jamLoop = object : Runnable {
|
||||
override fun run() {
|
||||
syncJam()
|
||||
handler.postDelayed(this, JAM_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
private val notificationPermission =
|
||||
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* ohne Erlaubnis: nur keine Benachrichtigung */ }
|
||||
|
||||
@@ -53,6 +63,8 @@ class MainActivity : AppCompatActivity() {
|
||||
progress = findViewById(R.id.progress)
|
||||
keepContentBetweenSystemBars()
|
||||
findViewById<View>(R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) }
|
||||
findViewById<View>(R.id.jamButton).setOnClickListener { JamActivity.start(this) }
|
||||
JamHub.init(this)
|
||||
|
||||
configureWebView()
|
||||
onBackPressedDispatcher.addCallback(
|
||||
@@ -66,7 +78,10 @@ class MainActivity : AppCompatActivity() {
|
||||
)
|
||||
|
||||
PlaybackHub.commandHandler = { command ->
|
||||
runOnUiThread { webView.evaluateJavascript(MediaScripts.forCommand(command), null) }
|
||||
runOnUiThread {
|
||||
// Im Jam gehen Play/Pause/Weiter/Zurueck an den Jam statt an den Player.
|
||||
if (!JamHub.intercept(command)) webView.evaluateJavascript(MediaScripts.forCommand(command), null)
|
||||
}
|
||||
}
|
||||
requestNotificationPermission()
|
||||
DiscordPresence.init(this)
|
||||
@@ -74,6 +89,7 @@ class MainActivity : AppCompatActivity() {
|
||||
|
||||
webView.loadUrl(startUrl(intent))
|
||||
handler.post(probeLoop)
|
||||
handler.post(jamLoop)
|
||||
checkForUpdate()
|
||||
}
|
||||
|
||||
@@ -166,7 +182,23 @@ class MainActivity : AppCompatActivity() {
|
||||
|
||||
private fun probe() {
|
||||
webView.evaluateJavascript(MediaScripts.PROBE) { raw ->
|
||||
NowPlaying.parse(raw)?.let(PlaybackHub::publish)
|
||||
NowPlaying.parse(raw)?.let { info ->
|
||||
PlaybackHub.publish(info)
|
||||
// Fuer "Jam starten": der gerade laufende Song wird der erste im Jam.
|
||||
val videoId = JamSync.parseVideoId(webView.url)
|
||||
JamHub.pageVideo = if (videoId != null && info.hasTrack) JamHub.PageVideo(videoId, info.title, info.artist) else null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun syncJam() {
|
||||
if (JamHub.state == null) return
|
||||
webView.evaluateJavascript(JamSync.PROBE) { raw ->
|
||||
val text = runCatching { JSONTokener(raw).nextValue() as? String }.getOrNull() ?: return@evaluateJavascript
|
||||
val probe = runCatching { JSONObject(text) }.getOrNull() ?: return@evaluateJavascript
|
||||
val actions = JamHub.syncPlayer(probe)
|
||||
actions.loadUrl?.let { webView.loadUrl(it) }
|
||||
for (script in actions.scripts) webView.evaluateJavascript(script, null)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,6 +250,7 @@ class MainActivity : AppCompatActivity() {
|
||||
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 JAM_INTERVAL_MS = 700L
|
||||
private const val PREFS = "playtube"
|
||||
private const val KEY_DISMISSED_UPDATE = "dismissed_update"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user