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:
@@ -19,12 +19,14 @@ android {
|
||||
applicationId = "de.fojadrachi.playtube"
|
||||
minSdk = 26
|
||||
targetSdk = 36
|
||||
versionCode = 6
|
||||
versionName = "1.3.0"
|
||||
versionCode = 7
|
||||
versionName = "1.4.0"
|
||||
|
||||
// Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play).
|
||||
buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"")
|
||||
buildConfigField("String", "REPO_SLUG", "\"Fojadrachi/Playtube-Android\"")
|
||||
// Playtube Jam: eigener Dienst (Ordner playtube-jam, Cloudflare Worker).
|
||||
buildConfigField("String", "JAM_SERVER", "\"https://jam.fojadrachi.de\"")
|
||||
// Discord-Anwendung von Playtube (gleiche wie in der Desktop-Version; die ID ist oeffentlich).
|
||||
buildConfigField("long", "DISCORD_APPLICATION_ID", "1548023494976086127L")
|
||||
|
||||
@@ -79,6 +81,8 @@ dependencies {
|
||||
implementation("androidx.webkit:webkit:1.12.1")
|
||||
implementation("androidx.media:media:1.7.0")
|
||||
implementation("androidx.palette:palette:1.0.0")
|
||||
// Playtube Jam: WebSocket zum Jam-Server.
|
||||
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||
// Discord Social SDK (Rich Presence): nicht im Repo, siehe README "Discord-SDK".
|
||||
implementation(files("../libs/discord_partner_sdk.aar"))
|
||||
|
||||
|
||||
@@ -60,6 +60,34 @@
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
|
||||
android:windowSoftInputMode="adjustResize" />
|
||||
|
||||
<!-- Playtube Jam: Einladungslinks (App-Link jam.fojadrachi.de, playtube://jam/<CODE>) und
|
||||
"Teilen" von YouTube-Links aus anderen Apps (fuegt sie zum laufenden Jam hinzu). -->
|
||||
<activity
|
||||
android:name=".JamActivity"
|
||||
android:exported="true"
|
||||
android:label="@string/jam_title"
|
||||
android:launchMode="singleTop"
|
||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<intent-filter android:autoVerify="true">
|
||||
<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="jam.fojadrachi.de" />
|
||||
</intent-filter>
|
||||
<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="playtube" android:host="jam" />
|
||||
</intent-filter>
|
||||
<intent-filter android:label="@string/jam_title">
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="text/plain" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".PcRemoteService"
|
||||
android:exported="false"
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<gradient android:angle="0" android:startColor="@color/brand_from" android:endColor="@color/brand_to" />
|
||||
<corners android:radius="10dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<solid android:color="#17171D" />
|
||||
<stroke android:width="1dp" android:color="#2A2A34" />
|
||||
<corners android:radius="14dp" />
|
||||
</shape>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<solid android:color="#1F1F27" />
|
||||
<stroke android:width="1dp" android:color="#2A2A34" />
|
||||
<corners android:radius="10dp" />
|
||||
</shape>
|
||||
@@ -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="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z" />
|
||||
</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="#FFAAAAAA"
|
||||
android:pathData="M19,6.41L17.59,5 12,10.59 6.41,5 5,6.41 10.59,12 5,17.59 6.41,19 12,13.41 17.59,19 19,17.59 13.41,12z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Playtube Jam: zwei Personen mit Note (Material "group") -->
|
||||
<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="M16,11c1.66,0 2.99,-1.34 2.99,-3S17.66,5 16,5c-1.66,0 -3,1.34 -3,3s1.34,3 3,3zM8,11c1.66,0 2.99,-1.34 2.99,-3S9.66,5 8,5C6.34,5 5,6.34 5,8s1.34,3 3,3zM8,13c-2.33,0 -7,1.17 -7,3.5V19h14v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5zM16,13c-0.29,0 -0.62,0.02 -0.97,0.05 1.16,0.84 1.97,1.97 1.97,3.45V19h6v-2.5c0,-2.33 -4.67,-3.5 -7,-3.5z" />
|
||||
</vector>
|
||||
@@ -0,0 +1,493 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Playtube Jam (JamActivity): dunkel, Lila/Pink wie "PC steuern". -->
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/jamRoot"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
android:background="@color/remote_background"
|
||||
android:orientation="vertical">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="56dp"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="8dp"
|
||||
android:paddingEnd="16dp">
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/jamBack"
|
||||
android:layout_width="48dp"
|
||||
android:layout_height="48dp"
|
||||
android:background="?attr/selectableItemBackgroundBorderless"
|
||||
android:contentDescription="@string/pc_back_to_player"
|
||||
android:src="@drawable/ic_keyboard_arrow_down" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="4dp"
|
||||
android:layout_weight="1"
|
||||
android:text="@string/jam_title"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="24sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/jamLeave"
|
||||
style="?android:attr/borderlessButtonStyle"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/jam_leave"
|
||||
android:textColor="@color/text_muted"
|
||||
android:visibility="gone" />
|
||||
</LinearLayout>
|
||||
|
||||
<ScrollView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="0dp"
|
||||
android:layout_weight="1"
|
||||
android:fillViewport="true">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:paddingBottom="24dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamStatus"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginBottom="8dp"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<!-- Noch in keinem Jam -->
|
||||
<LinearLayout
|
||||
android:id="@+id/jamSetup"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/jam_intro"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="14sp" />
|
||||
|
||||
<EditText
|
||||
android:id="@+id/jamName"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginTop="16dp"
|
||||
android:background="@drawable/bg_input"
|
||||
android:hint="@string/jam_name_hint"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="textPersonName|textCapWords"
|
||||
android:maxLength="32"
|
||||
android:paddingStart="12dp"
|
||||
android:paddingEnd="12dp"
|
||||
android:textColor="@color/text"
|
||||
android:textColorHint="@color/text_muted" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/jamStart"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginTop="12dp"
|
||||
android:background="@drawable/bg_brand_button"
|
||||
android:text="@string/jam_start"
|
||||
android:textAllCaps="false"
|
||||
android:textColor="@color/text"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:text="@string/jam_start_hint"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="12sp" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="16dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<EditText
|
||||
android:id="@+id/jamCode"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="48dp"
|
||||
android:layout_weight="1"
|
||||
android:background="@drawable/bg_input"
|
||||
android:hint="@string/jam_code_hint"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="textCapCharacters|textNoSuggestions"
|
||||
android:maxLength="60"
|
||||
android:paddingStart="12dp"
|
||||
android:paddingEnd="12dp"
|
||||
android:textColor="@color/text"
|
||||
android:textColorHint="@color/text_muted" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/jamJoin"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginStart="8dp"
|
||||
android:background="@drawable/bg_brand_button"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:text="@string/jam_join"
|
||||
android:textAllCaps="false"
|
||||
android:textColor="@color/text"
|
||||
android:textStyle="bold" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Im Jam -->
|
||||
<LinearLayout
|
||||
android:id="@+id/jamPanel"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical"
|
||||
android:visibility="gone">
|
||||
|
||||
<!-- Läuft gerade -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/jamCover"
|
||||
android:layout_width="96dp"
|
||||
android:layout_height="54dp"
|
||||
android:background="@drawable/bg_tile"
|
||||
android:contentDescription="@string/pc_cover"
|
||||
android:scaleType="centerCrop" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="12dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamNowTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="2"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="18sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamNowArtist"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="14sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamCantPlay"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:text="@string/jam_cant_play_here"
|
||||
android:textColor="#FCA5A5"
|
||||
android:textSize="13sp"
|
||||
android:visibility="gone" />
|
||||
|
||||
<SeekBar
|
||||
android:id="@+id/jamSeek"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:max="1000"
|
||||
android:progressTint="@color/brand_to"
|
||||
android:thumbTint="@color/text" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="16dp">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamTime"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_weight="1"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="12sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamDuration"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:gravity="center"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/jamPrevious"
|
||||
android:layout_width="56dp"
|
||||
android:layout_height="56dp"
|
||||
android:background="?attr/selectableItemBackgroundBorderless"
|
||||
android:contentDescription="@string/jam_previous"
|
||||
android:src="@drawable/ic_skip_previous" />
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/jamPlayPause"
|
||||
android:layout_width="64dp"
|
||||
android:layout_height="64dp"
|
||||
android:layout_marginStart="24dp"
|
||||
android:layout_marginEnd="24dp"
|
||||
android:background="@drawable/bg_play_button"
|
||||
android:contentDescription="@string/jam_play_pause"
|
||||
android:padding="16dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:src="@drawable/ic_play" />
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/jamNext"
|
||||
android:layout_width="56dp"
|
||||
android:layout_height="56dp"
|
||||
android:background="?attr/selectableItemBackgroundBorderless"
|
||||
android:contentDescription="@string/jam_next"
|
||||
android:src="@drawable/ic_skip_next" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Hinzufügen und Warteschlange -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<EditText
|
||||
android:id="@+id/jamAddInput"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="48dp"
|
||||
android:layout_weight="1"
|
||||
android:background="@drawable/bg_input"
|
||||
android:hint="@string/jam_add_hint"
|
||||
android:imeOptions="actionGo"
|
||||
android:importantForAutofill="no"
|
||||
android:inputType="text"
|
||||
android:maxLength="200"
|
||||
android:paddingStart="12dp"
|
||||
android:paddingEnd="12dp"
|
||||
android:textColor="@color/text"
|
||||
android:textColorHint="@color/text_muted" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/jamAddButton"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="48dp"
|
||||
android:layout_marginStart="8dp"
|
||||
android:background="@drawable/bg_brand_button"
|
||||
android:paddingStart="16dp"
|
||||
android:paddingEnd="16dp"
|
||||
android:text="@string/jam_add"
|
||||
android:textAllCaps="false"
|
||||
android:textColor="@color/text"
|
||||
android:textStyle="bold" />
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="6dp"
|
||||
android:text="@string/jam_add_hint_share"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="12sp" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/jamResults"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:orientation="vertical" />
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/jam_queue"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/jamQueue"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Einladen -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/jam_invite"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamInviteCode"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:letterSpacing="0.1"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="28sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamInviteLink"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textIsSelectable="true"
|
||||
android:textSize="13sp" />
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="8dp"
|
||||
android:orientation="horizontal">
|
||||
|
||||
<Button
|
||||
android:id="@+id/jamShare"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="44dp"
|
||||
android:layout_weight="1"
|
||||
android:background="@drawable/bg_brand_button"
|
||||
android:text="@string/jam_share"
|
||||
android:textAllCaps="false"
|
||||
android:textColor="@color/text" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/jamCopy"
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="44dp"
|
||||
android:layout_marginStart="8dp"
|
||||
android:layout_weight="1"
|
||||
android:background="@drawable/bg_input"
|
||||
android:text="@string/jam_copy"
|
||||
android:textAllCaps="false"
|
||||
android:textColor="@color/text" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Nur für den Host -->
|
||||
<LinearLayout
|
||||
android:id="@+id/jamHostBox"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<androidx.appcompat.widget.SwitchCompat
|
||||
android:id="@+id/jamAllControl"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/jam_all_control"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<Button
|
||||
android:id="@+id/jamEnd"
|
||||
style="?android:attr/borderlessButtonStyle"
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="4dp"
|
||||
android:text="@string/jam_end"
|
||||
android:textAllCaps="false"
|
||||
android:textColor="#F87171" />
|
||||
</LinearLayout>
|
||||
|
||||
<!-- Teilnehmer -->
|
||||
<LinearLayout
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:background="@drawable/bg_card"
|
||||
android:orientation="vertical"
|
||||
android:padding="16dp">
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="@string/jam_members"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="16sp"
|
||||
android:textStyle="bold" />
|
||||
|
||||
<LinearLayout
|
||||
android:id="@+id/jamMembers"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:orientation="vertical" />
|
||||
</LinearLayout>
|
||||
|
||||
<TextView
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginTop="12dp"
|
||||
android:text="@string/jam_play_hint"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
</ScrollView>
|
||||
</LinearLayout>
|
||||
@@ -34,4 +34,19 @@
|
||||
android:padding="10dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:src="@drawable/ic_pc_remote" />
|
||||
|
||||
<!-- Playtube Jam (JamActivity): direkt unter "PC steuern". -->
|
||||
<ImageButton
|
||||
android:id="@+id/jamButton"
|
||||
android:layout_width="44dp"
|
||||
android:layout_height="44dp"
|
||||
android:layout_gravity="end|center_vertical"
|
||||
android:layout_marginTop="56dp"
|
||||
android:layout_marginEnd="6dp"
|
||||
android:alpha="0.85"
|
||||
android:background="@drawable/bg_play_button"
|
||||
android:contentDescription="@string/jam_open"
|
||||
android:padding="10dp"
|
||||
android:scaleType="fitCenter"
|
||||
android:src="@drawable/ic_jam" />
|
||||
</FrameLayout>
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Zeile im Jam: Titel (Vorschaubild) oder Teilnehmer (Anfangsbuchstabe), dazu bis zu zwei Knöpfe. -->
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:gravity="center_vertical"
|
||||
android:minHeight="56dp"
|
||||
android:orientation="horizontal"
|
||||
android:paddingTop="6dp"
|
||||
android:paddingBottom="6dp">
|
||||
|
||||
<FrameLayout
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content">
|
||||
|
||||
<ImageView
|
||||
android:id="@+id/jamRowImage"
|
||||
android:layout_width="64dp"
|
||||
android:layout_height="36dp"
|
||||
android:background="@drawable/bg_tile"
|
||||
android:contentDescription="@null"
|
||||
android:scaleType="centerCrop" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamRowAvatar"
|
||||
android:layout_width="36dp"
|
||||
android:layout_height="36dp"
|
||||
android:background="@drawable/bg_play_button"
|
||||
android:gravity="center"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="15sp"
|
||||
android:textStyle="bold"
|
||||
android:visibility="gone" />
|
||||
</FrameLayout>
|
||||
|
||||
<LinearLayout
|
||||
android:layout_width="0dp"
|
||||
android:layout_height="wrap_content"
|
||||
android:layout_marginStart="12dp"
|
||||
android:layout_weight="1"
|
||||
android:orientation="vertical">
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamRowTitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/text"
|
||||
android:textSize="15sp" />
|
||||
|
||||
<TextView
|
||||
android:id="@+id/jamRowSubtitle"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="wrap_content"
|
||||
android:ellipsize="end"
|
||||
android:maxLines="1"
|
||||
android:textColor="@color/text_muted"
|
||||
android:textSize="12sp" />
|
||||
</LinearLayout>
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/jamRowAction1"
|
||||
android:layout_width="40dp"
|
||||
android:layout_height="40dp"
|
||||
android:background="?attr/selectableItemBackgroundBorderless"
|
||||
android:visibility="gone" />
|
||||
|
||||
<ImageButton
|
||||
android:id="@+id/jamRowAction2"
|
||||
android:layout_width="40dp"
|
||||
android:layout_height="40dp"
|
||||
android:background="?attr/selectableItemBackgroundBorderless"
|
||||
android:visibility="gone" />
|
||||
</LinearLayout>
|
||||
@@ -58,6 +58,75 @@
|
||||
<string name="pc_list_error">Das hat nicht geklappt: %1$s</string>
|
||||
<string name="pc_this_pc">Verbunden</string>
|
||||
|
||||
<!-- Playtube Jam (JamActivity, JamHub) -->
|
||||
<string name="jam_title">Jam</string>
|
||||
<string name="jam_open">Playtube Jam: gemeinsam hören</string>
|
||||
<string name="jam_intro">Hört gemeinsam wie bei Spotify Jam: jeder auf seinem eigenen Gerät, synchron, und alle wünschen sich Songs. Freunde ohne Playtube machen über den Link im Browser mit.</string>
|
||||
<string name="jam_name_hint">Dein Name</string>
|
||||
<string name="jam_start">Jam starten</string>
|
||||
<string name="jam_start_hint">Läuft gerade ein Song, wird er der erste im Jam.</string>
|
||||
<string name="jam_code_hint">Code oder Einladungslink</string>
|
||||
<string name="jam_join">Beitreten</string>
|
||||
<string name="jam_invite">Freunde einladen</string>
|
||||
<string name="jam_share">Link teilen</string>
|
||||
<string name="jam_copy">Kopieren</string>
|
||||
<string name="jam_copied">Link kopiert.</string>
|
||||
<string name="jam_share_text">Hör mit mir in Playtube Jam: %1$s</string>
|
||||
<string name="jam_all_control">Alle dürfen steuern</string>
|
||||
<string name="jam_end">Jam beenden</string>
|
||||
<string name="jam_end_confirm">Jam für alle beenden?</string>
|
||||
<string name="jam_leave">Verlassen</string>
|
||||
<string name="jam_members">Dabei</string>
|
||||
<string name="jam_queue">Als Nächstes</string>
|
||||
<string name="jam_queue_empty">Die Warteschlange ist leer.</string>
|
||||
<string name="jam_add">Hinzufügen</string>
|
||||
<string name="jam_search">Suchen</string>
|
||||
<string name="jam_add_hint">YouTube-Link oder Video-ID</string>
|
||||
<string name="jam_search_hint">Song suchen oder Link einfügen</string>
|
||||
<string name="jam_add_hint_share">Tipp: In der YouTube-App „Teilen“ › Playtube wählen.</string>
|
||||
<string name="jam_nothing">Noch läuft nichts – füge den ersten Song hinzu.</string>
|
||||
<string name="jam_cant_play_here">Dieser Titel lässt sich hier nicht abspielen (z. B. Region) – er läuft bei den anderen weiter.</string>
|
||||
<string name="jam_by">von %1$s</string>
|
||||
<string name="jam_host">Host</string>
|
||||
<string name="jam_you">%1$s (du)</string>
|
||||
<string name="jam_offline">offline</string>
|
||||
<string name="jam_cant_play">kann diesen Titel nicht abspielen</string>
|
||||
<string name="jam_client_pc">Playtube PC</string>
|
||||
<string name="jam_client_android">Android</string>
|
||||
<string name="jam_client_web">Browser</string>
|
||||
<string name="jam_kick">Entfernen</string>
|
||||
<string name="jam_kick_confirm">%1$s aus dem Jam entfernen?</string>
|
||||
<string name="jam_play_now">Jetzt spielen</string>
|
||||
<string name="jam_remove">Entfernen</string>
|
||||
<string name="jam_added">Hinzugefügt: %1$s</string>
|
||||
<string name="jam_added_shared">Zum Jam hinzugefügt.</string>
|
||||
<string name="jam_share_no_jam">Du bist gerade in keinem Jam. Starte einen oder tritt einem bei.</string>
|
||||
<string name="jam_play_hint">Die Musik läuft im Player von Playtube. Mit Steuerrecht wirken Play/Pause und Weiter dort und in der Benachrichtigung für alle.</string>
|
||||
<string name="jam_status_creating">Jam wird gestartet …</string>
|
||||
<string name="jam_status_joining">Verbinde …</string>
|
||||
<string name="jam_status_connected">Verbunden.</string>
|
||||
<string name="jam_status_reconnecting">Verbindung unterbrochen – verbinde neu …</string>
|
||||
<string name="jam_status_bad_code">Das ist kein gültiger Code (6 Zeichen).</string>
|
||||
<string name="jam_status_not_found">Diesen Jam gibt es nicht (mehr).</string>
|
||||
<string name="jam_status_failed">Keine Verbindung zum Jam-Server.</string>
|
||||
<string name="jam_status_need_name">Bitte gib zuerst deinen Namen ein.</string>
|
||||
<string name="jam_status_in_other">Du bist schon in einem Jam – verlasse ihn zuerst.</string>
|
||||
<string name="jam_ended_host">Der Host hat den Jam beendet.</string>
|
||||
<string name="jam_ended_over">Der Jam ist zu Ende.</string>
|
||||
<string name="jam_ended_expired">Der Jam ist abgelaufen.</string>
|
||||
<string name="jam_ended_kicked">Du wurdest aus dem Jam entfernt.</string>
|
||||
<string name="jam_ended_left">Du hast den Jam verlassen.</string>
|
||||
<string name="jam_ended_full">Der Jam ist voll.</string>
|
||||
<string name="jam_error_not_allowed">Das darf nur der Host.</string>
|
||||
<string name="jam_error_queue_full">Die Warteschlange ist voll.</string>
|
||||
<string name="jam_error_bad_video">Das ist kein YouTube-Link.</string>
|
||||
<string name="jam_error_rate_limited">Langsam – zu viele Aktionen auf einmal.</string>
|
||||
<string name="jam_error_search">Die Suche geht gerade nicht.</string>
|
||||
<string name="jam_error_other">Fehler: %1$s</string>
|
||||
<string name="jam_previous">Zurück</string>
|
||||
<string name="jam_next">Weiter</string>
|
||||
<string name="jam_play_pause">Wiedergabe umschalten</string>
|
||||
|
||||
<color name="remote_background">#121212</color>
|
||||
<color name="background">#0F0F0F</color>
|
||||
<color name="surface">#1F1F1F</color>
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package de.fojadrachi.playtube
|
||||
|
||||
import de.fojadrachi.playtube.JamSync.Local
|
||||
import de.fojadrachi.playtube.JamSync.Step
|
||||
import de.fojadrachi.playtube.JamSync.Target
|
||||
import org.json.JSONObject
|
||||
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 JamSyncTest {
|
||||
@Test
|
||||
fun `liest Codes und Einladungslinks`() {
|
||||
assertEquals("ABC234", JamSync.normalizeCode("abc-234"))
|
||||
assertEquals("ABC234", JamSync.normalizeCode(" ABC 234 "))
|
||||
assertEquals("ABC234", JamSync.normalizeCode("https://jam.fojadrachi.de/abc234"))
|
||||
assertEquals("ABC234", JamSync.normalizeCode("https://jam.fojadrachi.de/ABC234/?x=1"))
|
||||
assertEquals("ABC234", JamSync.normalizeCode("playtube://jam/ABC234"))
|
||||
assertNull(JamSync.normalizeCode("ABC10O"))
|
||||
assertNull(JamSync.normalizeCode("ABC23"))
|
||||
assertNull(JamSync.normalizeCode(null))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `liest Video-IDs aus Links und geteiltem Text`() {
|
||||
val id = "dQw4w9WgXcQ"
|
||||
for (input in listOf(
|
||||
id,
|
||||
"https://www.youtube.com/watch?v=$id&list=RD",
|
||||
"https://music.youtube.com/watch?v=$id",
|
||||
"https://youtu.be/$id?si=abc",
|
||||
"youtube.com/shorts/$id",
|
||||
"https://m.youtube.com/watch?feature=share&v=$id",
|
||||
)) {
|
||||
assertEquals(input, id, JamSync.parseVideoId(input))
|
||||
}
|
||||
assertNull(JamSync.parseVideoId("https://evil.example/watch?v=$id"))
|
||||
assertNull(JamSync.parseVideoId("kurz"))
|
||||
assertEquals(id, JamSync.videoIdFromSharedText("Hör dir das an: https://youtu.be/$id?si=x"))
|
||||
assertNull(JamSync.videoIdFromSharedText("kein Link hier"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `liest den Zustand des Servers`() {
|
||||
val state = JamSync.parseState(
|
||||
JSONObject(
|
||||
"""{"t":"state","code":"ABC234","you":"m2","hostId":"m1","allControl":false,"canControl":false,
|
||||
"features":{"search":true},
|
||||
"members":[{"id":"m1","name":"Chris","client":"pc","online":true,"host":true,"cantPlay":false}],
|
||||
"current":{"id":"i1","videoId":"dQw4w9WgXcQ","title":"T","artist":"A","thumb":"x","dur":212,"by":"m1","byName":"Chris"},
|
||||
"queue":[{"id":"i2","videoId":"aaaaaaaaaaa","title":"U","dur":null}],"history":[],
|
||||
"playback":{"paused":false,"position":10,"ref":1000},"serverNow":6000}""",
|
||||
),
|
||||
)
|
||||
assertFalse(state.isHost)
|
||||
assertTrue(state.search)
|
||||
assertEquals(212.0, state.current!!.dur!!, 0.0)
|
||||
assertNull(state.queue[0].dur)
|
||||
assertEquals("Chris", state.members[0].name)
|
||||
val want = JamSync.target(state, 6000.0)!!
|
||||
assertEquals(15.0, want.pos, 1e-9)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Zeitabgleich nimmt die schnellste Messung`() {
|
||||
val clock = JamSync.Clock()
|
||||
clock.hint(9000.0, 1000.0)
|
||||
assertEquals(8000.0, clock.offset, 0.0)
|
||||
clock.add(1000.0, 6050.0, 1100.0)
|
||||
clock.add(2000.0, 7900.0, 2800.0)
|
||||
clock.add(3000.0, 8010.0, 3020.0)
|
||||
assertEquals(5000.0, clock.offset, 0.0)
|
||||
clock.add(5000.0, 0.0, 4000.0)
|
||||
assertEquals(5000.0, clock.offset, 0.0)
|
||||
}
|
||||
|
||||
private fun want(pos: Double, paused: Boolean = false) = Target("aaaaaaaaaaa", "i", pos, paused, 200.0)
|
||||
private fun local(id: String?, pos: Double, paused: Boolean) = Local(id, pos, paused)
|
||||
|
||||
@Test
|
||||
fun `Nachzuegler laden an der richtigen Stelle`() {
|
||||
assertEquals(listOf(Step.Load("aaaaaaaaaaa", 42.5)), JamSync.decide(want(42.5), local("bbbbbbbbbbb", 3.0, false)))
|
||||
assertEquals(listOf(Step.Load("aaaaaaaaaaa", 0.0), Step.Pause), JamSync.decide(want(-1.0), local(null, 0.0, true)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `warten am Start, Pause und Play uebernehmen`() {
|
||||
val id = "aaaaaaaaaaa"
|
||||
assertEquals(listOf(Step.Pause, Step.Seek(0.0)), JamSync.decide(want(-1.0), local(id, 2.0, false)))
|
||||
assertEquals(listOf(Step.Pause), JamSync.decide(want(30.0, paused = true), local(id, 30.2, false)))
|
||||
assertEquals(listOf(Step.Play), JamSync.decide(want(30.0), local(id, 30.2, true)))
|
||||
assertEquals(listOf(Step.Pause), JamSync.decide(null, local(id, 3.0, false)))
|
||||
assertTrue(JamSync.decide(null, local(null, 0.0, true)).isEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `spult erst ab der Toleranz`() {
|
||||
val id = "aaaaaaaaaaa"
|
||||
assertTrue(JamSync.decide(want(30.0), local(id, 31.2, false)).isEmpty())
|
||||
assertEquals(listOf(Step.Seek(30.0)), JamSync.decide(want(30.0), local(id, 34.0, false)))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `laedt am Titelende nicht den alten Titel neu`() {
|
||||
assertEquals(listOf(Step.Pause), JamSync.decide(want(198.5), local("zzzzzzzzzzz", 1.0, false)))
|
||||
assertTrue(JamSync.decide(want(198.0), local("aaaaaaaaaaa", 199.9, false)).isEmpty())
|
||||
assertTrue(JamSync.reachedEnd(local("a", 199.5, false), 200.0, false))
|
||||
assertFalse(JamSync.reachedEnd(local("a", 150.0, false), 200.0, false))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `formatiert Zeit und Code`() {
|
||||
assertEquals("0:00", JamSync.formatTime(0.0))
|
||||
assertEquals("1:05", JamSync.formatTime(65.9))
|
||||
assertEquals("1:02:05", JamSync.formatTime(3725.0))
|
||||
assertEquals("ABC 234", JamSync.prettyCode("ABC234"))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user