diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index ab3dc21..1054140 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -88,6 +88,15 @@ + + + (R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) } findViewById(R.id.jamButton).setOnClickListener { JamActivity.start(this) } + findViewById(R.id.socialButton).setOnClickListener { SocialActivity.start(this) } findViewById(R.id.settingsButton).setOnClickListener { showMenu() } history = PlayHistory.fromJson(runCatching { historyFile().readText() }.getOrNull()) JamHub.init(this) + SocialHub.init(this) configureWebView() onBackPressedDispatcher.addCallback( @@ -202,6 +204,7 @@ class MainActivity : AppCompatActivity() { // 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 + SocialHub.observe(info, videoId) if (history.observe(videoId, info, info.playing, SystemClock.elapsedRealtime(), System.currentTimeMillis())) saveHistory() sleepTick(if (info.playing && info.hasTrack) videoId else null) } diff --git a/app/src/main/java/de/fojadrachi/playtube/SocialActivity.kt b/app/src/main/java/de/fojadrachi/playtube/SocialActivity.kt new file mode 100644 index 0000000..670d657 --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/SocialActivity.kt @@ -0,0 +1,455 @@ +package de.fojadrachi.playtube + +import android.content.Context +import android.content.Intent +import android.graphics.Typeface +import android.net.Uri +import android.os.Bundle +import android.os.Handler +import android.os.Looper +import android.text.InputType +import android.util.TypedValue +import android.view.Gravity +import android.view.View +import android.view.ViewGroup +import android.view.inputmethod.EditorInfo +import android.widget.Button +import android.widget.EditText +import android.widget.FrameLayout +import android.widget.ImageButton +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.ScrollView +import android.widget.TextView +import androidx.appcompat.app.AlertDialog +import androidx.appcompat.app.AppCompatActivity +import androidx.appcompat.widget.SwitchCompat +import androidx.core.content.ContextCompat +import androidx.core.view.ViewCompat +import androidx.core.view.WindowInsetsCompat +import org.json.JSONObject + +/** + * „Sozial“: Playtube-Konto (anmelden, registrieren, Passwort vergessen, abmelden, loeschen) und + * Freunde (suchen, Anfragen, was sie hoeren, in den eigenen Sync einladen, Einladungen annehmen). + * Verbindung und Zustand haelt [SocialHub]. Die Oberflaeche wird im Code gebaut. + */ +class SocialActivity : AppCompatActivity() { + companion object { + const val EXTRA_JOIN = "join_invite" + fun start(context: Context) = context.startActivity(Intent(context, SocialActivity::class.java)) + } + + private val handler = Handler(Looper.getMainLooper()) + private lateinit var content: LinearLayout + private var mode = 0 // 0 = anmelden, 1 = registrieren, 2 = Passwort vergessen + private var busy = false + private var results: List = emptyList() + private var searchText = "" + private val listener: () -> Unit = { render() } + + private fun dp(value: Int): Int = (value * resources.displayMetrics.density).toInt() + private fun color(id: Int) = ContextCompat.getColor(this, id) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + SocialHub.init(this) + JamHub.init(this) + val root = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setBackgroundColor(color(R.color.background)) + } + val bar = LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + setPadding(dp(8), dp(8), dp(16), dp(8)) + } + bar.addView(ImageButton(this).apply { + setImageResource(R.drawable.ic_keyboard_arrow_down) + background = null + contentDescription = getString(R.string.pc_close) + setOnClickListener { finish() } + }, LinearLayout.LayoutParams(dp(44), dp(44))) + bar.addView(text(getString(R.string.social_title), 20f, bold = true)) + root.addView(bar) + content = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setPadding(dp(16), 0, dp(16), dp(24)) + } + root.addView(ScrollView(this).apply { addView(content) }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)) + setContentView(root) + ViewCompat.setOnApplyWindowInsetsListener(root) { 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 + } + handleIntent(intent) + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handleIntent(intent) + } + + private fun handleIntent(intent: Intent?) { + intent?.getStringExtra(EXTRA_JOIN)?.let { id -> + intent.removeExtra(EXTRA_JOIN) + SocialHub.activeInvites().firstOrNull { it.id == id }?.let { join(it) } + } + } + + override fun onStart() { + super.onStart() + SocialHub.listeners.add(listener) + JamHub.listeners.add(listener) + render() + } + + override fun onStop() { + SocialHub.listeners.remove(listener) + JamHub.listeners.remove(listener) + super.onStop() + } + + // ------------------------------------------------------------------ Bausteine + + private fun text(value: String, sizeSp: Float = 14f, bold: Boolean = false, muted: Boolean = false): TextView = + TextView(this).apply { + text = value + setTextSize(TypedValue.COMPLEX_UNIT_SP, sizeSp) + setTextColor(color(if (muted) R.color.text_muted else R.color.text)) + if (bold) setTypeface(typeface, Typeface.BOLD) + } + + private fun card(): LinearLayout = LinearLayout(this).apply { + orientation = LinearLayout.VERTICAL + setBackgroundResource(R.drawable.bg_card) + setPadding(dp(16), dp(14), dp(16), dp(14)) + content.addView(this, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + topMargin = dp(12) + }) + } + + private fun input(hint: Int, password: Boolean = false, email: Boolean = false): EditText = EditText(this).apply { + setHint(hint) + setTextColor(color(R.color.text)) + setHintTextColor(color(R.color.text_muted)) + setBackgroundResource(R.drawable.bg_input) + setPadding(dp(12), dp(10), dp(12), dp(10)) + isSingleLine = true + inputType = when { + password -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD + email -> InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS + else -> InputType.TYPE_CLASS_TEXT + } + } + + private fun button(label: String, primary: Boolean = false, onClick: () -> Unit): Button = Button(this).apply { + text = label + isAllCaps = false + setTextColor(color(R.color.text)) + setBackgroundResource(if (primary) R.drawable.bg_brand_button else R.drawable.bg_pill) + setPadding(dp(14), 0, dp(14), 0) + minHeight = dp(40) + minimumHeight = dp(40) + setOnClickListener { onClick() } + } + + private fun LinearLayout.add(view: View, top: Int = 8) { + addView(view, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { topMargin = dp(top) }) + } + + private fun row(vararg views: View): LinearLayout = LinearLayout(this).apply { + orientation = LinearLayout.HORIZONTAL + gravity = Gravity.CENTER_VERTICAL + views.forEachIndexed { i, v -> + addView(v, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { + if (i > 0) marginStart = dp(8) + }) + } + } + + private fun link(label: String, onClick: () -> Unit) = text(label, 13f).apply { + setTextColor(color(R.color.brand_to)) + setPadding(0, dp(6), 0, dp(6)) + setOnClickListener { onClick() } + } + + // ------------------------------------------------------------------ Anzeige + + private fun render() { + // Eingaben behalten, wenn neu gezeichnet wird (z. B. Freundesliste aktualisiert) + content.removeAllViews() + content.add(text(getString(R.string.social_intro), 13f, muted = true), 0) + if (!SocialHub.signedIn) renderLogin() else renderSignedIn() + } + + private fun renderLogin() { + val card = card() + card.add(text(getString(listOf(R.string.social_login_title, R.string.social_register_title, R.string.social_reset_title)[mode]), 17f, bold = true), 0) + val login = input(R.string.social_login_field) + val name = input(R.string.social_name_field) + val email = input(R.string.social_email_field, email = true) + val password = input(R.string.social_password_field, password = true) + val password2 = input(R.string.social_password2_field, password = true) + when (mode) { + 0 -> { card.add(login); card.add(password) } + 1 -> { card.add(name); card.add(email); card.add(password); card.add(password2) } + else -> card.add(email) + } + val action = when (mode) { + 0 -> button(getString(R.string.social_login), primary = true) { + send("POST", "/api/account/login", JSONObject().put("login", login.text.toString().trim()).put("password", password.text.toString()).put("client", "android")) + } + 1 -> button(getString(R.string.social_register), primary = true) { + if (password.text.toString() != password2.text.toString()) { + SocialHub.message = getString(R.string.social_mismatch) + render() + } else { + send("POST", "/api/account/register", JSONObject().put("name", name.text.toString().trim()) + .put("email", email.text.toString().trim()).put("password", password.text.toString()).put("client", "android")) + } + } + else -> button(getString(R.string.social_send_reset), primary = true) { + send("POST", "/api/account/reset-request", JSONObject().put("email", email.text.toString().trim())) + } + } + action.isEnabled = !busy + card.add(action, 12) + password.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_DONE && mode == 0) { action.performClick(); true } else false } + if (SocialHub.message.isNotEmpty()) card.add(text(SocialHub.message, 13f).apply { setTextColor(0xFFFCA5A5.toInt()) }) + if (mode != 0) card.add(link(getString(R.string.social_to_login)) { mode = 0; SocialHub.message = ""; render() }) + if (mode != 1) card.add(link(getString(R.string.social_to_register)) { mode = 1; SocialHub.message = ""; render() }, 0) + if (mode == 0) card.add(link(getString(R.string.social_forgot)) { mode = 2; SocialHub.message = ""; render() }, 0) + card.add(text(getString(R.string.social_optional_hint), 12f, muted = true)) + card.add(link(getString(R.string.social_privacy)) { openPrivacy() }) + } + + private fun send(method: String, path: String, body: JSONObject) { + busy = true + SocialHub.message = getString(R.string.social_working) + render() + SocialHub.call(method, path, body, false) { json, error -> + busy = false + when { + error != null -> SocialHub.message = SocialHub.errorText(error) + path.endsWith("reset-request") -> { mode = 0; SocialHub.message = getString(R.string.social_reset_sent) } + json == null || !SocialHub.signedIn(json) -> SocialHub.message = SocialHub.errorText("failed") + } + render() + } + } + + private fun renderSignedIn() { + // Einladungen + val invites = SocialHub.activeInvites() + if (invites.isNotEmpty()) { + val card = card() + card.add(text(getString(R.string.social_invites), 17f, bold = true), 0) + for (invite in invites) { + val info = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } + info.addView(text(getString(R.string.social_invite_from, invite.fromName), bold = true)) + invite.songTitle?.let { info.addView(text(getString(R.string.social_invite_playing, it), 12f, muted = true)) } + val line = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL } + line.addView(info, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + line.addView(button(getString(R.string.social_join), primary = true) { join(invite) }) + line.addView(ImageButton(this).apply { + setImageResource(R.drawable.ic_close) + background = null + contentDescription = getString(R.string.social_dismiss) + setOnClickListener { SocialHub.dismiss(invite.id) } + }, LinearLayout.LayoutParams(dp(40), dp(40))) + card.add(line) + } + } + + if (SocialHub.message.isNotEmpty()) content.add(text(SocialHub.message, 13f, muted = true), 12) + + // Freunde + val list = card() + list.add(text(getString(R.string.social_friends), 17f, bold = true), 0) + val friends = SocialHub.friends + if (friends.friends.isEmpty()) list.add(text(getString(R.string.social_no_friends), 13f, muted = true)) + for (friend in friends.friends) list.add(friendRow(friend), 10) + list.add(text(getString(R.string.social_invite_hint), 12f, muted = true), 10) + + // Anfragen + if (friends.incoming.isNotEmpty()) { + val card = card() + card.add(text(getString(R.string.social_incoming), 17f, bold = true), 0) + for (p in friends.incoming) { + card.add(personRow(p.name, button(getString(R.string.social_accept), primary = true) { SocialHub.friendAction("accept", p.id) }, + button(getString(R.string.social_decline)) { SocialHub.friendAction("remove", p.id) })) + } + } + if (friends.outgoing.isNotEmpty()) { + val card = card() + card.add(text(getString(R.string.social_outgoing), 17f, bold = true), 0) + for (p in friends.outgoing) card.add(personRow(p.name, button(getString(R.string.social_withdraw)) { SocialHub.friendAction("remove", p.id) })) + } + + // Freunde finden + val search = card() + search.add(text(getString(R.string.social_search), 17f, bold = true), 0) + val query = input(R.string.social_search_placeholder).apply { + setText(searchText) + imeOptions = EditorInfo.IME_ACTION_SEARCH + } + val doSearch = { + searchText = query.text.toString().trim() + if (searchText.length < 2) { + SocialHub.message = getString(R.string.social_search_short) + render() + } else { + SocialHub.call("GET", "/api/friends/search?q=" + Uri.encode(searchText), null, true) { json, error -> + results = json?.let { SocialLogic.parseResults(it) } ?: emptyList() + SocialHub.message = when { + error != null -> SocialHub.errorText(error) + results.isEmpty() -> getString(R.string.social_no_results) + else -> "" + } + render() + } + } + } + query.setOnEditorActionListener { _, _, _ -> doSearch(); true } + val searchRow = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL } + searchRow.addView(query, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + searchRow.addView(button(getString(R.string.social_search_button)) { doSearch() }, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginStart = dp(8) }) + search.add(searchRow) + for (p in results) { + val info = when (p.relation) { + "friend" -> getString(R.string.social_rel_friend) + "outgoing" -> getString(R.string.social_rel_outgoing) + "incoming" -> getString(R.string.social_rel_incoming) + else -> null + } + val actions = when (p.relation) { + "none", "" -> arrayOf(button(getString(R.string.social_add)) { SocialHub.friendAction("request", p.id) { e -> if (e == null) refreshResult(p, "outgoing") } }) + "incoming" -> arrayOf(button(getString(R.string.social_accept), primary = true) { SocialHub.friendAction("accept", p.id) { e -> if (e == null) refreshResult(p, "friend") } }) + else -> emptyArray() + } + search.add(personRow(p.name, *actions, info = info)) + } + + // Konto + val account = card() + account.add(text(getString(R.string.social_signed_in_as), 12f, muted = true), 0) + account.add(text(SocialHub.user?.name ?: SocialHub.savedName(), 18f, bold = true), 2) + SocialHub.user?.email?.takeIf { it.isNotBlank() }?.let { account.add(text(it, 13f, muted = true), 0) } + if (!SocialHub.connected) account.add(text(getString(R.string.social_offline), 12f, muted = true)) + account.add(SwitchCompat(this).apply { + text = getString(R.string.social_share) + setTextColor(color(R.color.text)) + isChecked = SocialHub.user?.share ?: true + setOnCheckedChangeListener { b, checked -> if (b.isPressed) SocialHub.setShare(checked) } + }) + account.add(text(getString(R.string.social_share_hint), 12f, muted = true), 0) + account.add(row(button(getString(R.string.social_logout)) { SocialHub.logout() }, button(getString(R.string.social_delete_account)) { confirmDelete() }), 12) + account.add(link(getString(R.string.social_privacy)) { openPrivacy() }) + } + + private fun refreshResult(person: SocialLogic.Person, relation: String) { + results = results.map { if (it.id == person.id) it.copy(relation = relation) else it } + render() + } + + private fun personRow(name: String, vararg actions: View, info: String? = null): View { + val line = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL } + val texts = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } + texts.addView(text(name)) + info?.let { texts.addView(text(it, 12f, muted = true)) } + line.addView(texts, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + actions.forEach { action -> + line.addView(action, LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { marginStart = dp(6) }) + } + return line + } + + private fun friendRow(friend: SocialLogic.Friend): View { + val line = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER_VERTICAL } + // Cover des laufenden Titels, sonst Anfangsbuchstabe + val avatar = FrameLayout(this).apply { + setBackgroundResource(if (friend.online) R.drawable.bg_brand_button else R.drawable.bg_tile) + clipToOutline = true + } + val letter = text(friend.name.take(1).uppercase(), 16f, bold = true).apply { gravity = Gravity.CENTER } + avatar.addView(letter, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + friend.track?.thumb?.let { url -> + val image = ImageView(this).apply { scaleType = ImageView.ScaleType.CENTER_CROP } + avatar.addView(image, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) + ImageCache.load(url, dp(48)) { bitmap -> if (bitmap != null) image.setImageBitmap(bitmap) } + } + line.addView(avatar, LinearLayout.LayoutParams(dp(46), dp(46))) + val texts = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(dp(10), 0, dp(6), 0) } + val dot = if (friend.listening) "● " else if (friend.online) "● " else "○ " + texts.addView(text(dot + friend.name, bold = true).apply { + if (!friend.online) setTextColor(color(R.color.text_muted)) + }) + val online = when (friend.client) { + "pc" -> getString(R.string.social_online_pc) + "android" -> getString(R.string.social_online_android) + else -> getString(R.string.social_online) + } + texts.addView(text(SocialLogic.friendLine(friend, getString(R.string.social_offline_state), online), 12f, muted = true).apply { + isSingleLine = true + ellipsize = android.text.TextUtils.TruncateAt.END + }) + line.addView(texts, LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)) + line.addView(button(getString(R.string.social_invite)) { SocialHub.invite(friend.id) }.apply { + isEnabled = !SocialHub.isInvited(friend.id) + alpha = if (isEnabled) 1f else 0.5f + }) + line.setOnLongClickListener { + AlertDialog.Builder(this) + .setMessage(getString(R.string.social_remove_confirm, friend.name)) + .setPositiveButton(R.string.social_remove_friend) { _, _ -> SocialHub.friendAction("remove", friend.id) } + .setNegativeButton(R.string.pc_cancel, null) + .show() + true + } + return line + } + + private fun confirmDelete() { + val password = input(R.string.social_password_field, password = true) + val box = FrameLayout(this).apply { setPadding(dp(20), dp(8), dp(20), 0); addView(password) } + AlertDialog.Builder(this) + .setTitle(R.string.social_delete_account) + .setMessage(R.string.social_delete_hint) + .setView(box) + .setPositiveButton(R.string.social_delete_confirm) { _, _ -> + SocialHub.call("DELETE", "/api/account", JSONObject().put("password", password.text.toString()), true) { _, error -> + if (error == null) SocialHub.forget(getString(R.string.social_deleted)) else { + SocialHub.message = SocialHub.errorText(error) + render() + } + } + } + .setNegativeButton(R.string.pc_cancel, null) + .show() + } + + /** Einladung annehmen: einem anderen Sync erst verlassen, dann beitreten und den Sync zeigen. */ + private fun join(invite: SocialLogic.Invite) { + SocialHub.dismiss(invite.id) + val name = JamHub.savedName().ifBlank { SocialHub.user?.name ?: SocialHub.savedName() } + if (JamHub.code == invite.code) { + JamActivity.start(this) + return + } + val delay = if (JamHub.active) { + JamHub.leave() + 1000L + } else 0L + handler.postDelayed({ + JamHub.join(invite.code, name) + JamActivity.start(this) + }, delay) + } + + private fun openPrivacy() { + runCatching { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(SocialHub.PRIVACY_URL))) } + } +} diff --git a/app/src/main/java/de/fojadrachi/playtube/SocialHub.kt b/app/src/main/java/de/fojadrachi/playtube/SocialHub.kt new file mode 100644 index 0000000..0f181a9 --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/SocialHub.kt @@ -0,0 +1,343 @@ +package de.fojadrachi.playtube + +import android.Manifest +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Build +import android.os.Handler +import android.os.Looper +import androidx.core.app.NotificationCompat +import androidx.core.content.ContextCompat +import okhttp3.Call +import okhttp3.Callback +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-Konto und Freunde (freiwillig): Anmeldung, Freundesliste mit Online-Status und + * laufendem Titel, Einladungen in den Sync. Gespeichert wird nur das Sitzungstoken, nie das Passwort. + * Die Anzeige ist [SocialActivity]; der eigene Titel kommt von [MainActivity] ([observe]). + */ +object SocialHub { + private const val PREFS = "social" + private const val KEY_TOKEN = "token" + private const val KEY_NAME = "name" + private const val CHANNEL_ID = "invites" + private const val INVITE_TTL_MS = 15 * 60_000L + const val PRIVACY_URL = "https://playtube-ppp-eula.pages.dev/playtube/privacy/#konto" + + private val main = Handler(Looper.getMainLooper()) + private val http = OkHttpClient.Builder() + .connectTimeout(10, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .pingInterval(30, TimeUnit.SECONDS) + .build() + private val jsonType = "application/json".toMediaType() + + private var appContext: Context? = null + private var socket: WebSocket? = null + private var reconnectDelay = 2000L + private var lastPresence: String? = null + + var user: SocialLogic.User? = null + private set + var connected = false + private set + var friends = SocialLogic.Friends.EMPTY + private set + /** Einladung + Empfangszeit */ + val invites = ArrayList>() + /** Freunde, die eingeladen werden, sobald der eigene Sync laeuft */ + private val pendingInvites = LinkedHashSet() + /** Schon in den Sync mit diesem Code eingeladen */ + private var invitedCode: String? = null + val invited = HashSet() + /** Kurze Meldung fuer die Anzeige (Fehler, "Einladung gesendet" ...) */ + var message: String = "" + + val listeners = LinkedHashSet<() -> Unit>() + + private val server: String get() = JamHub.server + private fun prefs() = appContext!!.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + private fun str(id: Int, vararg args: Any): String = appContext!!.getString(id, *args) + private fun notifyListeners() = listeners.toList().forEach { it() } + + val signedIn: Boolean get() = token() != null + fun token(): String? = prefs().getString(KEY_TOKEN, null)?.takeIf { it.isNotEmpty() } + fun savedName(): String = prefs().getString(KEY_NAME, "") ?: "" + + /** Einmal beim App-Start (MainActivity): gespeicherte Anmeldung wieder aufnehmen. */ + fun init(context: Context) { + if (appContext != null) return + appContext = context.applicationContext + // Wenn der eigene Sync startet, wartende Einladungen schicken. + JamHub.listeners.add { onJamChanged() } + token()?.let { openSocket() } + } + + // ------------------------------------------------------------------ REST + + /** Aufruf an den Server; [done] laeuft auf dem Hauptthread mit (Antwort, Fehlerschluessel). */ + fun call(method: String, path: String, body: JSONObject?, withToken: Boolean, done: (JSONObject?, String?) -> Unit) { + val builder = Request.Builder().url(server + path) + val requestBody = (body ?: JSONObject()).toString().toRequestBody(jsonType) + when (method) { + "GET" -> builder.get() + "PATCH" -> builder.patch(requestBody) + "DELETE" -> builder.delete(requestBody) + else -> builder.post(requestBody) + } + if (withToken) token()?.let { builder.header("Authorization", "Bearer $it") } + http.newCall(builder.build()).enqueue(object : Callback { + override fun onFailure(call: Call, e: IOException) { + Diagnostics.line("social: $path nicht erreichbar: $e") + main.post { done(null, "network") } + } + + override fun onResponse(call: Call, response: Response) { + val status = response.code + val json = response.use { runCatching { JSONObject(it.body?.string() ?: "") }.getOrNull() } + main.post { + if (status in 200..299 && json?.optBoolean("ok", true) != false) done(json, null) + else done(json, SocialLogic.errorOf(status, json)) + } + } + }) + } + + /** Anmelden/Registrieren war erfolgreich: Token merken und verbinden. */ + fun signedIn(json: JSONObject): Boolean { + val token = json.optString("token").takeIf { it.isNotEmpty() } ?: return false + val account = SocialLogic.parseUser(json.optJSONObject("user")) ?: return false + user = account + prefs().edit().putString(KEY_TOKEN, token).putString(KEY_NAME, account.name).apply() + message = "" + openSocket() + notifyListeners() + return true + } + + /** Lokal abmelden (geht auch offline); das Token wird beim Server ungueltig gemacht. */ + fun logout() { + val token = token() + if (token != null) call("POST", "/api/account/logout", null, true) { _, _ -> } + forget(str(R.string.social_logged_out)) + } + + fun forget(reason: String) { + prefs().edit().remove(KEY_TOKEN).apply() + socket?.close(1000, null) + socket = null + user = null + connected = false + friends = SocialLogic.Friends.EMPTY + invites.clear() + pendingInvites.clear() + invited.clear() + lastPresence = null + message = reason + notifyListeners() + } + + fun setShare(share: Boolean) { + call("PATCH", "/api/account", JSONObject().put("share", share), true) { json, error -> + if (error != null) message = errorText(error) + SocialLogic.parseUser(json?.optJSONObject("user"))?.let { user = it } + notifyListeners() + } + } + + fun friendAction(action: String, id: String, done: (String?) -> Unit = {}) { + call("POST", "/api/friends/$action", JSONObject().put("id", id), true) { json, error -> + message = when { + error != null -> errorText(error) + json?.optString("status") == "requested" -> str(R.string.social_requested) + json?.optString("status") == "friends" -> str(R.string.social_now_friends) + else -> "" + } + notifyListeners() + done(error) + } + } + + fun errorText(error: String): String { + val id = appContext!!.resources.getIdentifier("social_error_$error", "string", appContext!!.packageName) + return if (id != 0) str(id) else str(R.string.social_error_failed) + } + + // ------------------------------------------------------------------ Verbindung + + private fun openSocket() { + val token = token() ?: return + socket?.close(1000, null) + val wsUrl = server.replaceFirst("https://", "wss://").replaceFirst("http://", "ws://") + "/api/social/ws" + socket = http.newWebSocket(Request.Builder().url(wsUrl).build(), object : WebSocketListener() { + override fun onOpen(webSocket: WebSocket, response: Response) { + webSocket.send(JSONObject().put("t", "auth").put("token", token).put("client", "android").toString()) + main.post { + if (socket !== webSocket) return@post + reconnectDelay = 2000L + lastPresence?.let { webSocket.send(it) } + } + } + + override fun onMessage(webSocket: WebSocket, text: String) { + main.post { if (socket === webSocket) handle(text) } + } + + override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { + Diagnostics.line("social: Verbindung fehlgeschlagen: $t") + main.post { if (socket === webSocket) lost() } + } + + override fun onClosed(webSocket: WebSocket, code: Int, reason: String) { + main.post { if (socket === webSocket) lost() } + } + }) + } + + private fun lost() { + socket = null + connected = false + notifyListeners() + if (token() == null) return + main.postDelayed({ if (socket == null && token() != null) openSocket() }, reconnectDelay) + reconnectDelay = (reconnectDelay * 2).coerceAtMost(60_000L) + } + + private fun handle(text: String) { + val msg = runCatching { JSONObject(text) }.getOrNull() ?: return + when (msg.optString("t")) { + "ready" -> { + connected = true + SocialLogic.parseUser(msg.optJSONObject("user"))?.let { + user = it + prefs().edit().putString(KEY_NAME, it.name).apply() + } + lastPresence?.let { socket?.send(it) } + } + "friends" -> friends = SocialLogic.parseFriends(msg) + "invite" -> SocialLogic.parseInvite(msg)?.let { invite -> + invites.removeAll { it.first.fromId == invite.fromId } + invites.add(invite to System.currentTimeMillis()) + notifyInvite(invite) + } + "invited" -> message = str(if (msg.optBoolean("delivered")) R.string.social_invited else R.string.social_invited_later) + "error" -> if (msg.optString("for") == "invite") message = errorText(msg.optString("error")) + "signedOut" -> { + val reason = msg.optString("reason") + forget(errorText(if (reason == "unauthorized") "session_expired" else reason)) + return + } + else -> return + } + notifyListeners() + } + + /** Eigener Player (alle 2 s aus MainActivity): nur bei Aenderung an die Freunde. */ + fun observe(info: NowPlaying?, videoId: String?) { + if (token() == null) return + val text = SocialLogic.presence(info, videoId).toString() + if (text == lastPresence) return + lastPresence = text + if (connected) socket?.send(text) + } + + // ------------------------------------------------------------------ Einladungen + + fun activeInvites(): List { + val now = System.currentTimeMillis() + invites.removeAll { now - it.second > INVITE_TTL_MS } + return invites.map { it.first } + } + + fun dismiss(inviteId: String) { + invites.removeAll { it.first.id == inviteId } + notificationManager()?.cancel(inviteId.hashCode()) + notifyListeners() + } + + /** Freund in den eigenen Sync einladen (laeuft keiner, wird einer gestartet). */ + fun invite(friendId: String) { + val code = JamHub.code + if (code != null) { + sendInvite(friendId, code) + } else { + val starting = pendingInvites.isNotEmpty() + pendingInvites.add(friendId) + message = str(R.string.social_starting_sync) + if (!starting) { + val name = JamHub.savedName().ifBlank { user?.name ?: savedName() } + val first = JamHub.pageVideo?.let { page -> + JSONObject().put("t", "add").put("videoId", page.videoId).put("title", page.title).put("artist", page.artist) + } + JamHub.start(name, first) + } + } + notifyListeners() + } + + private fun sendInvite(friendId: String, code: String) { + socket?.send(JSONObject().put("t", "invite").put("to", friendId).put("code", code).toString()) + if (invitedCode != code) { + invitedCode = code + invited.clear() + } + invited.add(friendId) + } + + fun isInvited(friendId: String): Boolean = + friendId in pendingInvites || (invitedCode != null && invitedCode == JamHub.code && friendId in invited) + + private fun onJamChanged() { + val code = JamHub.code ?: return + if (pendingInvites.isEmpty()) return + val waiting = pendingInvites.toList() + pendingInvites.clear() + waiting.forEach { sendInvite(it, code) } + notifyListeners() + } + + private fun notificationManager(): NotificationManager? = + appContext?.getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager + + /** Systembenachrichtigung - antippen oeffnet "Sozial" mit der Einladung. */ + private fun notifyInvite(invite: SocialLogic.Invite) { + val context = appContext ?: return + if (Build.VERSION.SDK_INT >= 33 && + ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED + ) return + val manager = notificationManager() ?: return + manager.createNotificationChannel( + NotificationChannel(CHANNEL_ID, str(R.string.channel_invites), NotificationManager.IMPORTANCE_HIGH), + ) + val open = Intent(context, SocialActivity::class.java) + .putExtra(SocialActivity.EXTRA_JOIN, invite.id) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP) + val pending = PendingIntent.getActivity( + context, invite.id.hashCode(), open, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + val notification = NotificationCompat.Builder(context, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(str(R.string.social_invite_from, invite.fromName)) + .setContentText(invite.songTitle?.let { str(R.string.social_invite_playing, it) } ?: str(R.string.social_invite_tap)) + .setContentIntent(pending) + .setAutoCancel(true) + .setTimeoutAfter(INVITE_TTL_MS) + .setPriority(NotificationCompat.PRIORITY_HIGH) + .build() + manager.notify(invite.id.hashCode(), notification) + } +} diff --git a/app/src/main/java/de/fojadrachi/playtube/SocialLogic.kt b/app/src/main/java/de/fojadrachi/playtube/SocialLogic.kt new file mode 100644 index 0000000..037e17b --- /dev/null +++ b/app/src/main/java/de/fojadrachi/playtube/SocialLogic.kt @@ -0,0 +1,86 @@ +package de.fojadrachi.playtube + +import org.json.JSONArray +import org.json.JSONObject + +/** + * Playtube-Konten und Freunde: reine Logik (ohne Android) fuer [SocialHub] und [SocialActivity]. + * Protokoll wie in `playtube-jam/src/social_hub.js`. + */ +object SocialLogic { + data class User(val id: String, val name: String, val email: String, val share: Boolean) + data class Track(val title: String, val artist: String, val thumb: String?, val videoId: String?) + data class Friend(val id: String, val name: String, val status: String, val track: Track?, val client: String?) { + val online: Boolean get() = status != "offline" + val listening: Boolean get() = status == "listening" && track != null + } + data class Person(val id: String, val name: String, val relation: String = "") + data class Friends(val friends: List, val incoming: List, val outgoing: List) { + companion object { val EMPTY = Friends(emptyList(), emptyList(), emptyList()) } + } + data class Invite(val id: String, val fromId: String, val fromName: String, val code: String, val songTitle: String?) + + private fun JSONObject.str(key: String): String? = + if (isNull(key)) null else optString(key).takeIf { it.isNotEmpty() } + + fun parseUser(json: JSONObject?): User? { + json ?: return null + val id = json.str("id") ?: return null + return User(id, json.optString("name"), json.optString("email"), json.optBoolean("share", true)) + } + + private fun persons(array: JSONArray?): List = + (0 until (array?.length() ?: 0)).mapNotNull { i -> + val p = array!!.optJSONObject(i) ?: return@mapNotNull null + Person(p.str("id") ?: return@mapNotNull null, p.optString("name"), p.optString("relation")) + } + + fun parseFriends(json: JSONObject): Friends { + val list = json.optJSONArray("friends") + val friends = (0 until (list?.length() ?: 0)).mapNotNull { i -> + val f = list!!.optJSONObject(i) ?: return@mapNotNull null + val t = f.optJSONObject("track") + val track = t?.str("title")?.let { Track(it, t.optString("artist"), t.str("thumb"), t.str("videoId")) } + Friend(f.str("id") ?: return@mapNotNull null, f.optString("name"), f.optString("status", "offline"), track, f.str("client")) + } + return Friends(friends, persons(json.optJSONArray("incoming")), persons(json.optJSONArray("outgoing"))) + } + + fun parseResults(json: JSONObject): List = persons(json.optJSONArray("results")) + + fun parseInvite(json: JSONObject): Invite? { + val from = json.optJSONObject("from") ?: return null + return Invite( + id = json.str("id") ?: return null, + fromId = from.str("id") ?: return null, + fromName = from.optString("name"), + code = JamSync.normalizeCode(json.str("code")) ?: return null, + songTitle = json.optJSONObject("current")?.str("title"), + ) + } + + /** Was die Freunde ueber den eigenen Player erfahren (`presence`-Nachricht). */ + fun presence(info: NowPlaying?, videoId: String?): JSONObject { + val msg = JSONObject().put("t", "presence") + if (info == null || !info.playing || !info.hasTrack) return msg.put("playing", false) + msg.put("playing", true).put("title", info.title).put("artist", info.artist) + info.artworkUrl?.takeIf { it.startsWith("https://") }?.let { msg.put("thumb", it) } + videoId?.let { msg.put("videoId", it) } + return msg + } + + /** Fehlerschluessel aus einer REST-Antwort. */ + fun errorOf(status: Int, body: JSONObject?): String = + body?.str("error") ?: when (status) { + 401 -> "unauthorized" + 429 -> "rate_limited" + else -> "failed" + } + + /** Zeile unter dem Namen in der Freundesliste. */ + fun friendLine(friend: Friend, offline: String, online: String): String = when { + friend.listening -> "♪ " + friend.track!!.title + (if (friend.track.artist.isNotBlank()) " – " + friend.track.artist else "") + friend.online -> online + else -> offline + } +} diff --git a/app/src/main/res/drawable/ic_people.xml b/app/src/main/res/drawable/ic_people.xml new file mode 100644 index 0000000..cdde116 --- /dev/null +++ b/app/src/main/res/drawable/ic_people.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 028c9e2..d8fd4f2 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -50,13 +50,28 @@ android:scaleType="fitCenter" android:src="@drawable/ic_jam" /> - + + + + Damit Fehler schneller behoben werden, sendet Playtube Fehlermeldungen und Abstürze (ohne Cookies, Anmeldedaten, Suchanfragen oder Songtitel) an den Playtube-Server. Du kannst das jederzeit über das Zahnrad abschalten. OK Abschalten + + Sozial: Freunde und Konto + Sozial + Einladungen von Freunden + Mit einem Playtube-Konto siehst du, was deine Freunde gerade hören, und holst sie mit einem Tipp in deinen Sync. + Anmelden + Konto erstellen + Passwort vergessen + Benutzername oder E-Mail + Benutzername (3–20 Zeichen: A–Z, 0–9, _ . -) + E-Mail-Adresse + Passwort + Passwort wiederholen + Anmelden + Konto erstellen + Link schicken + Neues Konto erstellen + Zur Anmeldung + Passwort vergessen? + Ein Konto ist freiwillig – Sync per Code oder Link geht weiterhin ohne. Passwort mindestens 8 Zeichen. + Datenschutz + Angemeldet als + Abmelden + Freunde sehen, was ich höre + Aus: Freunde sehen nur, ob du online bist. + Konto löschen + Endgültig löschen + Löscht dein Konto, alle Freundschaften und Anfragen sofort. Zur Bestätigung dein Passwort: + Freunde + Noch keine Freunde – such unten nach ihrem Benutzernamen. + Freunde finden + Benutzername + Suchen + Hinzufügen + Annehmen + Ablehnen + Zurückziehen + Entfernen + %1$s als Freund entfernen? + Anfragen + Gesendete Anfragen + Einladen + „Einladen“ holt den Freund in deinen Sync – läuft noch keiner, wird einer gestartet. Lange tippen entfernt einen Freund. + Einladungen + %1$s lädt dich in den Sync ein + Läuft gerade: %1$s + Tippen zum Beitreten + Beitreten + Ausblenden + Keine Verbindung zum Server – versuche es gleich wieder … + Offline + Online + Online · PC + Online · Android + Schon befreundet + Anfrage gesendet + Hat dir eine Anfrage geschickt + Einen Moment … + Die beiden Passwörter sind nicht gleich. + Falls es ein Konto mit dieser Adresse gibt, ist ein Link unterwegs (60 Minuten gültig). Schau auch im Spam-Ordner. + Abgemeldet. + Dein Konto ist gelöscht. + Mindestens 2 Zeichen eingeben. + Niemanden gefunden. + Anfrage gesendet. + Ihr seid jetzt befreundet. + Sync wird gestartet, dann geht die Einladung raus … + Einladung gesendet. + Gerade nicht online – die Einladung wartet 15 Minuten auf deinen Freund. + Das hat nicht geklappt. Bitte versuch es noch einmal. + Keine Verbindung zum Server. + Benutzername/E-Mail oder Passwort stimmt nicht. + Das Passwort stimmt nicht. + Zu viele Fehlversuche. Das Konto ist 15 Minuten gesperrt – oder setze das Passwort zurück. + Zu viele Versuche. Bitte warte eine Minute. + Benutzername: 3–20 Zeichen, nur A–Z, 0–9, _ . - + Das ist keine gültige E-Mail-Adresse. + Das Passwort ist zu kurz (mindestens 8 Zeichen). + Das Passwort ist zu lang. + Dieser Benutzername ist schon vergeben. + Mit dieser E-Mail gibt es schon ein Konto – melde dich an oder setze das Passwort zurück. + Der Mailversand ist noch nicht eingerichtet. Bitte später noch einmal versuchen. + Die E-Mail konnte nicht verschickt werden. Bitte später noch einmal versuchen. + Bitte melde dich neu an. + Deine Anmeldung ist abgelaufen. Bitte melde dich neu an. + Dein Passwort wurde geändert. Bitte melde dich mit dem neuen an. + Dein Konto ist gelöscht. + Abgemeldet. + Diesen Benutzer gibt es nicht. + Ihr seid schon befreundet. + Anfrage ist schon unterwegs. + Diese Anfrage gibt es nicht mehr. + Zu viele Freunde bzw. offene Anfragen. + Ihr seid (nicht mehr) befreundet. + Dein Sync läuft nicht mehr – starte einen neuen und lade noch einmal ein. + Ungültiger Sync-Code. diff --git a/app/src/test/java/de/fojadrachi/playtube/SocialLogicTest.kt b/app/src/test/java/de/fojadrachi/playtube/SocialLogicTest.kt new file mode 100644 index 0000000..c85d1c6 --- /dev/null +++ b/app/src/test/java/de/fojadrachi/playtube/SocialLogicTest.kt @@ -0,0 +1,70 @@ +package de.fojadrachi.playtube + +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 SocialLogicTest { + @Test + fun readsFriendList() { + val json = JSONObject( + """{"t":"friends","friends":[ + {"id":"u1","name":"Anna","status":"listening","client":"pc","track":{"title":"Song","artist":"Band","thumb":null,"videoId":"dQw4w9WgXcQ"}}, + {"id":"u2","name":"Max","status":"online","track":null,"client":"android"}, + {"id":"u3","name":"Zoe","status":"offline","track":null,"client":null}], + "incoming":[{"id":"u4","name":"Tom"}],"outgoing":[]}""", + ) + val list = SocialLogic.parseFriends(json) + assertEquals(3, list.friends.size) + val anna = list.friends[0] + assertTrue(anna.listening) + assertNull(anna.track!!.thumb) + assertEquals("dQw4w9WgXcQ", anna.track!!.videoId) + assertEquals("♪ Song – Band", SocialLogic.friendLine(anna, "Offline", "Online")) + assertEquals("Online", SocialLogic.friendLine(list.friends[1], "Offline", "Online")) + assertFalse(list.friends[2].online) + assertEquals("Offline", SocialLogic.friendLine(list.friends[2], "Offline", "Online")) + assertEquals("Tom", list.incoming.single().name) + assertTrue(list.outgoing.isEmpty()) + } + + @Test + fun readsInvitesAndUsers() { + val invite = SocialLogic.parseInvite( + JSONObject("""{"t":"invite","id":"i1","from":{"id":"u1","name":"Anna"},"code":"abc234","host":"Anna","current":{"title":"Song","artist":"Band"}}"""), + )!! + assertEquals("ABC234", invite.code) + assertEquals("Anna", invite.fromName) + assertEquals("Song", invite.songTitle) + assertNull(SocialLogic.parseInvite(JSONObject("""{"t":"invite","id":"i1","from":{"id":"u1"},"code":"ABC10O"}"""))) + val user = SocialLogic.parseUser(JSONObject("""{"id":"u0","name":"Chris","email":"c@example.com","share":false}"""))!! + assertFalse(user.share) + assertNull(SocialLogic.parseUser(JSONObject("{}"))) + assertEquals("u9", SocialLogic.parseResults(JSONObject("""{"results":[{"id":"u9","name":"X","relation":"incoming"}]}""")).single().id) + } + + @Test + fun buildsPresence() { + val playing = NowPlaying("Song", "Band", "https://lh3.googleusercontent.com/x", playing = true, positionMs = 0, durationMs = 1000) + val msg = SocialLogic.presence(playing, "dQw4w9WgXcQ") + assertEquals("presence", msg.getString("t")) + assertTrue(msg.getBoolean("playing")) + assertEquals("Song", msg.getString("title")) + assertEquals("https://lh3.googleusercontent.com/x", msg.getString("thumb")) + assertEquals("dQw4w9WgXcQ", msg.getString("videoId")) + assertFalse(SocialLogic.presence(playing.copy(playing = false), null).getBoolean("playing")) + assertFalse(SocialLogic.presence(null, null).getBoolean("playing")) + assertFalse(SocialLogic.presence(playing.copy(artworkUrl = "http://x"), null).has("thumb")) + } + + @Test + fun mapsErrors() { + assertEquals("wrong_login", SocialLogic.errorOf(401, JSONObject("""{"error":"wrong_login"}"""))) + assertEquals("unauthorized", SocialLogic.errorOf(401, null)) + assertEquals("rate_limited", SocialLogic.errorOf(429, JSONObject("{}"))) + assertEquals("failed", SocialLogic.errorOf(500, null)) + } +}