Files
Playtube-Android/app/src/main/java/de/fojadrachi/playtube/JamActivity.kt
T
2026-11-12 21:59:41 +01:00

401 lines
17 KiB
Kotlin

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 shared = intent.getStringExtra(Intent.EXTRA_TEXT)
val playlistId = JamSync.playlistIdFromSharedText(shared)
if (playlistId != null && JamHub.active) {
JamHub.addPlaylist(playlistId)
Toast.makeText(this, R.string.jam_playlist_adding, Toast.LENGTH_SHORT).show()
return
}
val videoId = JamSync.videoIdFromSharedText(shared) ?: run {
if (playlistId != null) status.setText(R.string.jam_share_no_jam)
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)
val playlistId = if (videoId == null) JamSync.parsePlaylistId(text) else null
if (playlistId != null) {
JamHub.addPlaylist(playlistId)
addInput.setText("")
status.setText(R.string.jam_playlist_adding)
return
}
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))
}
}
}