Compare commits
14
Commits
5ae9bc4431
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62ca2ef9eb | ||
|
|
af43633314 | ||
|
|
ce8af7a9c4 | ||
|
|
7f55699657 | ||
|
|
341155bc6b | ||
|
|
e0dd61fbb4 | ||
|
|
e3c534c569 | ||
|
|
94485dc326 | ||
|
|
75445d06c5 | ||
|
|
448b4b8edf | ||
|
|
3b8918d45d | ||
|
|
9bab0d6a24 | ||
|
|
d8d6ef4196 | ||
|
|
661d7ee72c |
@@ -25,11 +25,19 @@ mit Hintergrundwiedergabe und Discord Rich Presence. Ohne YouTube-Tab und ohne S
|
|||||||
- **Playtube Jam** (wie Spotify Jam): gemeinsam hören, jeder synchron auf dem eigenen Gerät.
|
- **Playtube Jam** (wie Spotify Jam): gemeinsam hören, jeder synchron auf dem eigenen Gerät.
|
||||||
Über den zweiten runden Knopf am rechten Rand einen Jam starten (der gerade laufende Song wird der
|
Über den zweiten runden Knopf am rechten Rand einen Jam starten (der gerade laufende Song wird der
|
||||||
erste) oder per Code beitreten; einladen über „Link teilen“. Einladungslinks
|
erste) oder per Code beitreten; einladen über „Link teilen“. Einladungslinks
|
||||||
`https://jam.fojadrachi.de/<CODE>` und `playtube://jam/<CODE>` öffnen direkt die App; YouTube-Links
|
`https://sync.fojadrachi.de/<CODE>` und `playtube://sync/<CODE>` öffnen direkt die App; YouTube-Links
|
||||||
aus anderen Apps über „Teilen › Jam“ hinzufügen. Gespielt wird in der YouTube-Music-Ansicht der App,
|
aus anderen Apps über „Teilen › Jam“ hinzufügen – auch ganze Playlists und Alben (Playlist-Link);
|
||||||
|
mehrere Songs laufen automatisch nacheinander. Gespielt wird in der YouTube-Music-Ansicht der App,
|
||||||
die sich mit dem Jam abgleicht ([JamSync.kt](app/src/main/java/de/fojadrachi/playtube/JamSync.kt),
|
die sich mit dem Jam abgleicht ([JamSync.kt](app/src/main/java/de/fojadrachi/playtube/JamSync.kt),
|
||||||
[JamHub.kt](app/src/main/java/de/fojadrachi/playtube/JamHub.kt)). Mitspielen können Playtube am PC
|
[JamHub.kt](app/src/main/java/de/fojadrachi/playtube/JamHub.kt)). Mitspielen können Playtube am PC
|
||||||
(ab 2.2.0) und Freunde im Browser; der Dienst liegt im Projekt `playtube-jam`.
|
(ab 2.2.0) und Freunde im Browser; der Dienst liegt im Projekt `playtube-jam`.
|
||||||
|
- **Diagnosedaten** (standardmäßig an, abschaltbar über das Zahnrad am rechten Rand; beim ersten
|
||||||
|
Start erscheint ein Hinweis): Abstürze und Verbindungsfehler landen in einem kleinen eigenen Log
|
||||||
|
(`files/diag.log`), das die App kurz nach dem Start höchstens alle 6 Stunden gefiltert an den
|
||||||
|
Playtube-Dienst schickt (`/api/diag` im Projekt `playtube-jam`, 30 Tage gespeichert). Ohne Cookies,
|
||||||
|
Anmeldedaten, Suchanfragen, Songtitel oder Video-IDs
|
||||||
|
([DiagReport.kt](app/src/main/java/de/fojadrachi/playtube/DiagReport.kt),
|
||||||
|
[Diagnostics.kt](app/src/main/java/de/fojadrachi/playtube/Diagnostics.kt)).
|
||||||
- **Links** zu `music.youtube.com` öffnen sich in Playtube.
|
- **Links** zu `music.youtube.com` öffnen sich in Playtube.
|
||||||
- **Updates** aus den eigenen Releases (Tag `vX.Y.Z-android`), kein GitHub, kein Play Store.
|
- **Updates** aus den eigenen Releases (Tag `vX.Y.Z-android`), kein GitHub, kein Play Store.
|
||||||
|
|
||||||
@@ -121,6 +129,7 @@ von Playtube fragen ein anderes Repo ab und sehen sie nie.
|
|||||||
| `NowPlaying.kt` | Datensatz „läuft gerade" |
|
| `NowPlaying.kt` | Datensatz „läuft gerade" |
|
||||||
| `UpdateChecker.kt` | Update-Prüfung über die Gitea-Releases |
|
| `UpdateChecker.kt` | Update-Prüfung über die Gitea-Releases |
|
||||||
| `DiscordPresence.kt`, `PresencePlan.kt`, `cpp/` | Discord Rich Presence: was angezeigt wird, und die Brücke zum SDK |
|
| `DiscordPresence.kt`, `PresencePlan.kt`, `cpp/` | Discord Rich Presence: was angezeigt wird, und die Brücke zum SDK |
|
||||||
|
| `Diagnostics.kt`, `DiagReport.kt` | Diagnose-Log, Absturz-Handler, Filter und Versand an `/api/diag` |
|
||||||
| `UserAgent.kt` | macht die WebView-Kennung zu einer normalen Chrome-Kennung (Google-Anmeldung) |
|
| `UserAgent.kt` | macht die WebView-Kennung zu einer normalen Chrome-Kennung (Google-Anmeldung) |
|
||||||
| `PcRemote.kt`, `PcSession.kt`, `PcRemoteService.kt`, `PcRemoteActivity.kt`, `ImageCache.kt` | „PC steuern“: Protokoll, dauerhafte Verbindung (Vordergrunddienst), Fernbedienung, Cover-Cache |
|
| `PcRemote.kt`, `PcSession.kt`, `PcRemoteService.kt`, `PcRemoteActivity.kt`, `ImageCache.kt` | „PC steuern“: Protokoll, dauerhafte Verbindung (Vordergrunddienst), Fernbedienung, Cover-Cache |
|
||||||
|
|
||||||
@@ -137,3 +146,13 @@ von Playtube fragen ein anderes Repo ab und sehen sie nie.
|
|||||||
App-Aktivität).
|
App-Aktivität).
|
||||||
- Kein Like-/Wiederholen-/Zufalls-Knopf in der Benachrichtigung; die Bedienung der Seite selbst
|
- Kein Like-/Wiederholen-/Zufalls-Knopf in der Benachrichtigung; die Bedienung der Seite selbst
|
||||||
funktioniert normal.
|
funktioniert normal.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
**Diagnostics** (on by default, can be turned off via the gear button on the right edge; a notice is
|
||||||
|
shown on first start): crashes and connection errors are written to a small app log
|
||||||
|
(`files/diag.log`) that the app sends, filtered, to the Playtube service (`/api/diag` in the
|
||||||
|
`playtube-jam` project) shortly after start and at most every 6 hours. Reports are kept for 30 days.
|
||||||
|
No cookies, sign-in data, searches, song titles or video IDs are sent.
|
||||||
|
|||||||
@@ -19,14 +19,14 @@ android {
|
|||||||
applicationId = "de.fojadrachi.playtube"
|
applicationId = "de.fojadrachi.playtube"
|
||||||
minSdk = 26
|
minSdk = 26
|
||||||
targetSdk = 36
|
targetSdk = 36
|
||||||
versionCode = 8
|
versionCode = 16
|
||||||
versionName = "1.4.1"
|
versionName = "1.11.0"
|
||||||
|
|
||||||
// Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play).
|
// Update-Quelle: eigener Gitea-Server (kein GitHub/Google Play).
|
||||||
buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"")
|
buildConfigField("String", "UPDATE_SERVER", "\"https://git.fojadrachi.de\"")
|
||||||
buildConfigField("String", "REPO_SLUG", "\"Fojadrachi/Playtube-Android\"")
|
buildConfigField("String", "REPO_SLUG", "\"Fojadrachi/Playtube-Android\"")
|
||||||
// Playtube Jam: eigener Dienst (Ordner playtube-jam, Cloudflare Worker).
|
// Playtube Jam: eigener Dienst (Ordner playtube-jam, Cloudflare Worker).
|
||||||
buildConfigField("String", "JAM_SERVER", "\"https://jam.fojadrachi.de\"")
|
buildConfigField("String", "JAM_SERVER", "\"https://sync.fojadrachi.de\"")
|
||||||
// Discord-Anwendung von Playtube (gleiche wie in der Desktop-Version; die ID ist oeffentlich).
|
// Discord-Anwendung von Playtube (gleiche wie in der Desktop-Version; die ID ist oeffentlich).
|
||||||
buildConfigField("long", "DISCORD_APPLICATION_ID", "1548023494976086127L")
|
buildConfigField("long", "DISCORD_APPLICATION_ID", "1548023494976086127L")
|
||||||
|
|
||||||
|
|||||||
@@ -60,8 +60,9 @@
|
|||||||
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
|
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
|
||||||
android:windowSoftInputMode="adjustResize" />
|
android:windowSoftInputMode="adjustResize" />
|
||||||
|
|
||||||
<!-- Playtube Jam: Einladungslinks (App-Link jam.fojadrachi.de, playtube://jam/<CODE>) und
|
<!-- Playtube Sync: Einladungslinks (App-Link sync.fojadrachi.de, playtube://sync/<CODE>;
|
||||||
"Teilen" von YouTube-Links aus anderen Apps (fuegt sie zum laufenden Jam hinzu). -->
|
alt jam.fojadrachi.de / playtube://jam/ bleiben gueltig) und "Teilen" von
|
||||||
|
YouTube-Links aus anderen Apps (fuegt sie zum laufenden Sync hinzu). -->
|
||||||
<activity
|
<activity
|
||||||
android:name=".JamActivity"
|
android:name=".JamActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
@@ -73,12 +74,14 @@
|
|||||||
<action android:name="android.intent.action.VIEW" />
|
<action android:name="android.intent.action.VIEW" />
|
||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
<category android:name="android.intent.category.BROWSABLE" />
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
<data android:scheme="https" android:host="sync.fojadrachi.de" />
|
||||||
<data android:scheme="https" android:host="jam.fojadrachi.de" />
|
<data android:scheme="https" android:host="jam.fojadrachi.de" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="android.intent.action.VIEW" />
|
<action android:name="android.intent.action.VIEW" />
|
||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
<category android:name="android.intent.category.BROWSABLE" />
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
<data android:scheme="playtube" android:host="sync" />
|
||||||
<data android:scheme="playtube" android:host="jam" />
|
<data android:scheme="playtube" android:host="jam" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
<intent-filter android:label="@string/jam_title">
|
<intent-filter android:label="@string/jam_title">
|
||||||
@@ -88,6 +91,15 @@
|
|||||||
</intent-filter>
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
|
<!-- Sozial: Playtube-Konto und Freunde (SocialHub). -->
|
||||||
|
<activity
|
||||||
|
android:name=".SocialActivity"
|
||||||
|
android:exported="false"
|
||||||
|
android:label="@string/social_title"
|
||||||
|
android:launchMode="singleTop"
|
||||||
|
android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout|keyboardHidden|keyboard|uiMode"
|
||||||
|
android:windowSoftInputMode="adjustResize" />
|
||||||
|
|
||||||
<service
|
<service
|
||||||
android:name=".PcRemoteService"
|
android:name=".PcRemoteService"
|
||||||
android:exported="false"
|
android:exported="false"
|
||||||
|
|||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package de.fojadrachi.playtube
|
||||||
|
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reine Logik fuer Diagnoseberichte (ohne Android, mit Unit-Tests): Logzeilen filtern und
|
||||||
|
* den Bericht fuer `POST /api/diag` (playtube-jam) bauen. Versand und Log-Datei: [Diagnostics].
|
||||||
|
*
|
||||||
|
* Nicht gesendet werden Cookies, Tokens, Anmeldedaten, Suchanfragen, Songtitel, Video-IDs,
|
||||||
|
* E-Mail-Adressen und URL-Parameter.
|
||||||
|
*/
|
||||||
|
object DiagReport {
|
||||||
|
const val MAX_LINES = 300
|
||||||
|
const val MAX_LINE_CHARS = 480
|
||||||
|
|
||||||
|
private val COOKIE = Regex("(?i)\\b(cookie|set-cookie|authorization)\\b.*")
|
||||||
|
private val BEARER = Regex("(?i)\\bbearer\\s+\\S+")
|
||||||
|
private val SECRET = Regex("(?i)\\b(\\w*token|\\w*key|secret|password|passwort|sapisid)(\\s*[\"']?\\s*[:=]\\s*[\"']?)[^\\s\"'&,;]+")
|
||||||
|
private val EMAIL = Regex("[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}")
|
||||||
|
private val URL_QUERY = Regex("(?i)(https?://[^\\s?#\"']+)[?#][^\\s\"']*")
|
||||||
|
private val WORD = Regex("[A-Za-z0-9_-]+")
|
||||||
|
private val JSON_PRIVATE = Regex("(?i)(\"(?:title|artist|author|album|name|query|q|search)\"\\s*:\\s*)\"(?:[^\"\\\\]|\\\\.)*\"")
|
||||||
|
private val CAMEL = Regex("^([A-Z][a-z]+)+$")
|
||||||
|
private val CONTROL = Regex("[\\u0000-\\u0008\\u000b-\\u001f\\u007f\\u202a-\\u202e\\u2066-\\u2069]")
|
||||||
|
|
||||||
|
/**
|
||||||
|
* YouTube-Video-ID: 11 Zeichen aus `[A-Za-z0-9_-]`, entweder Buchstaben plus Ziffer/`_`/`-` oder
|
||||||
|
* mindestens zwei Grossbuchstaben ohne normale Schreibweise (nicht "Verbindunge", "ServerError").
|
||||||
|
*/
|
||||||
|
fun looksLikeVideoId(word: String): Boolean {
|
||||||
|
if (word.length != 11 || !word.all { it in 'A'..'Z' || it in 'a'..'z' || it in '0'..'9' || it == '_' || it == '-' }) return false
|
||||||
|
val letters = word.any { it.isLetter() }
|
||||||
|
if (word.any { it.isDigit() || it == '_' || it == '-' }) return letters
|
||||||
|
return word.count { it in 'A'..'Z' } >= 2 && word.any { it in 'a'..'z' } && !CAMEL.matches(word)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun looksLikeSecret(word: String): Boolean =
|
||||||
|
word.length >= 20 && word.any { it.isDigit() } && word.any { it.isLetter() }
|
||||||
|
|
||||||
|
fun sanitize(line: String): String {
|
||||||
|
var text = CONTROL.replace(line, " ")
|
||||||
|
text = COOKIE.replace(text) { "${it.groupValues[1].lowercase()} [entfernt]" }
|
||||||
|
text = BEARER.replace(text, "Bearer [entfernt]")
|
||||||
|
text = SECRET.replace(text) { "${it.groupValues[1]}${it.groupValues[2]}[entfernt]" }
|
||||||
|
text = EMAIL.replace(text, "[e-mail]")
|
||||||
|
text = URL_QUERY.replace(text) { "${it.groupValues[1]}?[…]" }
|
||||||
|
text = JSON_PRIVATE.replace(text) { "${it.groupValues[1]}\"[entfernt]\"" }
|
||||||
|
text = WORD.replace(text) {
|
||||||
|
when {
|
||||||
|
looksLikeVideoId(it.value) -> "[video]"
|
||||||
|
looksLikeSecret(it.value) -> "[id]"
|
||||||
|
else -> it.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return text.trim().take(MAX_LINE_CHARS)
|
||||||
|
}
|
||||||
|
|
||||||
|
data class Collected(val lines: List<String>, val latest: Long)
|
||||||
|
|
||||||
|
/** Zeilen `[secs] text` nach `since` (Unix-Sekunden), gefiltert, hoechstens [MAX_LINES] neueste. */
|
||||||
|
fun collect(logText: String, since: Long): Collected {
|
||||||
|
var latest = since
|
||||||
|
val lines = ArrayList<String>()
|
||||||
|
for (raw in logText.lineSequence()) {
|
||||||
|
if (!raw.startsWith("[")) continue
|
||||||
|
val end = raw.indexOf("] ")
|
||||||
|
if (end < 0) continue
|
||||||
|
val secs = raw.substring(1, end).toLongOrNull() ?: continue
|
||||||
|
if (secs <= since) continue
|
||||||
|
latest = maxOf(latest, secs)
|
||||||
|
lines += "[$secs] ${sanitize(raw.substring(end + 2))}"
|
||||||
|
}
|
||||||
|
return Collected(lines.takeLast(MAX_LINES), latest)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isError(line: String): Boolean {
|
||||||
|
val lower = line.lowercase()
|
||||||
|
return listOf("absturz", "exception", "error", "fehler", "fehlgeschlagen", "failed").any { it in lower }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vermerk zum Bericht: manuell gesendet (ggf. ohne neue Einträge) oder leer. */
|
||||||
|
fun note(manual: Boolean, noNewLines: Boolean): String = when {
|
||||||
|
manual && noNewLines -> "manuell gesendet (keine neuen Einträge)"
|
||||||
|
manual -> "manuell gesendet"
|
||||||
|
else -> ""
|
||||||
|
}
|
||||||
|
|
||||||
|
fun build(installId: String, version: String, androidVersion: String, device: String, lines: List<String>, note: String = ""): JSONObject =
|
||||||
|
JSONObject()
|
||||||
|
.put("app", "android")
|
||||||
|
.put("version", version)
|
||||||
|
.put("platform", "android-$androidVersion")
|
||||||
|
.put("os", device)
|
||||||
|
.put("installId", installId)
|
||||||
|
.put("lines", JSONArray(lines))
|
||||||
|
.put("errors", JSONArray(lines.filter(::isError)))
|
||||||
|
.put("note", note)
|
||||||
|
.put("includesTitles", false)
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
package de.fojadrachi.playtube
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import java.io.File
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
import java.security.SecureRandom
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Diagnosedaten: kleines eigenes Log (Abstuerze, Verbindungsfehler) in `files/diag.log`, das
|
||||||
|
* Playtube kurz nach dem Start und hoechstens alle 6 Stunden an den Playtube-Server schickt
|
||||||
|
* (`POST /api/diag`). Standardmaessig an, abschaltbar im Einstellungsdialog.
|
||||||
|
*/
|
||||||
|
object Diagnostics {
|
||||||
|
private const val PREFS = "playtube"
|
||||||
|
private const val KEY_ENABLED = "diag_enabled"
|
||||||
|
private const val KEY_INSTALL_ID = "diag_install_id"
|
||||||
|
private const val KEY_LAST_SENT = "diag_last_sent"
|
||||||
|
private const val KEY_LAST_TRY = "diag_last_try"
|
||||||
|
private const val KEY_NOTICE = "diag_notice_shown"
|
||||||
|
private const val MAX_LOG_BYTES = 256 * 1024
|
||||||
|
private const val INTERVAL_MS = 6 * 3600 * 1000L
|
||||||
|
private const val TIMEOUT_MS = 10_000
|
||||||
|
|
||||||
|
private var appContext: Context? = null
|
||||||
|
private val main = Handler(Looper.getMainLooper())
|
||||||
|
|
||||||
|
fun init(context: Context) {
|
||||||
|
if (appContext != null) return
|
||||||
|
appContext = context.applicationContext
|
||||||
|
val previous = Thread.getDefaultUncaughtExceptionHandler()
|
||||||
|
Thread.setDefaultUncaughtExceptionHandler { thread, error ->
|
||||||
|
// Absturz sofort ins Log - gesendet wird beim naechsten Start.
|
||||||
|
line("Absturz in ${thread.name}: ${error.stackTraceToString().take(3000)}")
|
||||||
|
previous?.uncaughtException(thread, error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
fun isEnabled(context: Context): Boolean = prefs(context).getBoolean(KEY_ENABLED, true)
|
||||||
|
|
||||||
|
fun setEnabled(context: Context, enabled: Boolean) {
|
||||||
|
prefs(context).edit().putBoolean(KEY_ENABLED, enabled).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Einmaliger Hinweis, dass Diagnosedaten gesendet werden (Opt-out). */
|
||||||
|
fun needsNotice(context: Context): Boolean = !prefs(context).getBoolean(KEY_NOTICE, false)
|
||||||
|
|
||||||
|
fun noticeShown(context: Context) {
|
||||||
|
prefs(context).edit().putBoolean(KEY_NOTICE, true).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun installId(context: Context): String {
|
||||||
|
val prefs = prefs(context)
|
||||||
|
prefs.getString(KEY_INSTALL_ID, null)?.takeIf { it.isNotBlank() }?.let { return it }
|
||||||
|
val bytes = ByteArray(12).also { SecureRandom().nextBytes(it) }
|
||||||
|
val id = bytes.joinToString("") { "%02x".format(it) }
|
||||||
|
prefs.edit().putString(KEY_INSTALL_ID, id).apply()
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun logFile(context: Context) = File(context.filesDir, "diag.log")
|
||||||
|
|
||||||
|
/** Zeile ins Diagnose-Log schreiben (thread-sicher, auch ohne Versand-Erlaubnis lokal). */
|
||||||
|
@Synchronized
|
||||||
|
fun line(text: String) {
|
||||||
|
val context = appContext ?: return
|
||||||
|
runCatching {
|
||||||
|
val file = logFile(context)
|
||||||
|
if (file.length() > MAX_LOG_BYTES) {
|
||||||
|
// Aeltere Haelfte verwerfen.
|
||||||
|
val keep = file.readText().takeLast(MAX_LOG_BYTES / 2)
|
||||||
|
file.writeText(keep.substring(keep.indexOf('\n') + 1))
|
||||||
|
}
|
||||||
|
file.appendText("[${System.currentTimeMillis() / 1000}] ${text.replace('\n', ' ')}\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Automatisch senden (Start): nur wenn an, neue Zeilen da und der letzte Versuch >= 6 h her ist. */
|
||||||
|
fun sendIfDue(context: Context) {
|
||||||
|
if (!isEnabled(context)) return
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (now - prefs(context).getLong(KEY_LAST_TRY, 0) < INTERVAL_MS) return
|
||||||
|
send(context, manual = false) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Senden; [done] bekommt (null = nichts Neues, true/false = Erfolg) auf dem Hauptthread.
|
||||||
|
* [manual] ("Jetzt senden"): geht auch ohne neue Logzeilen raus, dann mit dem Vermerk
|
||||||
|
* "manuell gesendet" (Version, Gerät und Kennung reichen zum Prüfen).
|
||||||
|
*/
|
||||||
|
fun send(context: Context, manual: Boolean, done: (Boolean?) -> Unit) {
|
||||||
|
val ctx = context.applicationContext
|
||||||
|
Thread {
|
||||||
|
val prefs = prefs(ctx)
|
||||||
|
val text = runCatching { logFile(ctx).readText() }.getOrDefault("")
|
||||||
|
val collected = DiagReport.collect(text, prefs.getLong(KEY_LAST_SENT, 0))
|
||||||
|
if (collected.lines.isEmpty() && !manual) {
|
||||||
|
main.post { done(null) }
|
||||||
|
return@Thread
|
||||||
|
}
|
||||||
|
prefs.edit().putLong(KEY_LAST_TRY, System.currentTimeMillis()).apply()
|
||||||
|
val body = DiagReport.build(
|
||||||
|
installId(ctx),
|
||||||
|
BuildConfig.VERSION_NAME,
|
||||||
|
Build.VERSION.RELEASE ?: "?",
|
||||||
|
"${Build.MANUFACTURER} ${Build.MODEL}".take(80),
|
||||||
|
collected.lines,
|
||||||
|
DiagReport.note(manual, collected.lines.isEmpty()),
|
||||||
|
)
|
||||||
|
val ok = post("${BuildConfig.JAM_SERVER}/api/diag", body.toString())
|
||||||
|
if (ok) prefs.edit().putLong(KEY_LAST_SENT, collected.latest).apply()
|
||||||
|
main.post { done(ok) }
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun post(url: String, json: String): Boolean =
|
||||||
|
try {
|
||||||
|
val connection = URL(url).openConnection() as HttpURLConnection
|
||||||
|
connection.connectTimeout = TIMEOUT_MS
|
||||||
|
connection.readTimeout = TIMEOUT_MS
|
||||||
|
connection.requestMethod = "POST"
|
||||||
|
connection.doOutput = true
|
||||||
|
connection.setRequestProperty("Content-Type", "application/json")
|
||||||
|
connection.setRequestProperty("User-Agent", "Playtube-Android/${BuildConfig.VERSION_NAME}")
|
||||||
|
try {
|
||||||
|
connection.outputStream.use { it.write(json.toByteArray()) }
|
||||||
|
connection.responseCode == HttpURLConnection.HTTP_OK
|
||||||
|
} finally {
|
||||||
|
connection.disconnect()
|
||||||
|
}
|
||||||
|
} catch (_: Exception) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package de.fojadrachi.playtube
|
||||||
|
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.content.Context
|
||||||
|
import android.text.Editable
|
||||||
|
import android.text.TextWatcher
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.widget.ArrayAdapter
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.ListView
|
||||||
|
import android.widget.TextView
|
||||||
|
import java.text.SimpleDateFormat
|
||||||
|
import java.util.Calendar
|
||||||
|
import java.util.Date
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
/** Verlauf als Liste mit Suchfeld (Handy-Verlauf und Verlauf am PC). */
|
||||||
|
object HistoryDialog {
|
||||||
|
fun show(
|
||||||
|
context: Context,
|
||||||
|
title: String,
|
||||||
|
entries: List<HistoryEntry>,
|
||||||
|
onPick: (HistoryEntry) -> Unit,
|
||||||
|
onClear: (() -> Unit)? = null,
|
||||||
|
) {
|
||||||
|
val pad = (16 * context.resources.displayMetrics.density).toInt()
|
||||||
|
val search = EditText(context).apply {
|
||||||
|
hint = context.getString(R.string.history_search)
|
||||||
|
isSingleLine = true
|
||||||
|
}
|
||||||
|
val empty = TextView(context).apply {
|
||||||
|
text = context.getString(R.string.history_empty)
|
||||||
|
alpha = 0.7f
|
||||||
|
setPadding(0, pad, 0, pad)
|
||||||
|
}
|
||||||
|
var shown = entries
|
||||||
|
val adapter = object : ArrayAdapter<HistoryEntry>(context, android.R.layout.simple_list_item_2, android.R.id.text1, ArrayList(entries)) {
|
||||||
|
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
|
||||||
|
val view = super.getView(position, convertView, parent)
|
||||||
|
val entry = getItem(position) ?: return view
|
||||||
|
view.findViewById<TextView>(android.R.id.text1).text = entry.title
|
||||||
|
view.findViewById<TextView>(android.R.id.text2).text =
|
||||||
|
listOf(entry.artist, timeText(context, entry.playedAt)).filter { it.isNotBlank() }.joinToString(" · ")
|
||||||
|
return view
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val list = ListView(context).apply {
|
||||||
|
this.adapter = adapter
|
||||||
|
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (360 * context.resources.displayMetrics.density).toInt())
|
||||||
|
}
|
||||||
|
fun refresh() {
|
||||||
|
val q = search.text.toString().trim().lowercase()
|
||||||
|
shown = entries.filter { q.isEmpty() || it.title.lowercase().contains(q) || it.artist.lowercase().contains(q) }
|
||||||
|
adapter.clear()
|
||||||
|
adapter.addAll(shown)
|
||||||
|
empty.visibility = if (shown.isEmpty()) View.VISIBLE else View.GONE
|
||||||
|
}
|
||||||
|
search.addTextChangedListener(object : TextWatcher {
|
||||||
|
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
|
||||||
|
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
|
||||||
|
override fun afterTextChanged(s: Editable?) = refresh()
|
||||||
|
})
|
||||||
|
val content = LinearLayout(context).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
setPadding(pad, pad / 2, pad, 0)
|
||||||
|
addView(search)
|
||||||
|
addView(empty)
|
||||||
|
addView(list)
|
||||||
|
}
|
||||||
|
refresh()
|
||||||
|
val builder = AlertDialog.Builder(context)
|
||||||
|
.setTitle(title)
|
||||||
|
.setView(content)
|
||||||
|
.setPositiveButton(R.string.history_close, null)
|
||||||
|
if (onClear != null && entries.isNotEmpty()) {
|
||||||
|
builder.setNeutralButton(R.string.history_clear) { _, _ ->
|
||||||
|
AlertDialog.Builder(context)
|
||||||
|
.setMessage(R.string.history_clear_confirm)
|
||||||
|
.setPositiveButton(R.string.history_clear) { _, _ -> onClear() }
|
||||||
|
.setNegativeButton(android.R.string.cancel, null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val dialog = builder.show()
|
||||||
|
list.setOnItemClickListener { _, _, position, _ ->
|
||||||
|
shown.getOrNull(position)?.let(onPick)
|
||||||
|
dialog.dismiss()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Heute, 14:32" bzw. "15.11., 14:32". */
|
||||||
|
private fun timeText(context: Context, millis: Long): String {
|
||||||
|
if (millis <= 0) return ""
|
||||||
|
val time = android.text.format.DateFormat.getTimeFormat(context).format(Date(millis))
|
||||||
|
val then = Calendar.getInstance().apply { timeInMillis = millis }
|
||||||
|
val now = Calendar.getInstance()
|
||||||
|
val sameDay = then.get(Calendar.YEAR) == now.get(Calendar.YEAR) && then.get(Calendar.DAY_OF_YEAR) == now.get(Calendar.DAY_OF_YEAR)
|
||||||
|
return if (sameDay) context.getString(R.string.history_today, time)
|
||||||
|
else SimpleDateFormat("d.M.", Locale.GERMANY).format(Date(millis)) + ", " + time
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -83,6 +83,11 @@ class JamActivity : AppCompatActivity() {
|
|||||||
codeInput.setOnEditorActionListener { _, _, _ -> joinJam(codeInput.text.toString()); true }
|
codeInput.setOnEditorActionListener { _, _, _ -> joinJam(codeInput.text.toString()); true }
|
||||||
leave.setOnClickListener { JamHub.leave() }
|
leave.setOnClickListener { JamHub.leave() }
|
||||||
findViewById<View>(R.id.jamPlayPause).setOnClickListener { JamHub.playPause() }
|
findViewById<View>(R.id.jamPlayPause).setOnClickListener { JamHub.playPause() }
|
||||||
|
findViewById<View>(R.id.jamNowLike).setOnClickListener {
|
||||||
|
if (JamHub.state?.current == null) return@setOnClickListener
|
||||||
|
// Herz zaehlt fuer den laufenden Song, der in der WebView spielt - mit deinem Login.
|
||||||
|
PlaybackHub.send(PlayerCommand.Like)
|
||||||
|
}
|
||||||
findViewById<View>(R.id.jamNext).setOnClickListener { JamHub.send("skip") }
|
findViewById<View>(R.id.jamNext).setOnClickListener { JamHub.send("skip") }
|
||||||
findViewById<View>(R.id.jamPrevious).setOnClickListener { JamHub.send("previous") }
|
findViewById<View>(R.id.jamPrevious).setOnClickListener { JamHub.send("previous") }
|
||||||
addButton.setOnClickListener { add() }
|
addButton.setOnClickListener { add() }
|
||||||
@@ -140,7 +145,17 @@ class JamActivity : AppCompatActivity() {
|
|||||||
if (nameInput.text.isNotBlank()) joinJam(code) else nameInput.requestFocus()
|
if (nameInput.text.isNotBlank()) joinJam(code) else nameInput.requestFocus()
|
||||||
}
|
}
|
||||||
Intent.ACTION_SEND -> {
|
Intent.ACTION_SEND -> {
|
||||||
val videoId = JamSync.videoIdFromSharedText(intent.getStringExtra(Intent.EXTRA_TEXT)) ?: return
|
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) {
|
if (JamHub.active) {
|
||||||
JamHub.addVideo(videoId)
|
JamHub.addVideo(videoId)
|
||||||
Toast.makeText(this, R.string.jam_added_shared, Toast.LENGTH_SHORT).show()
|
Toast.makeText(this, R.string.jam_added_shared, Toast.LENGTH_SHORT).show()
|
||||||
@@ -186,6 +201,13 @@ class JamActivity : AppCompatActivity() {
|
|||||||
val text = addInput.text.toString().trim()
|
val text = addInput.text.toString().trim()
|
||||||
if (text.isEmpty()) return
|
if (text.isEmpty()) return
|
||||||
val videoId = JamSync.parseVideoId(text)
|
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) {
|
if (videoId != null) {
|
||||||
JamHub.addVideo(videoId)
|
JamHub.addVideo(videoId)
|
||||||
addInput.setText("")
|
addInput.setText("")
|
||||||
@@ -236,6 +258,9 @@ class JamActivity : AppCompatActivity() {
|
|||||||
val state = JamHub.state ?: return
|
val state = JamHub.state ?: return
|
||||||
|
|
||||||
val item = state.current
|
val item = state.current
|
||||||
|
val like = findViewById<ImageButton>(R.id.jamNowLike)
|
||||||
|
like.visibility = if (item != null) View.VISIBLE else View.GONE
|
||||||
|
like.setImageResource(if (PlaybackHub.nowPlaying.likeStatus == "like") R.drawable.ic_like else R.drawable.ic_favorite_border)
|
||||||
findViewById<TextView>(R.id.jamNowTitle).text = item?.title ?: getString(R.string.jam_nothing)
|
findViewById<TextView>(R.id.jamNowTitle).text = item?.title ?: getString(R.string.jam_nothing)
|
||||||
findViewById<TextView>(R.id.jamNowArtist).text = item?.let { subtitle(it) } ?: ""
|
findViewById<TextView>(R.id.jamNowArtist).text = item?.let { subtitle(it) } ?: ""
|
||||||
val cover = findViewById<ImageView>(R.id.jamCover)
|
val cover = findViewById<ImageView>(R.id.jamCover)
|
||||||
@@ -292,7 +317,18 @@ class JamActivity : AppCompatActivity() {
|
|||||||
Unit
|
Unit
|
||||||
}
|
}
|
||||||
} else null
|
} else null
|
||||||
members.addView(row(name, info, image = null, initial = m.name.take(1).uppercase(), action1 = null, action2 = kick).apply {
|
// Host-Rolle abgeben (nur an jemanden, der gerade verbunden ist).
|
||||||
|
val makeHost = if (state.isHost && m.id != state.you && m.online) {
|
||||||
|
R.drawable.ic_crown to {
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setMessage(getString(R.string.jam_make_host_confirm, m.name))
|
||||||
|
.setPositiveButton(R.string.jam_make_host) { _, _ -> JamHub.send("transfer", "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 = makeHost, action2 = kick).apply {
|
||||||
alpha = if (m.online) 1f else 0.5f
|
alpha = if (m.online) 1f else 0.5f
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -327,6 +363,10 @@ class JamActivity : AppCompatActivity() {
|
|||||||
findViewById<TextView>(R.id.jamTime).text = JamSync.formatTime(pos)
|
findViewById<TextView>(R.id.jamTime).text = JamSync.formatTime(pos)
|
||||||
findViewById<TextView>(R.id.jamDuration).text = JamSync.formatTime(dur)
|
findViewById<TextView>(R.id.jamDuration).text = JamSync.formatTime(dur)
|
||||||
if (!seeking) seek.progress = if (dur > 0) (pos / dur * 1000).toInt() else 0
|
if (!seeking) seek.progress = if (dur > 0) (pos / dur * 1000).toInt() else 0
|
||||||
|
val like = findViewById<ImageButton>(R.id.jamNowLike)
|
||||||
|
if (like.visibility == View.VISIBLE) {
|
||||||
|
like.setImageResource(if (PlaybackHub.nowPlaying.likeStatus == "like") R.drawable.ic_like else R.drawable.ic_favorite_border)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun subtitle(item: JamSync.Item): String {
|
private fun subtitle(item: JamSync.Item): String {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import okhttp3.WebSocketListener
|
|||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.io.IOException
|
import java.io.IOException
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
import kotlin.math.abs
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Playtube Jam: Verbindung zum Jam-Server und gemeinsamer Zustand fuer [JamActivity] (Anzeige)
|
* Playtube Jam: Verbindung zum Jam-Server und gemeinsamer Zustand fuer [JamActivity] (Anzeige)
|
||||||
@@ -104,9 +105,15 @@ object JamHub {
|
|||||||
val body = JSONObject().put("name", displayName).put("client", "android").toString()
|
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()
|
val request = Request.Builder().url("$server/api/jam").post(body.toRequestBody("application/json".toMediaType())).build()
|
||||||
http.newCall(request).enqueue(object : Callback {
|
http.newCall(request).enqueue(object : Callback {
|
||||||
override fun onFailure(call: Call, e: IOException) { main.post { setStatus(str(R.string.jam_status_failed)) } }
|
override fun onFailure(call: Call, e: IOException) {
|
||||||
|
Diagnostics.line("jam: Anlegen fehlgeschlagen: $e")
|
||||||
|
main.post { setStatus(str(R.string.jam_status_failed)) }
|
||||||
|
}
|
||||||
override fun onResponse(call: Call, response: Response) {
|
override fun onResponse(call: Call, response: Response) {
|
||||||
val text = response.use { if (it.isSuccessful) it.body?.string() else null }
|
val text = response.use {
|
||||||
|
if (!it.isSuccessful) Diagnostics.line("jam: Anlegen fehlgeschlagen: HTTP ${it.code}")
|
||||||
|
if (it.isSuccessful) it.body?.string() else null
|
||||||
|
}
|
||||||
main.post {
|
main.post {
|
||||||
val json = text?.let { runCatching { JSONObject(it) }.getOrNull() }
|
val json = text?.let { runCatching { JSONObject(it) }.getOrNull() }
|
||||||
if (json == null) {
|
if (json == null) {
|
||||||
@@ -134,9 +141,13 @@ object JamHub {
|
|||||||
setStatus(str(R.string.jam_status_joining))
|
setStatus(str(R.string.jam_status_joining))
|
||||||
val request = Request.Builder().url("$server/api/jam/$joinCode").build()
|
val request = Request.Builder().url("$server/api/jam/$joinCode").build()
|
||||||
http.newCall(request).enqueue(object : Callback {
|
http.newCall(request).enqueue(object : Callback {
|
||||||
override fun onFailure(call: Call, e: IOException) { main.post { setStatus(str(R.string.jam_status_failed)) } }
|
override fun onFailure(call: Call, e: IOException) {
|
||||||
|
Diagnostics.line("jam: Beitreten fehlgeschlagen: $e")
|
||||||
|
main.post { setStatus(str(R.string.jam_status_failed)) }
|
||||||
|
}
|
||||||
override fun onResponse(call: Call, response: Response) {
|
override fun onResponse(call: Call, response: Response) {
|
||||||
val status = response.use { it.code }
|
val status = response.use { it.code }
|
||||||
|
if (status != 200 && status != 404) Diagnostics.line("jam: Beitreten fehlgeschlagen: HTTP $status")
|
||||||
main.post {
|
main.post {
|
||||||
when (status) {
|
when (status) {
|
||||||
200 -> {
|
200 -> {
|
||||||
@@ -195,6 +206,7 @@ object JamHub {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||||
|
Diagnostics.line("jam: Verbindung fehlgeschlagen: $t")
|
||||||
main.post { if (socket === webSocket) lost() }
|
main.post { if (socket === webSocket) lost() }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,7 +252,10 @@ object JamHub {
|
|||||||
"ended" -> close(endedText(msg.optString("reason")), forget = true)
|
"ended" -> close(endedText(msg.optString("reason")), forget = true)
|
||||||
"error" -> when (val error = msg.optString("error")) {
|
"error" -> when (val error = msg.optString("error")) {
|
||||||
"not_found", "kicked", "full" -> close(endedText(error), forget = true)
|
"not_found", "kicked", "full" -> close(endedText(error), forget = true)
|
||||||
else -> setStatus(errorText(error))
|
else -> {
|
||||||
|
Diagnostics.line("jam: Server meldet Fehler $error")
|
||||||
|
setStatus(errorText(error))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -261,6 +276,8 @@ object JamHub {
|
|||||||
"not_allowed" -> str(R.string.jam_error_not_allowed)
|
"not_allowed" -> str(R.string.jam_error_not_allowed)
|
||||||
"queue_full" -> str(R.string.jam_error_queue_full)
|
"queue_full" -> str(R.string.jam_error_queue_full)
|
||||||
"bad_video" -> str(R.string.jam_error_bad_video)
|
"bad_video" -> str(R.string.jam_error_bad_video)
|
||||||
|
"offline" -> str(R.string.jam_error_offline)
|
||||||
|
"playlist_not_found" -> str(R.string.jam_error_playlist)
|
||||||
"rate_limited" -> str(R.string.jam_error_rate_limited)
|
"rate_limited" -> str(R.string.jam_error_rate_limited)
|
||||||
else -> str(R.string.jam_error_other, error)
|
else -> str(R.string.jam_error_other, error)
|
||||||
}
|
}
|
||||||
@@ -313,6 +330,11 @@ object JamHub {
|
|||||||
send(msg)
|
send(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Ganze Playlist / ganzes Album: der Jam-Server holt die Songs. */
|
||||||
|
fun addPlaylist(playlistId: String) {
|
||||||
|
send(JSONObject().put("t", "addPlaylist").put("playlistId", playlistId))
|
||||||
|
}
|
||||||
|
|
||||||
data class SearchResult(val videoId: String, val title: String, val artist: String, val thumb: String)
|
data class SearchResult(val videoId: String, val title: String, val artist: String, val thumb: String)
|
||||||
|
|
||||||
fun search(query: String, done: (List<SearchResult>?) -> Unit) {
|
fun search(query: String, done: (List<SearchResult>?) -> Unit) {
|
||||||
@@ -341,6 +363,8 @@ object JamHub {
|
|||||||
*/
|
*/
|
||||||
fun intercept(command: PlayerCommand): Boolean {
|
fun intercept(command: PlayerCommand): Boolean {
|
||||||
val s = state ?: return false
|
val s = state ?: return false
|
||||||
|
// Like gilt fuer den laufenden Song in der WebView (eigener Login) - nicht in den Jam umleiten.
|
||||||
|
if (command == PlayerCommand.Like) return false
|
||||||
if (!s.canControl) return true
|
if (!s.canControl) return true
|
||||||
when (command) {
|
when (command) {
|
||||||
PlayerCommand.PlayPause -> playPause()
|
PlayerCommand.PlayPause -> playPause()
|
||||||
@@ -348,6 +372,7 @@ object JamHub {
|
|||||||
PlayerCommand.Pause -> send("pause")
|
PlayerCommand.Pause -> send("pause")
|
||||||
PlayerCommand.Next -> send("skip")
|
PlayerCommand.Next -> send("skip")
|
||||||
PlayerCommand.Previous -> send("previous")
|
PlayerCommand.Previous -> send("previous")
|
||||||
|
PlayerCommand.Like -> return false
|
||||||
is PlayerCommand.SeekTo -> send("seek", "pos" to command.positionMs / 1000.0)
|
is PlayerCommand.SeekTo -> send("seek", "pos" to command.positionMs / 1000.0)
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
@@ -362,11 +387,15 @@ object JamHub {
|
|||||||
fun syncPlayer(probe: JSONObject): Actions {
|
fun syncPlayer(probe: JSONObject): Actions {
|
||||||
val s = state ?: return Actions(null, emptyList())
|
val s = state ?: return Actions(null, emptyList())
|
||||||
val now = SystemClock.elapsedRealtime()
|
val now = SystemClock.elapsedRealtime()
|
||||||
val want = JamSync.target(s, clock.serverNow(System.currentTimeMillis().toDouble()))
|
// Soll-Position zum Zeitpunkt der Messung in der Seite (nicht erst nach der Antwort).
|
||||||
|
val wall = System.currentTimeMillis().toDouble()
|
||||||
|
val sampled = probe.optDouble("now", wall).takeIf { it.isFinite() && abs(it - wall) < 5000 } ?: wall
|
||||||
|
val want = JamSync.target(s, clock.serverNow(sampled))
|
||||||
val local = JamSync.Local(
|
val local = JamSync.Local(
|
||||||
videoId = probe.optString("id").takeIf { it.isNotEmpty() && it != "null" && !probe.isNull("id") },
|
videoId = probe.optString("id").takeIf { it.isNotEmpty() && it != "null" && !probe.isNull("id") },
|
||||||
pos = probe.optDouble("t", 0.0),
|
pos = probe.optDouble("t", 0.0),
|
||||||
paused = probe.optBoolean("paused", true),
|
paused = probe.optBoolean("paused", true),
|
||||||
|
rate = probe.optDouble("rate", 1.0).takeIf { it.isFinite() && it > 0 } ?: 1.0,
|
||||||
)
|
)
|
||||||
val duration = probe.optDouble("d", 0.0)
|
val duration = probe.optDouble("d", 0.0)
|
||||||
val scripts = ArrayList<String>()
|
val scripts = ArrayList<String>()
|
||||||
@@ -457,6 +486,7 @@ object JamHub {
|
|||||||
expectUntil = now + 3000
|
expectUntil = now + 3000
|
||||||
scripts.add(pause)
|
scripts.add(pause)
|
||||||
}
|
}
|
||||||
|
is JamSync.Step.Rate -> scripts.add(JamSync.rateScript(step.rate))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Actions(load, scripts)
|
return Actions(load, scripts)
|
||||||
|
|||||||
@@ -13,7 +13,25 @@ import kotlin.math.max
|
|||||||
* paused ? position : position + (T - ref) / 1000. Negativ heisst "startet gleich".
|
* paused ? position : position + (T - ref) / 1000. Negativ heisst "startet gleich".
|
||||||
*/
|
*/
|
||||||
object JamSync {
|
object JamSync {
|
||||||
const val TOLERANCE_S = 1.5
|
const val TOLERANCE_S = 1.0
|
||||||
|
|
||||||
|
/** Beim Spulen etwas vorhalten: bis das Video an der neuen Stelle spielt, vergeht Zeit. */
|
||||||
|
const val SEEK_LEAD_S = 0.2
|
||||||
|
private const val NUDGE_START_S = 0.08
|
||||||
|
private const val NUDGE_STOP_S = 0.03
|
||||||
|
private const val NUDGE_GAIN = 0.25
|
||||||
|
private const val NUDGE_MAX = 0.08
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wiedergabetempo, das eine kleine Abweichung [drift] (eigene minus Jam-Position, s) ausgleicht -
|
||||||
|
* unhoerbar, die Tonhoehe bleibt. Einmal angefangen ([current] != 1) bis fast 0 ausgleichen.
|
||||||
|
*/
|
||||||
|
fun nudgeRate(drift: Double, current: Double): Double {
|
||||||
|
val threshold = if (abs(current - 1.0) > 0.001) NUDGE_STOP_S else NUDGE_START_S
|
||||||
|
if (!drift.isFinite() || abs(drift) < threshold) return 1.0
|
||||||
|
val rate = (1.0 - NUDGE_GAIN * drift).coerceIn(1.0 - NUDGE_MAX, 1.0 + NUDGE_MAX)
|
||||||
|
return Math.round(rate * 1000.0) / 1000.0
|
||||||
|
}
|
||||||
private const val CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
private const val CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
|
||||||
private val VIDEO_ID = Regex("^[A-Za-z0-9_-]{11}$")
|
private val VIDEO_ID = Regex("^[A-Za-z0-9_-]{11}$")
|
||||||
|
|
||||||
@@ -88,6 +106,28 @@ object JamSync {
|
|||||||
return id?.takeIf { VIDEO_ID.matches(it) }
|
return id?.takeIf { VIDEO_ID.matches(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val PLAYLIST_ID = Regex("^(PL|OLAK5uy_|RD|LL|UU|FL|OL|LM)[A-Za-z0-9_-]{0,80}$")
|
||||||
|
|
||||||
|
/** Playlist-/Album-ID aus einer ID oder einem Link mit `list=`, sonst null. */
|
||||||
|
fun parsePlaylistId(input: String?): String? {
|
||||||
|
val text = input?.trim() ?: return null
|
||||||
|
val raw = if (text.contains("youtube.com") || text.contains("youtu.be") || text.contains("://")) {
|
||||||
|
val rest = text.substringAfter("://", text)
|
||||||
|
val host = rest.substringBefore('/').lowercase().removePrefix("www.").removePrefix("m.").removePrefix("music.")
|
||||||
|
if (host != "youtube.com" && host != "youtu.be") return null
|
||||||
|
rest.substringAfter('?', "").substringBefore('#').split('&')
|
||||||
|
.firstOrNull { it.startsWith("list=") }?.removePrefix("list=") ?: return null
|
||||||
|
} else text
|
||||||
|
val id = raw.removePrefix("VL")
|
||||||
|
return id.takeIf { PLAYLIST_ID.matches(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Playlist-Link (ohne einzelnes Video) aus einem geteilten Text. */
|
||||||
|
fun playlistIdFromSharedText(text: String?): String? =
|
||||||
|
text?.split(Regex("\\s+"))?.firstNotNullOfOrNull { word ->
|
||||||
|
if (parseVideoId(word) == null) parsePlaylistId(word) else null
|
||||||
|
}
|
||||||
|
|
||||||
/** Sucht in einem geteilten Text (z. B. aus der YouTube-App) den ersten YouTube-Link. */
|
/** Sucht in einem geteilten Text (z. B. aus der YouTube-App) den ersten YouTube-Link. */
|
||||||
fun videoIdFromSharedText(text: String?): String? =
|
fun videoIdFromSharedText(text: String?): String? =
|
||||||
text?.split(Regex("\\s+"))?.firstNotNullOfOrNull { parseVideoId(it) }
|
text?.split(Regex("\\s+"))?.firstNotNullOfOrNull { parseVideoId(it) }
|
||||||
@@ -185,13 +225,14 @@ object JamSync {
|
|||||||
return Target(item.videoId, item.id, positionAt(state.playback, serverNow), state.playback.paused, item.dur)
|
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)
|
data class Local(val videoId: String?, val pos: Double, val paused: Boolean, val rate: Double = 1.0)
|
||||||
|
|
||||||
sealed class Step {
|
sealed class Step {
|
||||||
data class Load(val videoId: String, val pos: Double) : Step()
|
data class Load(val videoId: String, val pos: Double) : Step()
|
||||||
data class Seek(val pos: Double) : Step()
|
data class Seek(val pos: Double) : Step()
|
||||||
data object Play : Step()
|
data object Play : Step()
|
||||||
data object Pause : Step()
|
data object Pause : Step()
|
||||||
|
data class Rate(val rate: Double) : Step()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Was der eigene Player tun soll, damit er zum Jam passt. */
|
/** Was der eigene Player tun soll, damit er zum Jam passt. */
|
||||||
@@ -211,9 +252,14 @@ object JamSync {
|
|||||||
if (local.pos > 0.5) steps.add(Step.Seek(0.0))
|
if (local.pos > 0.5) steps.add(Step.Seek(0.0))
|
||||||
return steps
|
return steps
|
||||||
}
|
}
|
||||||
if (abs(local.pos - want.pos) > tolerance && !(nearEnd && local.pos > want.pos)) steps.add(Step.Seek(want.pos))
|
val drift = local.pos - want.pos
|
||||||
|
val seek = abs(drift) > tolerance && !(nearEnd && local.pos > want.pos)
|
||||||
|
if (seek) steps.add(Step.Seek(if (want.paused) want.pos else want.pos + SEEK_LEAD_S))
|
||||||
if (want.paused && !local.paused) steps.add(Step.Pause)
|
if (want.paused && !local.paused) steps.add(Step.Pause)
|
||||||
if (!want.paused && local.paused) steps.add(Step.Play)
|
if (!want.paused && local.paused) steps.add(Step.Play)
|
||||||
|
// Feinabgleich ueber das Tempo, solange beide normal laufen.
|
||||||
|
val desired = if (!seek && !want.paused && !local.paused && !nearEnd) nudgeRate(drift, local.rate) else 1.0
|
||||||
|
if (abs(desired - local.rate) > 0.004) steps.add(Step.Rate(desired))
|
||||||
return steps
|
return steps
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,6 +295,8 @@ object JamSync {
|
|||||||
d: api('getDuration') && player.getDuration() > 0 ? player.getDuration() : ((video && isFinite(video.duration)) ? video.duration : 0),
|
d: api('getDuration') && player.getDuration() > 0 ? player.getDuration() : ((video && isFinite(video.duration)) ? video.duration : 0),
|
||||||
paused: paused,
|
paused: paused,
|
||||||
ended: state === 0 || (video ? video.ended : false),
|
ended: state === 0 || (video ? video.ended : false),
|
||||||
|
rate: video && video.playbackRate > 0 ? video.playbackRate : 1,
|
||||||
|
now: Date.now(),
|
||||||
ad: ad,
|
ad: ad,
|
||||||
error: error,
|
error: error,
|
||||||
title: meta && meta.title ? meta.title : null,
|
title: meta && meta.title ? meta.title : null,
|
||||||
@@ -266,6 +314,14 @@ object JamSync {
|
|||||||
"var v=p&&p.querySelector('video')||document.querySelector('video');if(v){v.$prop();}})();"
|
"var v=p&&p.querySelector('video')||document.querySelector('video');if(v){v.$prop();}})();"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Wiedergabetempo des Players (Feinabgleich, Tonhoehe bleibt). */
|
||||||
|
fun rateScript(rate: Double): String {
|
||||||
|
val r = if (rate.isFinite()) rate.coerceIn(0.5, 2.0) else 1.0
|
||||||
|
return "(function(){var p=document.getElementById('movie_player');" +
|
||||||
|
"var v=p&&p.querySelector('video')||document.querySelector('video');" +
|
||||||
|
"if(v){v.preservesPitch=true;v.playbackRate=$r;}})();"
|
||||||
|
}
|
||||||
|
|
||||||
fun seekScript(seconds: Double): String {
|
fun seekScript(seconds: Double): String {
|
||||||
val s = if (seconds.isFinite()) max(0.0, seconds) else 0.0
|
val s = if (seconds.isFinite()) max(0.0, seconds) else 0.0
|
||||||
return "(function(){var p=document.getElementById('movie_player');var s=$s;" +
|
return "(function(){var p=document.getElementById('movie_player');var s=$s;" +
|
||||||
|
|||||||
@@ -10,7 +10,12 @@ import android.os.Build
|
|||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.Handler
|
import android.os.Handler
|
||||||
import android.os.Looper
|
import android.os.Looper
|
||||||
|
import android.os.SystemClock
|
||||||
import android.view.View
|
import android.view.View
|
||||||
|
import android.widget.CheckBox
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
import android.webkit.CookieManager
|
import android.webkit.CookieManager
|
||||||
import android.webkit.PermissionRequest
|
import android.webkit.PermissionRequest
|
||||||
import android.webkit.WebChromeClient
|
import android.webkit.WebChromeClient
|
||||||
@@ -53,18 +58,27 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Verlauf (auf dem Handy gehoerte Songs) und Schlaf-Timer
|
||||||
|
private lateinit var history: PlayHistory
|
||||||
|
private var sleepTimer: SleepTimer? = null
|
||||||
|
|
||||||
private val notificationPermission =
|
private val notificationPermission =
|
||||||
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* ohne Erlaubnis: nur keine Benachrichtigung */ }
|
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* ohne Erlaubnis: nur keine Benachrichtigung */ }
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
Diagnostics.init(this)
|
||||||
setContentView(R.layout.activity_main)
|
setContentView(R.layout.activity_main)
|
||||||
webView = findViewById(R.id.webView)
|
webView = findViewById(R.id.webView)
|
||||||
progress = findViewById(R.id.progress)
|
progress = findViewById(R.id.progress)
|
||||||
keepContentBetweenSystemBars()
|
keepContentBetweenSystemBars()
|
||||||
findViewById<View>(R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) }
|
findViewById<View>(R.id.pcRemoteButton).setOnClickListener { PcRemoteActivity.start(this) }
|
||||||
findViewById<View>(R.id.jamButton).setOnClickListener { JamActivity.start(this) }
|
findViewById<View>(R.id.jamButton).setOnClickListener { JamActivity.start(this) }
|
||||||
|
findViewById<View>(R.id.socialButton).setOnClickListener { SocialActivity.start(this) }
|
||||||
|
findViewById<View>(R.id.settingsButton).setOnClickListener { showMenu() }
|
||||||
|
history = PlayHistory.fromJson(runCatching { historyFile().readText() }.getOrNull())
|
||||||
JamHub.init(this)
|
JamHub.init(this)
|
||||||
|
SocialHub.init(this)
|
||||||
|
|
||||||
configureWebView()
|
configureWebView()
|
||||||
onBackPressedDispatcher.addCallback(
|
onBackPressedDispatcher.addCallback(
|
||||||
@@ -91,6 +105,9 @@ class MainActivity : AppCompatActivity() {
|
|||||||
handler.post(probeLoop)
|
handler.post(probeLoop)
|
||||||
handler.post(jamLoop)
|
handler.post(jamLoop)
|
||||||
checkForUpdate()
|
checkForUpdate()
|
||||||
|
showDiagnosticsNotice()
|
||||||
|
// Kurz nach dem Start: Absturz vom letzten Mal o. ä. senden (höchstens alle 6 Stunden).
|
||||||
|
handler.postDelayed({ Diagnostics.sendIfDue(this) }, DIAG_DELAY_MS)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
@@ -187,6 +204,9 @@ class MainActivity : AppCompatActivity() {
|
|||||||
// Fuer "Jam starten": der gerade laufende Song wird der erste im Jam.
|
// Fuer "Jam starten": der gerade laufende Song wird der erste im Jam.
|
||||||
val videoId = JamSync.parseVideoId(webView.url)
|
val videoId = JamSync.parseVideoId(webView.url)
|
||||||
JamHub.pageVideo = if (videoId != null && info.hasTrack) JamHub.PageVideo(videoId, info.title, info.artist) else null
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -227,6 +247,165 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}.start()
|
}.start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ Einstellungen / Diagnose
|
||||||
|
|
||||||
|
/** Einmaliger Hinweis: Diagnosedaten sind an (Opt-out) und lassen sich hier abschalten. */
|
||||||
|
private fun showDiagnosticsNotice() {
|
||||||
|
if (!Diagnostics.needsNotice(this)) return
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.diag_notice_title)
|
||||||
|
.setMessage(R.string.diag_notice_message)
|
||||||
|
.setPositiveButton(R.string.diag_notice_ok) { _, _ -> Diagnostics.noticeShown(this) }
|
||||||
|
.setNegativeButton(R.string.diag_notice_off) { _, _ ->
|
||||||
|
Diagnostics.setEnabled(this, false)
|
||||||
|
Diagnostics.noticeShown(this)
|
||||||
|
}
|
||||||
|
.setOnCancelListener { Diagnostics.noticeShown(this) }
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ Menue, Schlaf-Timer, Verlauf
|
||||||
|
|
||||||
|
/** Der kleine Knopf rechts: Schlaf-Timer, Verlauf, Einstellungen. */
|
||||||
|
private fun showMenu() {
|
||||||
|
val timer = sleepTimer
|
||||||
|
val sleepLabel = if (timer == null) getString(R.string.sleep_title)
|
||||||
|
else getString(R.string.sleep_title_active, sleepText(timer))
|
||||||
|
val items = arrayOf(sleepLabel, getString(R.string.history_title), getString(R.string.settings_open))
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.menu_title)
|
||||||
|
.setItems(items) { _, which ->
|
||||||
|
when (which) {
|
||||||
|
0 -> showSleepDialog()
|
||||||
|
1 -> showHistory()
|
||||||
|
else -> showSettings()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sleepText(timer: SleepTimer): String =
|
||||||
|
if (timer.endOfTrack) getString(R.string.sleep_end_short)
|
||||||
|
else SleepTimer.format(timer.remainingSeconds(SystemClock.elapsedRealtime()))
|
||||||
|
|
||||||
|
private fun showSleepDialog() {
|
||||||
|
val minutes = SleepTimer.CHOICES
|
||||||
|
val labels = minutes.map { getString(R.string.sleep_minutes, it) } +
|
||||||
|
getString(R.string.sleep_end) + getString(R.string.sleep_off)
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.sleep_title)
|
||||||
|
.setItems(labels.toTypedArray()) { _, which ->
|
||||||
|
when {
|
||||||
|
which < minutes.size -> setSleep(SleepTimer.minutes(minutes[which], SystemClock.elapsedRealtime()))
|
||||||
|
which == minutes.size -> setSleep(SleepTimer.endOfTrack(currentVideo()))
|
||||||
|
else -> setSleep(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun currentVideo(): String? =
|
||||||
|
JamSync.parseVideoId(webView.url)?.takeIf { PlaybackHub.nowPlaying.playing && PlaybackHub.nowPlaying.hasTrack }
|
||||||
|
|
||||||
|
private fun setSleep(timer: SleepTimer?) {
|
||||||
|
restoreVolume()
|
||||||
|
sleepTimer = timer
|
||||||
|
val text = if (timer == null) getString(R.string.sleep_cleared) else getString(R.string.sleep_set, sleepText(timer))
|
||||||
|
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bei jeder Abfrage der Seite (alle 1,5 s). */
|
||||||
|
private fun sleepTick(track: String?) {
|
||||||
|
val timer = sleepTimer ?: return
|
||||||
|
when (val step = timer.tick(SystemClock.elapsedRealtime(), track)) {
|
||||||
|
SleepTimer.Step.Wait -> Unit
|
||||||
|
is SleepTimer.Step.Fade -> webView.evaluateJavascript(
|
||||||
|
"(function(){var v=document.querySelector('video');if(!v)return;" +
|
||||||
|
"if(window.__ptSleepVol===undefined){window.__ptSleepVol=v.volume;}" +
|
||||||
|
"v.volume=Math.max(0,window.__ptSleepVol*${step.factor});})();",
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
SleepTimer.Step.Stop -> {
|
||||||
|
sleepTimer = null
|
||||||
|
// Im Jam nur fuer sich aufhoeren: den Jam verlassen statt ihn fuer alle anzuhalten.
|
||||||
|
if (JamHub.state != null) JamHub.leave()
|
||||||
|
webView.evaluateJavascript(MediaScripts.forCommand(PlayerCommand.Pause), null)
|
||||||
|
handler.postDelayed({ restoreVolume() }, 1500)
|
||||||
|
Diagnostics.line("sleep: Schlaf-Timer abgelaufen")
|
||||||
|
Toast.makeText(this, R.string.sleep_done, Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun restoreVolume() {
|
||||||
|
webView.evaluateJavascript(
|
||||||
|
"(function(){var v=document.querySelector('video');if(v&&window.__ptSleepVol!==undefined){" +
|
||||||
|
"v.volume=window.__ptSleepVol;}delete window.__ptSleepVol;})();",
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun historyFile() = java.io.File(filesDir, "history.json")
|
||||||
|
|
||||||
|
private fun saveHistory() {
|
||||||
|
val text = history.toJson()
|
||||||
|
Thread {
|
||||||
|
runCatching {
|
||||||
|
val tmp = java.io.File(filesDir, "history.json.tmp")
|
||||||
|
tmp.writeText(text)
|
||||||
|
tmp.renameTo(historyFile())
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showHistory() {
|
||||||
|
HistoryDialog.show(
|
||||||
|
this,
|
||||||
|
getString(R.string.history_title),
|
||||||
|
history.search(""),
|
||||||
|
onPick = { webView.loadUrl("$MUSIC_ORIGIN/watch?v=${it.videoId}") },
|
||||||
|
onClear = {
|
||||||
|
history.clear()
|
||||||
|
saveHistory()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showSettings() {
|
||||||
|
val pad = (20 * resources.displayMetrics.density).toInt()
|
||||||
|
val box = CheckBox(this).apply {
|
||||||
|
setText(R.string.diag_enabled)
|
||||||
|
isChecked = Diagnostics.isEnabled(this@MainActivity)
|
||||||
|
setOnCheckedChangeListener { _, checked -> Diagnostics.setEnabled(this@MainActivity, checked) }
|
||||||
|
}
|
||||||
|
val hint = TextView(this).apply {
|
||||||
|
text = getString(R.string.diag_hint) + "\n\n" + getString(R.string.diag_install_id, Diagnostics.installId(this@MainActivity))
|
||||||
|
setTextIsSelectable(true)
|
||||||
|
alpha = 0.75f
|
||||||
|
}
|
||||||
|
val content = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
setPadding(pad, pad / 2, pad, 0)
|
||||||
|
addView(box)
|
||||||
|
addView(hint)
|
||||||
|
}
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.settings_title)
|
||||||
|
.setView(content)
|
||||||
|
.setPositiveButton(R.string.diag_done, null)
|
||||||
|
.setNeutralButton(R.string.diag_send_now) { _, _ ->
|
||||||
|
Diagnostics.send(this, manual = true) { ok ->
|
||||||
|
val text = when (ok) {
|
||||||
|
null -> R.string.diag_nothing
|
||||||
|
true -> R.string.diag_sent
|
||||||
|
false -> R.string.diag_failed
|
||||||
|
}
|
||||||
|
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
private fun showUpdateDialog(release: UpdateChecker.Release) {
|
private fun showUpdateDialog(release: UpdateChecker.Release) {
|
||||||
val prefs = getSharedPreferences(PREFS, MODE_PRIVATE)
|
val prefs = getSharedPreferences(PREFS, MODE_PRIVATE)
|
||||||
if (prefs.getString(KEY_DISMISSED_UPDATE, null) == release.tag) return
|
if (prefs.getString(KEY_DISMISSED_UPDATE, null) == release.tag) return
|
||||||
@@ -251,6 +430,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
private const val HOME_URL = "https://music.youtube.com/"
|
private const val HOME_URL = "https://music.youtube.com/"
|
||||||
private const val PROBE_INTERVAL_MS = 1500L
|
private const val PROBE_INTERVAL_MS = 1500L
|
||||||
private const val JAM_INTERVAL_MS = 700L
|
private const val JAM_INTERVAL_MS = 700L
|
||||||
|
private const val DIAG_DELAY_MS = 30_000L
|
||||||
private const val PREFS = "playtube"
|
private const val PREFS = "playtube"
|
||||||
private const val KEY_DISMISSED_UPDATE = "dismissed_update"
|
private const val KEY_DISMISSED_UPDATE = "dismissed_update"
|
||||||
|
|
||||||
|
|||||||
@@ -62,13 +62,23 @@ object MediaScripts {
|
|||||||
var sliderOk = isFinite(now) && isFinite(max) && max > 0;
|
var sliderOk = isFinite(now) && isFinite(max) && max > 0;
|
||||||
var current = sliderOk ? now : (video ? video.currentTime : 0);
|
var current = sliderOk ? now : (video ? video.currentTime : 0);
|
||||||
var duration = sliderOk ? max : ((video && isFinite(video.duration)) ? video.duration : 0);
|
var duration = sliderOk ? max : ((video && isFinite(video.duration)) ? video.duration : 0);
|
||||||
|
var likeStatus = null;
|
||||||
|
try {
|
||||||
|
var renderer = document.querySelector('ytmusic-player-bar ytmusic-like-button-renderer');
|
||||||
|
likeStatus = renderer ? (renderer.getAttribute('like-status') || '').toLowerCase() : null;
|
||||||
|
if (!likeStatus) {
|
||||||
|
var pressed = document.querySelector('like-button-view-model button[aria-pressed=true], #segmented-like-button button[aria-pressed=true]');
|
||||||
|
if (pressed) likeStatus = 'like';
|
||||||
|
}
|
||||||
|
} catch (e) { likeStatus = null; }
|
||||||
return JSON.stringify({
|
return JSON.stringify({
|
||||||
title: title || '',
|
title: title || '',
|
||||||
artist: artist || '',
|
artist: artist || '',
|
||||||
artwork: artwork,
|
artwork: artwork,
|
||||||
playing: !!video && !video.paused && !video.ended && video.readyState > 2,
|
playing: !!video && !video.paused && !video.ended && video.readyState > 2,
|
||||||
currentTime: current || 0,
|
currentTime: current || 0,
|
||||||
duration: duration || 0
|
duration: duration || 0,
|
||||||
|
likeStatus: likeStatus
|
||||||
});
|
});
|
||||||
})();
|
})();
|
||||||
"""
|
"""
|
||||||
@@ -85,6 +95,8 @@ object MediaScripts {
|
|||||||
action("nexttrack", "['ytmusic-player-bar .next-button','.next-button']")
|
action("nexttrack", "['ytmusic-player-bar .next-button','.next-button']")
|
||||||
PlayerCommand.Previous ->
|
PlayerCommand.Previous ->
|
||||||
action("previoustrack", "['ytmusic-player-bar .previous-button','.previous-button']")
|
action("previoustrack", "['ytmusic-player-bar .previous-button','.previous-button']")
|
||||||
|
PlayerCommand.Like ->
|
||||||
|
action("like", "['ytmusic-player-bar ytmusic-like-button-renderer #button-shape-like button','like-button-view-model button','#segmented-like-button button']")
|
||||||
is PlayerCommand.SeekTo -> {
|
is PlayerCommand.SeekTo -> {
|
||||||
val seconds = command.positionMs / 1000.0
|
val seconds = command.positionMs / 1000.0
|
||||||
"(function(){var v=document.querySelector('video');if(v){v.currentTime=$seconds;}})();"
|
"(function(){var v=document.querySelector('video');if(v){v.currentTime=$seconds;}})();"
|
||||||
|
|||||||
@@ -11,11 +11,12 @@ data class NowPlaying(
|
|||||||
val playing: Boolean,
|
val playing: Boolean,
|
||||||
val positionMs: Long,
|
val positionMs: Long,
|
||||||
val durationMs: Long,
|
val durationMs: Long,
|
||||||
|
val likeStatus: String? = null,
|
||||||
) {
|
) {
|
||||||
val hasTrack: Boolean get() = title.isNotBlank()
|
val hasTrack: Boolean get() = title.isNotBlank()
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val EMPTY = NowPlaying("", "", null, playing = false, positionMs = 0L, durationMs = 0L)
|
val EMPTY = NowPlaying("", "", null, playing = false, positionMs = 0L, durationMs = 0L, likeStatus = null)
|
||||||
|
|
||||||
private const val ARTIST_SEPARATOR = " • "
|
private const val ARTIST_SEPARATOR = " • "
|
||||||
|
|
||||||
@@ -34,6 +35,7 @@ data class NowPlaying(
|
|||||||
playing = json.optBoolean("playing", false),
|
playing = json.optBoolean("playing", false),
|
||||||
positionMs = seconds(json.optDouble("currentTime", 0.0)),
|
positionMs = seconds(json.optDouble("currentTime", 0.0)),
|
||||||
durationMs = seconds(json.optDouble("duration", 0.0)),
|
durationMs = seconds(json.optDouble("duration", 0.0)),
|
||||||
|
likeStatus = json.optString("likeStatus").takeIf { it.isNotBlank() && it != "null" },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,6 +39,8 @@ data class PcState(
|
|||||||
val liked: Boolean,
|
val liked: Boolean,
|
||||||
/** "NONE", "ALL" oder "ONE" (leer = unbekannt). */
|
/** "NONE", "ALL" oder "ONE" (leer = unbekannt). */
|
||||||
val repeatMode: String = "",
|
val repeatMode: String = "",
|
||||||
|
/** Schlaf-Timer am PC: Restsekunden, -1 = Songende, null = aus (oder Playtube zu alt). */
|
||||||
|
val sleepTimer: Long? = null,
|
||||||
) {
|
) {
|
||||||
companion object {
|
companion object {
|
||||||
val EMPTY = PcState("music", "music", "", "", "", false, 0.0, 0.0, 100, false)
|
val EMPTY = PcState("music", "music", "", "", "", false, 0.0, 0.0, 100, false)
|
||||||
@@ -82,6 +84,7 @@ object PcRemote {
|
|||||||
volume = (tab?.optDouble("volume")?.takeIf { it.isFinite() } ?: 100.0).toInt().coerceIn(0, 100),
|
volume = (tab?.optDouble("volume")?.takeIf { it.isFinite() } ?: 100.0).toInt().coerceIn(0, 100),
|
||||||
liked = tab?.optString("likeStatus").equals("LIKE", ignoreCase = true),
|
liked = tab?.optString("likeStatus").equals("LIKE", ignoreCase = true),
|
||||||
repeatMode = tab.text("repeatMode").uppercase(),
|
repeatMode = tab.text("repeatMode").uppercase(),
|
||||||
|
sleepTimer = if (state.isNull("sleepTimer")) null else state.optLong("sleepTimer", Long.MIN_VALUE).takeIf { it >= -1 },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -143,6 +143,9 @@ class PcRemoteActivity : AppCompatActivity(), PcSession.Listener {
|
|||||||
findViewById<ImageButton>(R.id.listBack).setOnClickListener { closeList() }
|
findViewById<ImageButton>(R.id.listBack).setOnClickListener { closeList() }
|
||||||
findViewById<Button>(R.id.queueButton).setOnClickListener { openList(ListMode.QUEUE) }
|
findViewById<Button>(R.id.queueButton).setOnClickListener { openList(ListMode.QUEUE) }
|
||||||
findViewById<Button>(R.id.playlistsButton).setOnClickListener { openList(ListMode.PLAYLISTS) }
|
findViewById<Button>(R.id.playlistsButton).setOnClickListener { openList(ListMode.PLAYLISTS) }
|
||||||
|
sleepButton = findViewById(R.id.sleepButton)
|
||||||
|
sleepButton.setOnClickListener { showPcSleepDialog() }
|
||||||
|
findViewById<Button>(R.id.historyButton).setOnClickListener { showPcHistory() }
|
||||||
|
|
||||||
findViewById<ImageButton>(R.id.previousButton).setOnClickListener { PcSession.send("previous") }
|
findViewById<ImageButton>(R.id.previousButton).setOnClickListener { PcSession.send("previous") }
|
||||||
findViewById<ImageButton>(R.id.nextButton).setOnClickListener { PcSession.send("next") }
|
findViewById<ImageButton>(R.id.nextButton).setOnClickListener { PcSession.send("next") }
|
||||||
@@ -413,6 +416,7 @@ class PcRemoteActivity : AppCompatActivity(), PcSession.Listener {
|
|||||||
findViewById<ImageButton>(R.id.shuffleButton).imageTintList = tint(R.color.text_muted)
|
findViewById<ImageButton>(R.id.shuffleButton).imageTintList = tint(R.color.text_muted)
|
||||||
tabYoutube.alpha = if (state.visibleTab == "youtube") 1f else 0.45f
|
tabYoutube.alpha = if (state.visibleTab == "youtube") 1f else 0.45f
|
||||||
tabMusic.alpha = if (state.visibleTab == "music") 1f else 0.45f
|
tabMusic.alpha = if (state.visibleTab == "music") 1f else 0.45f
|
||||||
|
renderSleep(state.sleepTimer)
|
||||||
|
|
||||||
if (state.thumbnail != coverUrl) loadCover(state.thumbnail)
|
if (state.thumbnail != coverUrl) loadCover(state.thumbnail)
|
||||||
}
|
}
|
||||||
@@ -469,6 +473,57 @@ class PcRemoteActivity : AppCompatActivity(), PcSession.Listener {
|
|||||||
loadList(mode, scrollToCurrent = true)
|
loadList(mode, scrollToCurrent = true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ Schlaf-Timer und Verlauf am PC
|
||||||
|
|
||||||
|
private lateinit var sleepButton: Button
|
||||||
|
|
||||||
|
private fun renderSleep(seconds: Long?) {
|
||||||
|
sleepButton.text = when (seconds) {
|
||||||
|
null -> getString(R.string.pc_sleep)
|
||||||
|
-1L -> getString(R.string.sleep_end_short)
|
||||||
|
else -> SleepTimer.format(seconds)
|
||||||
|
}
|
||||||
|
sleepButton.compoundDrawableTintList = tint(if (seconds != null) R.color.brand_to else R.color.text)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showPcSleepDialog() {
|
||||||
|
val minutes = SleepTimer.CHOICES
|
||||||
|
val labels = minutes.map { getString(R.string.sleep_minutes, it) } +
|
||||||
|
getString(R.string.sleep_end) + getString(R.string.sleep_off)
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle(R.string.sleep_title)
|
||||||
|
.setItems(labels.toTypedArray()) { _, which ->
|
||||||
|
val value = when {
|
||||||
|
which < minutes.size -> minutes[which]
|
||||||
|
which == minutes.size -> -1
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
PcSession.request("sleep_timer", { put("value", value) }) { result ->
|
||||||
|
result.onFailure { error ->
|
||||||
|
val text = if (PcRemote.isUnknownCommand(error.message)) getString(R.string.pc_too_old)
|
||||||
|
else error.message ?: error.javaClass.simpleName
|
||||||
|
android.widget.Toast.makeText(this, text, android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showPcHistory() {
|
||||||
|
PcSession.request("history", { put("value", 200) }) { result ->
|
||||||
|
if (isDestroyed) return@request
|
||||||
|
result.onSuccess { reply ->
|
||||||
|
HistoryDialog.show(this, getString(R.string.history_pc_title), PlayHistory.parsePcHistory(reply), onPick = { entry ->
|
||||||
|
PcSession.request("play_video", { put("video", entry.videoId) })
|
||||||
|
})
|
||||||
|
}.onFailure { error ->
|
||||||
|
val text = if (PcRemote.isUnknownCommand(error.message)) getString(R.string.pc_too_old)
|
||||||
|
else error.message ?: error.javaClass.simpleName
|
||||||
|
android.widget.Toast.makeText(this, text, android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun closeList() {
|
private fun closeList() {
|
||||||
listMode = null
|
listMode = null
|
||||||
listPanel.visibility = View.GONE
|
listPanel.visibility = View.GONE
|
||||||
|
|||||||
@@ -134,6 +134,7 @@ object PcSession {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
|
Diagnostics.line("pc: Verbinden fehlgeschlagen: $e")
|
||||||
main.post {
|
main.post {
|
||||||
if (gen != generation) return@post
|
if (gen != generation) return@post
|
||||||
reset()
|
reset()
|
||||||
@@ -293,6 +294,7 @@ object PcSession {
|
|||||||
} catch (e: PcRemote.RemoteException) {
|
} catch (e: PcRemote.RemoteException) {
|
||||||
main.post { done(Result.failure(e)) } // Befehl abgelehnt - Verbindung bleibt
|
main.post { done(Result.failure(e)) } // Befehl abgelehnt - Verbindung bleibt
|
||||||
} catch (e: IOException) {
|
} catch (e: IOException) {
|
||||||
|
Diagnostics.line("pc: Verbindung verloren: $e")
|
||||||
closeConnection()
|
closeConnection()
|
||||||
main.post {
|
main.post {
|
||||||
if (gen == generation) onConnectionLost()
|
if (gen == generation) onConnectionLost()
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package de.fojadrachi.playtube
|
||||||
|
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/** Ein gehoerter Song. */
|
||||||
|
data class HistoryEntry(
|
||||||
|
val videoId: String,
|
||||||
|
val title: String,
|
||||||
|
val artist: String,
|
||||||
|
val artwork: String?,
|
||||||
|
/** Beginn (Unix-Millisekunden) */
|
||||||
|
val playedAt: Long,
|
||||||
|
/** Gehoerte Sekunden */
|
||||||
|
val listened: Int,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verlauf der auf dem Handy gehoerten Songs. Ein Song zaehlt nach 30 s (bei kuerzeren Songs nach der
|
||||||
|
* Haelfte) - wie am PC (playtube-desktop/src/history.rs). Reine Logik; gespeichert wird ueber [toJson].
|
||||||
|
*/
|
||||||
|
class PlayHistory(entries: List<HistoryEntry> = emptyList()) {
|
||||||
|
private val list = ArrayList(entries)
|
||||||
|
val entries: List<HistoryEntry> get() = list
|
||||||
|
|
||||||
|
private var currentId: String? = null
|
||||||
|
private var current: HistoryEntry? = null
|
||||||
|
private var currentDurationS = 0.0
|
||||||
|
private var listenedS = 0.0
|
||||||
|
private var storedIndex = -1
|
||||||
|
/** Hoerdauer geaendert, aber noch nicht gespeichert */
|
||||||
|
private var dirty = false
|
||||||
|
private var lastTickMs: Long? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Neuer Stand aus der Seite. [videoId] = null oder [playing] = false: gerade laeuft nichts.
|
||||||
|
* Gibt true zurueck, wenn sich die gespeicherte Liste geaendert hat (dann speichern).
|
||||||
|
*/
|
||||||
|
fun observe(videoId: String?, info: NowPlaying, playing: Boolean, nowMs: Long, wallMs: Long): Boolean {
|
||||||
|
val step = lastTickMs?.let { ((nowMs - it).coerceAtLeast(0) / 1000.0).coerceAtMost(MAX_STEP_S) } ?: 0.0
|
||||||
|
lastTickMs = nowMs
|
||||||
|
if (videoId == null || !playing || !info.hasTrack) return finish()
|
||||||
|
|
||||||
|
if (videoId != currentId) {
|
||||||
|
val changed = finish()
|
||||||
|
currentId = videoId
|
||||||
|
current = HistoryEntry(videoId, info.title, info.artist, info.artworkUrl, wallMs, 0)
|
||||||
|
currentDurationS = info.durationMs / 1000.0
|
||||||
|
listenedS = 0.0
|
||||||
|
storedIndex = -1
|
||||||
|
return changed // der erste Takt eines neuen Songs zaehlt noch nicht
|
||||||
|
}
|
||||||
|
listenedS += step
|
||||||
|
if (info.durationMs > 0) currentDurationS = info.durationMs / 1000.0
|
||||||
|
val needed = if (currentDurationS > 0) minOf(COUNT_AFTER_S, currentDurationS / 2) else COUNT_AFTER_S
|
||||||
|
val entry = current ?: return false
|
||||||
|
if (storedIndex < 0 && listenedS >= needed) {
|
||||||
|
list += entry.copy(listened = listenedS.toInt())
|
||||||
|
while (list.size > MAX_ENTRIES) list.removeAt(0)
|
||||||
|
storedIndex = list.size - 1
|
||||||
|
dirty = false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if (storedIndex in list.indices && list[storedIndex].listened != listenedS.toInt()) {
|
||||||
|
list[storedIndex] = list[storedIndex].copy(listened = listenedS.toInt())
|
||||||
|
dirty = true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pause/Ende: gezaehlte Hoerdauer festhalten (true = speichern). */
|
||||||
|
private fun finish(): Boolean {
|
||||||
|
val save = dirty
|
||||||
|
dirty = false
|
||||||
|
return save
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Neueste zuerst, optional nach Titel/Interpret gefiltert. */
|
||||||
|
fun search(query: String, limit: Int = 300): List<HistoryEntry> {
|
||||||
|
val q = query.trim().lowercase()
|
||||||
|
return list.asReversed().asSequence()
|
||||||
|
.filter { q.isEmpty() || it.title.lowercase().contains(q) || it.artist.lowercase().contains(q) }
|
||||||
|
.take(limit)
|
||||||
|
.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun clear() {
|
||||||
|
list.clear()
|
||||||
|
currentId = null
|
||||||
|
current = null
|
||||||
|
storedIndex = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toJson(): String {
|
||||||
|
val array = JSONArray()
|
||||||
|
for (e in list) {
|
||||||
|
array.put(JSONObject().apply {
|
||||||
|
put("videoId", e.videoId)
|
||||||
|
put("title", e.title)
|
||||||
|
put("artist", e.artist)
|
||||||
|
e.artwork?.let { put("artwork", it) }
|
||||||
|
put("playedAt", e.playedAt)
|
||||||
|
put("listened", e.listened)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return array.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val MAX_ENTRIES = 3000
|
||||||
|
private const val COUNT_AFTER_S = 30.0
|
||||||
|
private const val MAX_STEP_S = 10.0
|
||||||
|
|
||||||
|
fun fromJson(text: String?): PlayHistory {
|
||||||
|
if (text.isNullOrBlank()) return PlayHistory()
|
||||||
|
val array = runCatching { JSONArray(text) }.getOrNull() ?: return PlayHistory()
|
||||||
|
val entries = ArrayList<HistoryEntry>()
|
||||||
|
for (i in 0 until array.length()) {
|
||||||
|
val o = array.optJSONObject(i) ?: continue
|
||||||
|
val id = o.optString("videoId")
|
||||||
|
if (id.isBlank()) continue
|
||||||
|
entries += HistoryEntry(
|
||||||
|
videoId = id,
|
||||||
|
title = o.optString("title"),
|
||||||
|
artist = o.optString("artist"),
|
||||||
|
artwork = o.optString("artwork").takeIf { it.startsWith("https://") },
|
||||||
|
playedAt = o.optLong("playedAt"),
|
||||||
|
listened = o.optInt("listened"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return PlayHistory(entries)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PC-Verlauf ("history"-Antwort der Fernsteuerung, playedAt in Sekunden). */
|
||||||
|
fun parsePcHistory(reply: JSONObject): List<HistoryEntry> {
|
||||||
|
val array = reply.optJSONArray("history") ?: return emptyList()
|
||||||
|
val entries = ArrayList<HistoryEntry>()
|
||||||
|
for (i in 0 until array.length()) {
|
||||||
|
val o = array.optJSONObject(i) ?: continue
|
||||||
|
val id = o.optString("videoId")
|
||||||
|
if (id.isBlank() || !id.all { it.isLetterOrDigit() || it == '_' || it == '-' }) continue
|
||||||
|
entries += HistoryEntry(
|
||||||
|
videoId = id,
|
||||||
|
title = o.optString("title").take(150),
|
||||||
|
artist = o.optString("artist").take(150),
|
||||||
|
artwork = o.optString("thumbnail").takeIf { it.startsWith("https://") },
|
||||||
|
playedAt = o.optLong("playedAt") * 1000,
|
||||||
|
listened = o.optInt("listened"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return entries
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ sealed class PlayerCommand {
|
|||||||
data object Pause : PlayerCommand()
|
data object Pause : PlayerCommand()
|
||||||
data object Next : PlayerCommand()
|
data object Next : PlayerCommand()
|
||||||
data object Previous : PlayerCommand()
|
data object Previous : PlayerCommand()
|
||||||
|
data object Like : PlayerCommand()
|
||||||
data class SeekTo(val positionMs: Long) : PlayerCommand()
|
data class SeekTo(val positionMs: Long) : PlayerCommand()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package de.fojadrachi.playtube
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schlaf-Timer: nach X Minuten (mit sanftem Ausblenden in den letzten 15 s) oder am Ende des
|
||||||
|
* laufenden Songs pausieren. Reine Logik ohne Android - die Activity ruft [tick] regelmaessig auf.
|
||||||
|
* Gleiches Verhalten wie am PC (playtube-desktop/src/sleep.rs).
|
||||||
|
*/
|
||||||
|
class SleepTimer private constructor(
|
||||||
|
/** Zeitpunkt (elapsedRealtime) zum Pausieren; null = am Songende. */
|
||||||
|
private val deadlineMs: Long?,
|
||||||
|
/** Song, nach dem pausiert wird (nur bei Songende); null = noch nichts gemerkt. */
|
||||||
|
private var track: String?,
|
||||||
|
) {
|
||||||
|
sealed class Step {
|
||||||
|
data object Wait : Step()
|
||||||
|
/** Lautstaerke auf diesen Anteil (0..1) der urspruenglichen setzen. */
|
||||||
|
data class Fade(val factor: Double) : Step()
|
||||||
|
data object Stop : Step()
|
||||||
|
}
|
||||||
|
|
||||||
|
val endOfTrack: Boolean get() = deadlineMs == null
|
||||||
|
|
||||||
|
/** Restzeit in Sekunden; -1 = bis zum Songende. */
|
||||||
|
fun remainingSeconds(nowMs: Long): Long =
|
||||||
|
if (deadlineMs == null) -1 else ((deadlineMs - nowMs).coerceAtLeast(0) + 999) / 1000
|
||||||
|
|
||||||
|
fun tick(nowMs: Long, currentTrack: String?): Step {
|
||||||
|
if (deadlineMs == null) {
|
||||||
|
val remembered = track
|
||||||
|
return when {
|
||||||
|
currentTrack == null -> Step.Wait // kurze Ladepause zaehlt nicht
|
||||||
|
remembered == null -> {
|
||||||
|
track = currentTrack
|
||||||
|
Step.Wait
|
||||||
|
}
|
||||||
|
remembered != currentTrack -> Step.Stop
|
||||||
|
else -> Step.Wait
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val left = deadlineMs - nowMs
|
||||||
|
return when {
|
||||||
|
left <= 0 -> Step.Stop
|
||||||
|
left <= FADE_MS -> Step.Fade(left.toDouble() / FADE_MS)
|
||||||
|
else -> Step.Wait
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val FADE_MS = 15_000L
|
||||||
|
/** Auswahl im Dialog (Minuten). */
|
||||||
|
val CHOICES = listOf(15, 30, 45, 60, 90, 120)
|
||||||
|
const val MAX_MINUTES = 24 * 60
|
||||||
|
|
||||||
|
fun minutes(minutes: Int, nowMs: Long): SleepTimer =
|
||||||
|
SleepTimer(nowMs + minutes.coerceIn(1, MAX_MINUTES) * 60_000L, null)
|
||||||
|
|
||||||
|
fun endOfTrack(currentTrack: String?): SleepTimer = SleepTimer(null, currentTrack)
|
||||||
|
|
||||||
|
/** "12:34" bzw. "1:02:03". */
|
||||||
|
fun format(seconds: Long): String {
|
||||||
|
val s = seconds.coerceAtLeast(0)
|
||||||
|
val h = s / 3600
|
||||||
|
val m = (s % 3600) / 60
|
||||||
|
val sec = s % 60
|
||||||
|
return if (h > 0) "%d:%02d:%02d".format(h, m, sec) else "%d:%02d".format(m, sec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<SocialLogic.Person> = 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<View>(button(getString(R.string.social_add)) { SocialHub.friendAction("request", p.id) { e -> if (e == null) refreshResult(p, "outgoing") } })
|
||||||
|
"incoming" -> arrayOf<View>(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))) }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Pair<SocialLogic.Invite, Long>>()
|
||||||
|
/** Freunde, die eingeladen werden, sobald der eigene Sync laeuft */
|
||||||
|
private val pendingInvites = LinkedHashSet<String>()
|
||||||
|
/** Schon in den Sync mit diesem Code eingeladen */
|
||||||
|
private var invitedCode: String? = null
|
||||||
|
val invited = HashSet<String>()
|
||||||
|
/** 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<SocialLogic.Invite> {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Friend>, val incoming: List<Person>, val outgoing: List<Person>) {
|
||||||
|
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<Person> =
|
||||||
|
(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<Person> = 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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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="M12.34,2.02C6.59,1.82 2,6.42 2,12c0,5.52 4.48,10 10,10 3.71,0 6.93,-2.02 8.66,-5.02C13.15,16.73 8.57,8.55 12.34,2.02z" />
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Krone: "Zum Host machen" in der Teilnehmerliste des Jams -->
|
||||||
|
<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="M5,16L3,5l5.5,5L12,4l3.5,6L21,5l-2,11H5zM19,19c0,0.6 -0.4,1 -1,1H6c-0.6,0 -1,-0.4 -1,-1v-1h14v1z" />
|
||||||
|
</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="#FFFFFFFF"
|
||||||
|
android:pathData="M13,3c-4.97,0 -9,4.03 -9,9L1,12l3.89,3.89 0.07,0.14L9,12L6,12c0,-3.87 3.13,-7 7,-7s7,3.13 7,7 -3.13,7 -7,7c-1.93,0 -3.68,-0.79 -4.94,-2.06l-1.42,1.42C8.27,19.99 10.51,21 13,21c4.97,0 9,-4.03 9,-9s-4.03,-9 -9,-9zM12,8v5l4.28,2.54 0.72,-1.21 -3.5,-2.08L13.5,8L12,8z" />
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Sozial: Person mit Plus (Material "person_add") -->
|
||||||
|
<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="M15,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM6,10L6,7L4,7v3L1,10v2h3v3h2v-3h3v-2L6,10zM15,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z" />
|
||||||
|
</vector>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<!-- Einstellungen (Material "settings") -->
|
||||||
|
<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.14,12.94c0.04,-0.3 0.06,-0.61 0.06,-0.94c0,-0.32 -0.02,-0.64 -0.07,-0.94l2.03,-1.58c0.18,-0.14 0.23,-0.41 0.12,-0.61l-1.92,-3.32c-0.12,-0.22 -0.37,-0.29 -0.59,-0.22l-2.39,0.96c-0.5,-0.38 -1.03,-0.7 -1.62,-0.94L14.4,2.81c-0.04,-0.24 -0.24,-0.41 -0.48,-0.41h-3.84c-0.24,0 -0.43,0.17 -0.47,0.41L9.25,5.35C8.66,5.59 8.12,5.92 7.63,6.29L5.24,5.33c-0.22,-0.08 -0.47,0 -0.59,0.22L2.74,8.87C2.62,9.08 2.66,9.34 2.86,9.48l2.03,1.58C4.84,11.36 4.8,11.69 4.8,12s0.02,0.64 0.07,0.94l-2.03,1.58c-0.18,0.14 -0.23,0.41 -0.12,0.61l1.92,3.32c0.12,0.22 0.37,0.29 0.59,0.22l2.39,-0.96c0.5,0.38 1.03,0.7 1.62,0.94l0.36,2.54c0.05,0.24 0.24,0.41 0.48,0.41h3.84c0.24,0 0.44,-0.17 0.47,-0.41l0.36,-2.54c0.59,-0.24 1.13,-0.56 1.62,-0.94l2.39,0.96c0.22,0.08 0.47,0 0.59,-0.22l1.92,-3.32c0.12,-0.22 0.07,-0.47 -0.12,-0.61L19.14,12.94zM12,15.6c-1.98,0 -3.6,-1.62 -3.6,-3.6s1.62,-3.6 3.6,-3.6s3.6,1.62 3.6,3.6S13.98,15.6 12,15.6z" />
|
||||||
|
</vector>
|
||||||
@@ -207,6 +207,15 @@
|
|||||||
android:textColor="@color/text_muted"
|
android:textColor="@color/text_muted"
|
||||||
android:textSize="14sp" />
|
android:textSize="14sp" />
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/jamNowLike"
|
||||||
|
android:layout_width="44dp"
|
||||||
|
android:layout_height="44dp"
|
||||||
|
android:background="?attr/selectableItemBackgroundBorderless"
|
||||||
|
android:contentDescription="@string/jam_like"
|
||||||
|
android:src="@drawable/ic_favorite_border"
|
||||||
|
android:tint="@color/brand_to" />
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|
||||||
<TextView
|
<TextView
|
||||||
@@ -383,6 +392,7 @@
|
|||||||
<TextView
|
<TextView
|
||||||
android:id="@+id/jamInviteCode"
|
android:id="@+id/jamInviteCode"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
|
android:gravity="center"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
android:layout_marginTop="4dp"
|
android:layout_marginTop="4dp"
|
||||||
android:letterSpacing="0.1"
|
android:letterSpacing="0.1"
|
||||||
@@ -393,6 +403,7 @@
|
|||||||
<TextView
|
<TextView
|
||||||
android:id="@+id/jamInviteLink"
|
android:id="@+id/jamInviteLink"
|
||||||
android:layout_width="match_parent"
|
android:layout_width="match_parent"
|
||||||
|
android:gravity="center"
|
||||||
android:layout_height="wrap_content"
|
android:layout_height="wrap_content"
|
||||||
android:textColor="@color/text_muted"
|
android:textColor="@color/text_muted"
|
||||||
android:textIsSelectable="true"
|
android:textIsSelectable="true"
|
||||||
|
|||||||
@@ -49,4 +49,34 @@
|
|||||||
android:padding="10dp"
|
android:padding="10dp"
|
||||||
android:scaleType="fitCenter"
|
android:scaleType="fitCenter"
|
||||||
android:src="@drawable/ic_jam" />
|
android:src="@drawable/ic_jam" />
|
||||||
|
|
||||||
|
<!-- Sozial (SocialActivity): unter dem Sync-Knopf. -->
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/socialButton"
|
||||||
|
android:layout_width="44dp"
|
||||||
|
android:layout_height="44dp"
|
||||||
|
android:layout_gravity="end|center_vertical"
|
||||||
|
android:layout_marginTop="112dp"
|
||||||
|
android:layout_marginEnd="6dp"
|
||||||
|
android:alpha="0.85"
|
||||||
|
android:background="@drawable/bg_play_button"
|
||||||
|
android:contentDescription="@string/social_open"
|
||||||
|
android:padding="10dp"
|
||||||
|
android:scaleType="fitCenter"
|
||||||
|
android:src="@drawable/ic_people" />
|
||||||
|
|
||||||
|
<!-- Einstellungen (Diagnosedaten): unter dem Sozial-Knopf, etwas kleiner. -->
|
||||||
|
<ImageButton
|
||||||
|
android:id="@+id/settingsButton"
|
||||||
|
android:layout_width="36dp"
|
||||||
|
android:layout_height="36dp"
|
||||||
|
android:layout_gravity="end|center_vertical"
|
||||||
|
android:layout_marginTop="164dp"
|
||||||
|
android:layout_marginEnd="10dp"
|
||||||
|
android:alpha="0.7"
|
||||||
|
android:background="@drawable/bg_play_button"
|
||||||
|
android:contentDescription="@string/settings_open"
|
||||||
|
android:padding="8dp"
|
||||||
|
android:scaleType="fitCenter"
|
||||||
|
android:src="@drawable/ic_settings" />
|
||||||
</FrameLayout>
|
</FrameLayout>
|
||||||
|
|||||||
@@ -401,6 +401,48 @@
|
|||||||
android:textColor="@color/text"
|
android:textColor="@color/text"
|
||||||
android:textSize="14sp" />
|
android:textSize="14sp" />
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|
||||||
|
<LinearLayout
|
||||||
|
android:layout_width="match_parent"
|
||||||
|
android:layout_height="wrap_content"
|
||||||
|
android:layout_marginTop="10dp"
|
||||||
|
android:orientation="horizontal">
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/sleepButton"
|
||||||
|
style="?android:attr/borderlessButtonStyle"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="44dp"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:background="@drawable/bg_pill"
|
||||||
|
android:drawableStart="@drawable/ic_bedtime"
|
||||||
|
android:drawablePadding="8dp"
|
||||||
|
android:drawableTint="@color/text"
|
||||||
|
android:paddingStart="16dp"
|
||||||
|
android:paddingEnd="16dp"
|
||||||
|
android:text="@string/pc_sleep"
|
||||||
|
android:textAllCaps="false"
|
||||||
|
android:textColor="@color/text"
|
||||||
|
android:textSize="14sp" />
|
||||||
|
|
||||||
|
<Button
|
||||||
|
android:id="@+id/historyButton"
|
||||||
|
style="?android:attr/borderlessButtonStyle"
|
||||||
|
android:layout_width="0dp"
|
||||||
|
android:layout_height="44dp"
|
||||||
|
android:layout_marginStart="12dp"
|
||||||
|
android:layout_weight="1"
|
||||||
|
android:background="@drawable/bg_pill"
|
||||||
|
android:drawableStart="@drawable/ic_history"
|
||||||
|
android:drawablePadding="8dp"
|
||||||
|
android:drawableTint="@color/text"
|
||||||
|
android:paddingStart="16dp"
|
||||||
|
android:paddingEnd="16dp"
|
||||||
|
android:text="@string/pc_history"
|
||||||
|
android:textAllCaps="false"
|
||||||
|
android:textColor="@color/text"
|
||||||
|
android:textSize="14sp" />
|
||||||
|
</LinearLayout>
|
||||||
</LinearLayout>
|
</LinearLayout>
|
||||||
|
|
||||||
<!-- Vollbild-Liste: Warteschlange oder Playlists -->
|
<!-- Vollbild-Liste: Warteschlange oder Playlists -->
|
||||||
|
|||||||
@@ -58,23 +58,23 @@
|
|||||||
<string name="pc_list_error">Das hat nicht geklappt: %1$s</string>
|
<string name="pc_list_error">Das hat nicht geklappt: %1$s</string>
|
||||||
<string name="pc_this_pc">Verbunden</string>
|
<string name="pc_this_pc">Verbunden</string>
|
||||||
|
|
||||||
<!-- Playtube Jam (JamActivity, JamHub) -->
|
<!-- Playtube Sync (JamActivity, JamHub) -->
|
||||||
<string name="jam_title">Jam</string>
|
<string name="jam_title">Sync</string>
|
||||||
<string name="jam_open">Playtube Jam: gemeinsam hören</string>
|
<string name="jam_open">Playtube Sync: 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_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_name_hint">Dein Name</string>
|
||||||
<string name="jam_start">Jam starten</string>
|
<string name="jam_start">Sync starten</string>
|
||||||
<string name="jam_start_hint">Läuft gerade ein Song, wird er der erste im Jam.</string>
|
<string name="jam_start_hint">Läuft gerade ein Song, wird er der erste im Sync.</string>
|
||||||
<string name="jam_code_hint">Code oder Einladungslink</string>
|
<string name="jam_code_hint">Code oder Einladungslink</string>
|
||||||
<string name="jam_join">Beitreten</string>
|
<string name="jam_join">Beitreten</string>
|
||||||
<string name="jam_invite">Freunde einladen</string>
|
<string name="jam_invite">Freunde einladen</string>
|
||||||
<string name="jam_share">Link teilen</string>
|
<string name="jam_share">Link teilen</string>
|
||||||
<string name="jam_copy">Kopieren</string>
|
<string name="jam_copy">Kopieren</string>
|
||||||
<string name="jam_copied">Link kopiert.</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_share_text">Hör mit mir in Playtube Sync: %1$s</string>
|
||||||
<string name="jam_all_control">Alle dürfen steuern</string>
|
<string name="jam_all_control">Alle dürfen steuern</string>
|
||||||
<string name="jam_end">Jam beenden</string>
|
<string name="jam_end">Sync beenden</string>
|
||||||
<string name="jam_end_confirm">Jam für alle beenden?</string>
|
<string name="jam_end_confirm">Sync für alle beenden?</string>
|
||||||
<string name="jam_leave">Verlassen</string>
|
<string name="jam_leave">Verlassen</string>
|
||||||
<string name="jam_members">Dabei</string>
|
<string name="jam_members">Dabei</string>
|
||||||
<string name="jam_queue">Als Nächstes</string>
|
<string name="jam_queue">Als Nächstes</string>
|
||||||
@@ -95,28 +95,34 @@
|
|||||||
<string name="jam_client_android">Android</string>
|
<string name="jam_client_android">Android</string>
|
||||||
<string name="jam_client_web">Browser</string>
|
<string name="jam_client_web">Browser</string>
|
||||||
<string name="jam_kick">Entfernen</string>
|
<string name="jam_kick">Entfernen</string>
|
||||||
<string name="jam_kick_confirm">%1$s aus dem Jam entfernen?</string>
|
<string name="jam_kick_confirm">%1$s aus dem Sync entfernen?</string>
|
||||||
|
<string name="jam_make_host">Zum Host machen</string>
|
||||||
|
<string name="jam_like">Zu Lieblingssongs</string>
|
||||||
|
<string name="jam_make_host_confirm">%1$s zum Host machen? Du gibst damit die Host-Rechte ab.</string>
|
||||||
|
<string name="jam_error_offline">Diese Person ist gerade nicht verbunden.</string>
|
||||||
<string name="jam_play_now">Jetzt spielen</string>
|
<string name="jam_play_now">Jetzt spielen</string>
|
||||||
<string name="jam_remove">Entfernen</string>
|
<string name="jam_remove">Entfernen</string>
|
||||||
<string name="jam_added">Hinzugefügt: %1$s</string>
|
<string name="jam_added">Hinzugefügt: %1$s</string>
|
||||||
<string name="jam_added_shared">Zum Jam hinzugefügt.</string>
|
<string name="jam_added_shared">Zum Sync 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_playlist_adding">Playlist wird hinzugefügt …</string>
|
||||||
<string name="jam_play_hint">Die Musik läuft im Player von Playtube. Du kannst dort weiter in YouTube Music stöbern: Tippst du einen Song an, landet er wie bei Spotify im Jam. Mit Steuerrecht wirken Play/Pause und Weiter dort und in der Benachrichtigung für alle.</string>
|
<string name="jam_error_playlist">Diese Playlist ist nicht öffentlich oder existiert nicht.</string>
|
||||||
<string name="jam_status_creating">Jam wird gestartet …</string>
|
<string name="jam_share_no_jam">Du bist gerade in keinem Sync. Starte einen oder tritt einem bei.</string>
|
||||||
|
<string name="jam_play_hint">Die Musik läuft im Player von Playtube. Du kannst dort weiter in YouTube Music stöbern: Tippst du einen Song an, landet er wie bei Spotify im Sync. Mit Steuerrecht wirken Play/Pause und Weiter dort und in der Benachrichtigung für alle.</string>
|
||||||
|
<string name="jam_status_creating">Sync wird gestartet …</string>
|
||||||
<string name="jam_status_joining">Verbinde …</string>
|
<string name="jam_status_joining">Verbinde …</string>
|
||||||
<string name="jam_status_connected">Verbunden.</string>
|
<string name="jam_status_connected">Verbunden.</string>
|
||||||
<string name="jam_status_reconnecting">Verbindung unterbrochen – verbinde neu …</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_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_not_found">Diesen Sync gibt es nicht (mehr).</string>
|
||||||
<string name="jam_status_failed">Keine Verbindung zum Jam-Server.</string>
|
<string name="jam_status_failed">Keine Verbindung zum Sync-Server.</string>
|
||||||
<string name="jam_status_need_name">Bitte gib zuerst deinen Namen ein.</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_status_in_other">Du bist schon in einem Sync – verlasse ihn zuerst.</string>
|
||||||
<string name="jam_ended_host">Der Host hat den Jam beendet.</string>
|
<string name="jam_ended_host">Der Host hat den Sync beendet.</string>
|
||||||
<string name="jam_ended_over">Der Jam ist zu Ende.</string>
|
<string name="jam_ended_over">Der Sync ist zu Ende.</string>
|
||||||
<string name="jam_ended_expired">Der Jam ist abgelaufen.</string>
|
<string name="jam_ended_expired">Der Sync ist abgelaufen.</string>
|
||||||
<string name="jam_ended_kicked">Du wurdest aus dem Jam entfernt.</string>
|
<string name="jam_ended_kicked">Du wurdest aus dem Sync entfernt.</string>
|
||||||
<string name="jam_ended_left">Du hast den Jam verlassen.</string>
|
<string name="jam_ended_left">Du hast den Sync verlassen.</string>
|
||||||
<string name="jam_ended_full">Der Jam ist voll.</string>
|
<string name="jam_ended_full">Der Sync ist voll.</string>
|
||||||
<string name="jam_error_not_allowed">Das darf nur der Host.</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_queue_full">Die Warteschlange ist voll.</string>
|
||||||
<string name="jam_error_bad_video">Das ist kein YouTube-Link.</string>
|
<string name="jam_error_bad_video">Das ist kein YouTube-Link.</string>
|
||||||
@@ -143,4 +149,139 @@
|
|||||||
<item name="colorPrimary">@color/brand_from</item>
|
<item name="colorPrimary">@color/brand_from</item>
|
||||||
<item name="colorAccent">@color/brand_to</item>
|
<item name="colorAccent">@color/brand_to</item>
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
|
<!-- Einstellungen / Diagnose -->
|
||||||
|
<string name="settings_open">Einstellungen</string>
|
||||||
|
<string name="settings_title">Playtube-Einstellungen</string>
|
||||||
|
|
||||||
|
<!-- Schlaf-Timer und Verlauf -->
|
||||||
|
<string name="menu_title">Playtube</string>
|
||||||
|
<string name="sleep_title">Schlaf-Timer</string>
|
||||||
|
<string name="sleep_title_active">Schlaf-Timer (%1$s)</string>
|
||||||
|
<string name="sleep_minutes">%1$d Minuten</string>
|
||||||
|
<string name="sleep_end">Ende des Songs</string>
|
||||||
|
<string name="sleep_end_short">Songende</string>
|
||||||
|
<string name="sleep_off">Aus</string>
|
||||||
|
<string name="sleep_set">Schlaf-Timer: %1$s</string>
|
||||||
|
<string name="sleep_cleared">Schlaf-Timer aus</string>
|
||||||
|
<string name="sleep_done">Schlaf-Timer abgelaufen – Wiedergabe pausiert</string>
|
||||||
|
<string name="history_title">Verlauf</string>
|
||||||
|
<string name="history_pc_title">Verlauf am PC</string>
|
||||||
|
<string name="history_search">Im Verlauf suchen …</string>
|
||||||
|
<string name="history_empty">Noch nichts gehört – Songs erscheinen hier nach 30 Sekunden.</string>
|
||||||
|
<string name="history_clear">Verlauf löschen</string>
|
||||||
|
<string name="history_clear_confirm">Den ganzen Verlauf auf diesem Handy löschen?</string>
|
||||||
|
<string name="history_close">Schließen</string>
|
||||||
|
<string name="history_today">Heute, %1$s</string>
|
||||||
|
<string name="pc_sleep">Schlaf-Timer</string>
|
||||||
|
<string name="pc_history">Verlauf</string>
|
||||||
|
<string name="pc_too_old">Dafür braucht Playtube am PC ein Update (ab 2.14.0).</string>
|
||||||
|
<string name="diag_enabled">Diagnosedaten senden (hilft, Fehler zu finden)</string>
|
||||||
|
<string name="diag_hint">Gesendet werden Fehlermeldungen und Abstürze aus dem Playtube-Log, App- und Android-Version sowie das Gerätemodell mit einer zufälligen Kennung – keine Cookies, Anmeldedaten, Suchanfragen, Songtitel oder Video-IDs. Gespeichert 30 Tage. Details: playtube-ppp-eula.pages.dev/playtube/privacy/#diag</string>
|
||||||
|
<string name="diag_install_id">Kennung dieser Installation: %1$s</string>
|
||||||
|
<string name="diag_send_now">Jetzt senden</string>
|
||||||
|
<string name="diag_done">Fertig</string>
|
||||||
|
<string name="diag_sent">Diagnosedaten gesendet.</string>
|
||||||
|
<string name="diag_nothing">Keine neuen Einträge seit dem letzten Bericht.</string>
|
||||||
|
<string name="diag_failed">Senden fehlgeschlagen.</string>
|
||||||
|
<string name="diag_notice_title">Diagnosedaten</string>
|
||||||
|
<string name="diag_notice_message">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.</string>
|
||||||
|
<string name="diag_notice_ok">OK</string>
|
||||||
|
<string name="diag_notice_off">Abschalten</string>
|
||||||
|
<!-- Sozial: Konto und Freunde (SocialActivity, SocialHub) -->
|
||||||
|
<string name="social_open">Sozial: Freunde und Konto</string>
|
||||||
|
<string name="social_title">Sozial</string>
|
||||||
|
<string name="channel_invites">Einladungen von Freunden</string>
|
||||||
|
<string name="social_intro">Mit einem Playtube-Konto siehst du, was deine Freunde gerade hören, und holst sie mit einem Tipp in deinen Sync.</string>
|
||||||
|
<string name="social_login_title">Anmelden</string>
|
||||||
|
<string name="social_register_title">Konto erstellen</string>
|
||||||
|
<string name="social_reset_title">Passwort vergessen</string>
|
||||||
|
<string name="social_login_field">Benutzername oder E-Mail</string>
|
||||||
|
<string name="social_name_field">Benutzername (3–20 Zeichen: A–Z, 0–9, _ . -)</string>
|
||||||
|
<string name="social_email_field">E-Mail-Adresse</string>
|
||||||
|
<string name="social_password_field">Passwort</string>
|
||||||
|
<string name="social_password2_field">Passwort wiederholen</string>
|
||||||
|
<string name="social_login">Anmelden</string>
|
||||||
|
<string name="social_register">Konto erstellen</string>
|
||||||
|
<string name="social_send_reset">Link schicken</string>
|
||||||
|
<string name="social_to_register">Neues Konto erstellen</string>
|
||||||
|
<string name="social_to_login">Zur Anmeldung</string>
|
||||||
|
<string name="social_forgot">Passwort vergessen?</string>
|
||||||
|
<string name="social_optional_hint">Ein Konto ist freiwillig – Sync per Code oder Link geht weiterhin ohne. Passwort mindestens 8 Zeichen.</string>
|
||||||
|
<string name="social_privacy">Datenschutz</string>
|
||||||
|
<string name="social_signed_in_as">Angemeldet als</string>
|
||||||
|
<string name="social_logout">Abmelden</string>
|
||||||
|
<string name="social_share">Freunde sehen, was ich höre</string>
|
||||||
|
<string name="social_share_hint">Aus: Freunde sehen nur, ob du online bist.</string>
|
||||||
|
<string name="social_delete_account">Konto löschen</string>
|
||||||
|
<string name="social_delete_confirm">Endgültig löschen</string>
|
||||||
|
<string name="social_delete_hint">Löscht dein Konto, alle Freundschaften und Anfragen sofort. Zur Bestätigung dein Passwort:</string>
|
||||||
|
<string name="social_friends">Freunde</string>
|
||||||
|
<string name="social_no_friends">Noch keine Freunde – such unten nach ihrem Benutzernamen.</string>
|
||||||
|
<string name="social_search">Freunde finden</string>
|
||||||
|
<string name="social_search_placeholder">Benutzername</string>
|
||||||
|
<string name="social_search_button">Suchen</string>
|
||||||
|
<string name="social_add">Hinzufügen</string>
|
||||||
|
<string name="social_accept">Annehmen</string>
|
||||||
|
<string name="social_decline">Ablehnen</string>
|
||||||
|
<string name="social_withdraw">Zurückziehen</string>
|
||||||
|
<string name="social_remove_friend">Entfernen</string>
|
||||||
|
<string name="social_remove_confirm">%1$s als Freund entfernen?</string>
|
||||||
|
<string name="social_incoming">Anfragen</string>
|
||||||
|
<string name="social_outgoing">Gesendete Anfragen</string>
|
||||||
|
<string name="social_invite">Einladen</string>
|
||||||
|
<string name="social_invite_hint">„Einladen“ holt den Freund in deinen Sync – läuft noch keiner, wird einer gestartet. Lange tippen entfernt einen Freund.</string>
|
||||||
|
<string name="social_invites">Einladungen</string>
|
||||||
|
<string name="social_invite_from">%1$s lädt dich in den Sync ein</string>
|
||||||
|
<string name="social_invite_playing">Läuft gerade: %1$s</string>
|
||||||
|
<string name="social_invite_tap">Tippen zum Beitreten</string>
|
||||||
|
<string name="social_join">Beitreten</string>
|
||||||
|
<string name="social_dismiss">Ausblenden</string>
|
||||||
|
<string name="social_offline">Keine Verbindung zum Server – versuche es gleich wieder …</string>
|
||||||
|
<string name="social_offline_state">Offline</string>
|
||||||
|
<string name="social_online">Online</string>
|
||||||
|
<string name="social_online_pc">Online · PC</string>
|
||||||
|
<string name="social_online_android">Online · Android</string>
|
||||||
|
<string name="social_rel_friend">Schon befreundet</string>
|
||||||
|
<string name="social_rel_outgoing">Anfrage gesendet</string>
|
||||||
|
<string name="social_rel_incoming">Hat dir eine Anfrage geschickt</string>
|
||||||
|
<string name="social_working">Einen Moment …</string>
|
||||||
|
<string name="social_mismatch">Die beiden Passwörter sind nicht gleich.</string>
|
||||||
|
<string name="social_reset_sent">Falls es ein Konto mit dieser Adresse gibt, ist ein Link unterwegs (60 Minuten gültig). Schau auch im Spam-Ordner.</string>
|
||||||
|
<string name="social_logged_out">Abgemeldet.</string>
|
||||||
|
<string name="social_deleted">Dein Konto ist gelöscht.</string>
|
||||||
|
<string name="social_search_short">Mindestens 2 Zeichen eingeben.</string>
|
||||||
|
<string name="social_no_results">Niemanden gefunden.</string>
|
||||||
|
<string name="social_requested">Anfrage gesendet.</string>
|
||||||
|
<string name="social_now_friends">Ihr seid jetzt befreundet.</string>
|
||||||
|
<string name="social_starting_sync">Sync wird gestartet, dann geht die Einladung raus …</string>
|
||||||
|
<string name="social_invited">Einladung gesendet.</string>
|
||||||
|
<string name="social_invited_later">Gerade nicht online – die Einladung wartet 15 Minuten auf deinen Freund.</string>
|
||||||
|
<string name="social_error_failed">Das hat nicht geklappt. Bitte versuch es noch einmal.</string>
|
||||||
|
<string name="social_error_network">Keine Verbindung zum Server.</string>
|
||||||
|
<string name="social_error_wrong_login">Benutzername/E-Mail oder Passwort stimmt nicht.</string>
|
||||||
|
<string name="social_error_wrong_password">Das Passwort stimmt nicht.</string>
|
||||||
|
<string name="social_error_locked">Zu viele Fehlversuche. Das Konto ist 15 Minuten gesperrt – oder setze das Passwort zurück.</string>
|
||||||
|
<string name="social_error_rate_limited">Zu viele Versuche. Bitte warte eine Minute.</string>
|
||||||
|
<string name="social_error_bad_name">Benutzername: 3–20 Zeichen, nur A–Z, 0–9, _ . -</string>
|
||||||
|
<string name="social_error_bad_email">Das ist keine gültige E-Mail-Adresse.</string>
|
||||||
|
<string name="social_error_password_short">Das Passwort ist zu kurz (mindestens 8 Zeichen).</string>
|
||||||
|
<string name="social_error_password_long">Das Passwort ist zu lang.</string>
|
||||||
|
<string name="social_error_name_taken">Dieser Benutzername ist schon vergeben.</string>
|
||||||
|
<string name="social_error_email_taken">Mit dieser E-Mail gibt es schon ein Konto – melde dich an oder setze das Passwort zurück.</string>
|
||||||
|
<string name="social_error_mail_disabled">Der Mailversand ist noch nicht eingerichtet. Bitte später noch einmal versuchen.</string>
|
||||||
|
<string name="social_error_mail_failed">Die E-Mail konnte nicht verschickt werden. Bitte später noch einmal versuchen.</string>
|
||||||
|
<string name="social_error_unauthorized">Bitte melde dich neu an.</string>
|
||||||
|
<string name="social_error_session_expired">Deine Anmeldung ist abgelaufen. Bitte melde dich neu an.</string>
|
||||||
|
<string name="social_error_password_reset">Dein Passwort wurde geändert. Bitte melde dich mit dem neuen an.</string>
|
||||||
|
<string name="social_error_deleted">Dein Konto ist gelöscht.</string>
|
||||||
|
<string name="social_error_logout">Abgemeldet.</string>
|
||||||
|
<string name="social_error_user_not_found">Diesen Benutzer gibt es nicht.</string>
|
||||||
|
<string name="social_error_already_friends">Ihr seid schon befreundet.</string>
|
||||||
|
<string name="social_error_already_requested">Anfrage ist schon unterwegs.</string>
|
||||||
|
<string name="social_error_no_request">Diese Anfrage gibt es nicht mehr.</string>
|
||||||
|
<string name="social_error_too_many">Zu viele Freunde bzw. offene Anfragen.</string>
|
||||||
|
<string name="social_error_not_friends">Ihr seid (nicht mehr) befreundet.</string>
|
||||||
|
<string name="social_error_jam_not_found">Dein Sync läuft nicht mehr – starte einen neuen und lade noch einmal ein.</string>
|
||||||
|
<string name="social_error_bad_code">Ungültiger Sync-Code.</string>
|
||||||
</resources>
|
</resources>
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package de.fojadrachi.playtube
|
||||||
|
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class DiagReportTest {
|
||||||
|
@Test
|
||||||
|
fun removesPrivateData() {
|
||||||
|
val cases = mapOf(
|
||||||
|
"Cookie: SAPISID=abc; HSID=def" to "cookie [entfernt]",
|
||||||
|
"jam: lade dQw4w9WgXcQ" to "jam: lade [video]",
|
||||||
|
"GET https://music.youtube.com/search?q=lieblingssong ok" to "GET https://music.youtube.com/search?[…] ok",
|
||||||
|
"token=abcdef123 weiter" to "token=[entfernt] weiter",
|
||||||
|
"{\"last_token\":\"xyz\"}" to "{\"last_token\":\"[entfernt]\"}",
|
||||||
|
"Mail [email protected]" to "Mail [e-mail]",
|
||||||
|
"Playlist PLabcdefghij1234567890XYZ" to "Playlist [id]",
|
||||||
|
"Sende Bearer eyJhbGciOiJIUzI1NiJ9" to "Sende Bearer [entfernt]",
|
||||||
|
)
|
||||||
|
for ((input, expected) in cases) assertEquals(input, expected, DiagReport.sanitize(input))
|
||||||
|
assertEquals("Jam: Verbindung fehlgeschlagen", DiagReport.sanitize("Jam: Verbindung fehlgeschlagen"))
|
||||||
|
assertEquals("a b", DiagReport.sanitize("a\u0000b"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun removesIdsWithoutDigitsAndJsonTitles() {
|
||||||
|
assertEquals("jam: lade [video]", DiagReport.sanitize("jam: lade JZYXtUJcTws"))
|
||||||
|
assertEquals(
|
||||||
|
"Player: {\"artist\":\"[entfernt]\",\"id\":\"[video]\",\"title\":\"[entfernt]\",\"paused\":true}",
|
||||||
|
DiagReport.sanitize("Player: {\"artist\":\"Band\",\"id\":\"Rlg9P5i1bkQ\",\"title\":\"Mein Song\",\"paused\":true}"),
|
||||||
|
)
|
||||||
|
assertEquals("Verbindunge ServerError PlaytubeApp", DiagReport.sanitize("Verbindunge ServerError PlaytubeApp"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun recognizesVideoIds() {
|
||||||
|
assertTrue(DiagReport.looksLikeVideoId("dQw4w9WgXcQ"))
|
||||||
|
assertFalse(DiagReport.looksLikeVideoId("Verbindunge"))
|
||||||
|
assertFalse(DiagReport.looksLikeVideoId("12345678901"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun collectsOnlyNewLines() {
|
||||||
|
val log = "[100] alt\n[200] Jam: Verbindung fehlgeschlagen\nkaputt\n[202] neu\n"
|
||||||
|
val collected = DiagReport.collect(log, 100)
|
||||||
|
assertEquals(listOf("[200] Jam: Verbindung fehlgeschlagen", "[202] neu"), collected.lines)
|
||||||
|
assertEquals(202L, collected.latest)
|
||||||
|
assertTrue(DiagReport.collect(log, 202).lines.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun keepsTheNewestLines() {
|
||||||
|
val log = (1..1000).joinToString("\n") { "[$it] Zeile $it" }
|
||||||
|
val lines = DiagReport.collect(log, 0).lines
|
||||||
|
assertEquals(DiagReport.MAX_LINES, lines.size)
|
||||||
|
assertEquals("[701] Zeile 701", lines.first())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun manualReportWithoutLinesHasNote() {
|
||||||
|
assertEquals("manuell gesendet (keine neuen Einträge)", DiagReport.note(manual = true, noNewLines = true))
|
||||||
|
assertEquals("manuell gesendet", DiagReport.note(manual = true, noNewLines = false))
|
||||||
|
assertEquals("", DiagReport.note(manual = false, noNewLines = true))
|
||||||
|
val report = DiagReport.build("abc123abc123", "1.6.1", "15", "Google Pixel 9", emptyList(), DiagReport.note(true, true))
|
||||||
|
assertEquals(0, report.getJSONArray("lines").length())
|
||||||
|
assertTrue(report.getString("note").isNotEmpty()) // sonst lehnt der Server den Bericht als leer ab
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun buildsReport() {
|
||||||
|
val lines = listOf("[1] Absturz in main: java.lang.IllegalStateException", "[2] ok")
|
||||||
|
val report = DiagReport.build("abc123abc123", "1.6.0", "15", "Google Pixel 9", lines)
|
||||||
|
assertEquals("android", report.getString("app"))
|
||||||
|
assertEquals("android-15", report.getString("platform"))
|
||||||
|
assertEquals(1, report.getJSONArray("errors").length())
|
||||||
|
assertFalse(report.getBoolean("includesTitles"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -42,6 +42,34 @@ class JamSyncTest {
|
|||||||
assertNull(JamSync.videoIdFromSharedText("kein Link hier"))
|
assertNull(JamSync.videoIdFromSharedText("kein Link hier"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `gleicht kleine Abweichungen ueber das Tempo aus`() {
|
||||||
|
val want = JamSync.Target("aaaaaaaaaaa", "i", 30.0, false, 200.0)
|
||||||
|
fun local(pos: Double, rate: Double = 1.0, paused: Boolean = false) = JamSync.Local("aaaaaaaaaaa", pos, paused, rate)
|
||||||
|
assertEquals(listOf(JamSync.Step.Rate(0.92)), JamSync.decide(want, local(30.4)))
|
||||||
|
assertEquals(listOf(JamSync.Step.Rate(1.05)), JamSync.decide(want, local(29.8)))
|
||||||
|
assertEquals(listOf(JamSync.Step.Rate(1.0)), JamSync.decide(want, local(30.01, rate = 1.05)))
|
||||||
|
assertEquals(emptyList<JamSync.Step>(), JamSync.decide(want, local(30.05)))
|
||||||
|
assertEquals(
|
||||||
|
listOf(JamSync.Step.Seek(30.0 + JamSync.SEEK_LEAD_S), JamSync.Step.Rate(1.0)),
|
||||||
|
JamSync.decide(want, local(34.0, rate = 1.08)),
|
||||||
|
)
|
||||||
|
assertEquals(0.988, JamSync.nudgeRate(0.05, 1.02), 1e-9)
|
||||||
|
assertEquals(1.0, JamSync.nudgeRate(0.05, 1.0), 1e-9)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `liest Playlist-Links`() {
|
||||||
|
assertEquals("PLabc_1", JamSync.parsePlaylistId("https://music.youtube.com/playlist?list=PLabc_1"))
|
||||||
|
assertEquals("RDxyz", JamSync.parsePlaylistId("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=RDxyz"))
|
||||||
|
assertEquals("OLAK5uy_abc", JamSync.parsePlaylistId("OLAK5uy_abc"))
|
||||||
|
assertEquals("PLabc", JamSync.parsePlaylistId("VLPLabc"))
|
||||||
|
assertNull(JamSync.parsePlaylistId("https://evil.example/playlist?list=PLabc"))
|
||||||
|
assertNull(JamSync.parsePlaylistId("queen"))
|
||||||
|
assertEquals("PLabc", JamSync.playlistIdFromSharedText("Hör mal: https://music.youtube.com/playlist?list=PLabc"))
|
||||||
|
assertNull(JamSync.playlistIdFromSharedText("https://youtu.be/dQw4w9WgXcQ?list=PLabc"))
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun `liest den Zustand des Servers`() {
|
fun `liest den Zustand des Servers`() {
|
||||||
val state = JamSync.parseState(
|
val state = JamSync.parseState(
|
||||||
@@ -98,8 +126,8 @@ class JamSyncTest {
|
|||||||
@Test
|
@Test
|
||||||
fun `spult erst ab der Toleranz`() {
|
fun `spult erst ab der Toleranz`() {
|
||||||
val id = "aaaaaaaaaaa"
|
val id = "aaaaaaaaaaa"
|
||||||
assertTrue(JamSync.decide(want(30.0), local(id, 31.2, false)).isEmpty())
|
assertTrue(JamSync.decide(want(30.0), local(id, 30.05, false)).isEmpty())
|
||||||
assertEquals(listOf(Step.Seek(30.0)), JamSync.decide(want(30.0), local(id, 34.0, false)))
|
assertEquals(listOf(Step.Seek(30.0 + JamSync.SEEK_LEAD_S)), JamSync.decide(want(30.0), local(id, 34.0, false)))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
package de.fojadrachi.playtube
|
||||||
|
|
||||||
|
import org.json.JSONObject
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
class SleepAndHistoryTest {
|
||||||
|
private fun song(title: String, durationS: Long = 200) =
|
||||||
|
NowPlaying(title, "Band", "https://i.ytimg.com/x.jpg", playing = true, positionMs = 0, durationMs = durationS * 1000)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Schlaf-Timer wartet, blendet aus und stoppt`() {
|
||||||
|
val timer = SleepTimer.minutes(1, 0)
|
||||||
|
assertEquals(60L, timer.remainingSeconds(0))
|
||||||
|
assertEquals(SleepTimer.Step.Wait, timer.tick(10_000, null))
|
||||||
|
val fade = timer.tick(50_000, null) as SleepTimer.Step.Fade
|
||||||
|
assertEquals(10.0 / 15.0, fade.factor, 0.01)
|
||||||
|
assertEquals(SleepTimer.Step.Stop, timer.tick(60_000, null))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Schlaf-Timer am Songende stoppt beim naechsten Song`() {
|
||||||
|
val timer = SleepTimer.endOfTrack(null)
|
||||||
|
assertTrue(timer.endOfTrack)
|
||||||
|
assertEquals(-1L, timer.remainingSeconds(0))
|
||||||
|
assertEquals(SleepTimer.Step.Wait, timer.tick(0, "aaa"))
|
||||||
|
assertEquals(SleepTimer.Step.Wait, timer.tick(0, null))
|
||||||
|
assertEquals(SleepTimer.Step.Wait, timer.tick(0, "aaa"))
|
||||||
|
assertEquals(SleepTimer.Step.Stop, timer.tick(0, "bbb"))
|
||||||
|
assertEquals("1:05", SleepTimer.format(65))
|
||||||
|
assertEquals("1:02:03", SleepTimer.format(3723))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Verlauf zaehlt nach 30 Sekunden und haelt die Hoerdauer fest`() {
|
||||||
|
val history = PlayHistory()
|
||||||
|
val info = song("Lied")
|
||||||
|
assertFalse(history.observe("vid1", info, true, 0, 1000))
|
||||||
|
var changed = false
|
||||||
|
for (i in 1..14) changed = changed or history.observe("vid1", info, true, i * 2000L, 1000)
|
||||||
|
assertFalse(changed)
|
||||||
|
assertTrue(history.observe("vid1", info, true, 30_000, 1000))
|
||||||
|
assertEquals(1, history.entries.size)
|
||||||
|
history.observe("vid1", info, true, 40_000, 1000)
|
||||||
|
assertTrue(history.observe(null, info, false, 41_000, 1000))
|
||||||
|
assertEquals(40, history.entries[0].listened)
|
||||||
|
assertFalse("schon gespeichert", history.observe(null, info, false, 42_000, 1000))
|
||||||
|
assertEquals(1000L, history.entries[0].playedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Uebersprungene Songs zaehlen nicht, kurze nach der Haelfte`() {
|
||||||
|
val history = PlayHistory()
|
||||||
|
history.observe("skip", song("Weg"), true, 0, 0)
|
||||||
|
history.observe("skip", song("Weg"), true, 5_000, 0)
|
||||||
|
history.observe("short", song("Kurz", 40), true, 6_000, 0)
|
||||||
|
history.observe("short", song("Kurz", 40), true, 16_000, 0)
|
||||||
|
history.observe("short", song("Kurz", 40), true, 26_000, 0)
|
||||||
|
assertEquals(listOf("Kurz"), history.entries.map { it.title })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `Speichern, Laden und Suchen`() {
|
||||||
|
val history = PlayHistory(listOf(
|
||||||
|
HistoryEntry("a1", "Alpha", "X", null, 1, 40),
|
||||||
|
HistoryEntry("b2", "Beta", "alphaband", "https://i.ytimg.com/b.jpg", 2, 50),
|
||||||
|
))
|
||||||
|
val loaded = PlayHistory.fromJson(history.toJson())
|
||||||
|
assertEquals(history.entries, loaded.entries)
|
||||||
|
assertEquals(listOf("Beta", "Alpha"), loaded.search("").map { it.title })
|
||||||
|
assertEquals(listOf("Beta", "Alpha"), loaded.search("ALPHA").map { it.title })
|
||||||
|
assertEquals(listOf("Alpha"), loaded.search("x").map { it.title })
|
||||||
|
assertTrue(PlayHistory.fromJson("kaputt").entries.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `PC-Verlauf wird gelesen und geprueft`() {
|
||||||
|
val reply = JSONObject("""{"ok":true,"history":[
|
||||||
|
{"videoId":"dQw4w9WgXcQ","title":"Lied","artist":"Band","thumbnail":"https://i.ytimg.com/a.jpg","playedAt":100,"listened":60},
|
||||||
|
{"videoId":"bad id!","title":"X"},
|
||||||
|
{"videoId":"ok_id-1","title":"Y","thumbnail":"javascript:x"}]}""")
|
||||||
|
val list = PlayHistory.parsePcHistory(reply)
|
||||||
|
assertEquals(listOf("dQw4w9WgXcQ", "ok_id-1"), list.map { it.videoId })
|
||||||
|
assertEquals(100_000L, list[0].playedAt)
|
||||||
|
assertEquals(null, list[1].artwork)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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":"[email protected]","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))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,15 @@
|
|||||||
## Playtube für Android 1.4.1
|
## Playtube für Android 1.11.0
|
||||||
|
|
||||||
- **Jam mit YouTube Music:** Während eines Jams kannst du in YouTube Music normal weiterstöbern (Suche, Bibliothek,
|
- **Neue Adresse für Sync:** Einladungen laufen jetzt über `sync.fojadrachi.de` (passend zum neuen Namen). Alte
|
||||||
Playlists), ohne dass der Jam-Song neu lädt. Tippst du einen Song an, kommt er wie bei Spotify Jam in die
|
Links auf `jam.fojadrachi.de` und `playtube://jam/…` funktionieren weiter.
|
||||||
gemeinsame Warteschlange.
|
|
||||||
- Der Jam liest Position und Status jetzt direkt vom YouTube-Music-Player – zuverlässigeres Synchronisieren.
|
|
||||||
|
|
||||||
Alles Weitere wie in 1.4.0 (Playtube Jam). Voraussetzung: Android 8.0 oder neuer.
|
Alles Weitere wie in 1.10.0. Voraussetzung: Android 8.0 oder neuer.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Playtube for Android 1.11.0
|
||||||
|
|
||||||
|
- **New address for Sync:** invites now go through `sync.fojadrachi.de` (matching the new name). Old links to
|
||||||
|
`jam.fojadrachi.de` and `playtube://jam/…` keep working.
|
||||||
|
|
||||||
|
Everything else as in 1.10.0. Requires Android 8.0 or newer.
|
||||||
|
|||||||
Reference in New Issue
Block a user