package de.fojadrachi.playtube import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Handler import android.os.Looper import androidx.core.content.ContextCompat import org.json.JSONObject import java.io.IOException import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.concurrent.RejectedExecutionException /** * Die Verbindung zum PC ueberlebt den Steuerungsbildschirm (wie Spotify Connect): sie lebt hier im * Prozess, gehalten von [PcRemoteService] (Vordergrunddienst + Benachrichtigung). Verbindung, Status- * Abfrage und Befehle laufen auf einem eigenen Thread; Aufrufer und Listener sind immer der Hauptthread. */ object PcSession { enum class Phase { IDLE, CONNECTING, CONNECTED, RECONNECTING } enum class Problem { PAIRING_REQUIRED, FAILED, LOST } interface Listener { fun onUpdate() fun onProblem(problem: Problem, message: String) } const val PREFS = "pc_remote" const val KEY_TOKEN_FOR = "token:" const val KEY_NAME_FOR = "name:" const val KEY_LAST_HOST = "last_host" private const val POLL_VISIBLE_MS = 1_000L private const val POLL_BACKGROUND_MS = 4_000L private const val RECONNECT_ATTEMPTS = 5 private val main = Handler(Looper.getMainLooper()) private val worker: ExecutorService = Executors.newSingleThreadExecutor() private val listeners = mutableListOf() /** Nur auf [worker] benutzen. */ private var connection: PcRemote.Connection? = null private var statusPending = false private var generation = 0 private var reconnectAttempt = 0 private lateinit var appContext: Context var phase = Phase.IDLE private set var device: PcDevice? = null private set var state: PcState = PcState.EMPTY private set /** Verbunden oder gerade dabei (Player soll angezeigt werden). */ val isActive: Boolean get() = phase == Phase.CONNECTED || phase == Phase.RECONNECTING fun prefs(context: Context): SharedPreferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) // ------------------------------------------------------------------ Listener / Polling fun addListener(listener: Listener) { listeners += listener if (listeners.size == 1 && phase == Phase.CONNECTED) { main.removeCallbacks(poll) main.post(poll) // sofort frischen Stand holen, danach im 1-s-Takt } } fun removeListener(listener: Listener) { listeners -= listener } private val poll = object : Runnable { override fun run() { if (phase != Phase.CONNECTED) return requestStatus() main.postDelayed(this, if (listeners.isEmpty()) POLL_BACKGROUND_MS else POLL_VISIBLE_MS) } } private fun notifyUpdate() = listeners.toList().forEach { it.onUpdate() } private fun notifyProblem(problem: Problem, message: String) = listeners.toList().forEach { it.onProblem(problem, message) } // ------------------------------------------------------------------ Verbinden / Trennen /** * Verbindet mit [target]: mit [code] wird neu gekoppelt, sonst mit dem gespeicherten [token]. * Startet dabei den Vordergrunddienst, der die Verbindung haelt. */ fun connect(context: Context, target: PcDevice, token: String?, code: String?) { appContext = context.applicationContext val gen = ++generation main.removeCallbacks(poll) phase = Phase.CONNECTING device = target state = PcState.EMPTY reconnectAttempt = 0 notifyUpdate() ContextCompat.startForegroundService(appContext, Intent(appContext, PcRemoteService::class.java)) onWorker { closeConnection() try { val conn = PcRemote.Connection.open(target) val reply = try { if (code != null) { conn.request("pair") { put("code", code) put("device", Build.MODEL ?: "Android") } } else { conn.request("hello") { put("token", token.orEmpty()) } } } catch (e: IOException) { conn.close() throw e } connection = conn main.post { if (gen == generation) onConnected(target, reply, code != null) else onWorker { conn.close() } } } catch (e: PcRemote.RemoteException) { main.post { if (gen != generation) return@post if (code == null) { prefs(appContext).edit().remove(KEY_TOKEN_FOR + target.name).apply() reset() notifyProblem(Problem.PAIRING_REQUIRED, e.message.orEmpty()) } else { reset() notifyProblem(Problem.FAILED, e.message ?: "Fehler") } } } catch (e: IOException) { main.post { if (gen != generation) return@post reset() notifyProblem(Problem.FAILED, e.message ?: e.javaClass.simpleName) } } } } private fun onConnected(target: PcDevice, reply: JSONObject, paired: Boolean) { // Der PC meldet seinen Namen - unter dem merken wir uns Token und Adresse. val name = reply.optString("name").ifBlank { target.name } val token = if (paired) reply.optString("token") else prefs(appContext).getString(KEY_TOKEN_FOR + target.name, null) prefs(appContext).edit().apply { if (!token.isNullOrEmpty()) { putString(KEY_TOKEN_FOR + target.name, token) putString(KEY_TOKEN_FOR + name, token) } putString(KEY_NAME_FOR + target.host, name) putString(KEY_LAST_HOST, target.host) }.apply() device = target.copy(name = name) phase = Phase.CONNECTED notifyUpdate() main.removeCallbacks(poll) main.post(poll) } /** Trennt bewusst (Knopf "Trennen") und beendet den Dienst. */ fun disconnect() { reset() notifyUpdate() } private fun reset() { generation++ main.removeCallbacks(poll) main.removeCallbacks(reconnectRunnable) phase = Phase.IDLE device = null state = PcState.EMPTY statusPending = false onWorker { closeConnection() } if (::appContext.isInitialized) appContext.stopService(Intent(appContext, PcRemoteService::class.java)) } // ------------------------------------------------------------------ Verbindungsverlust private fun onConnectionLost() { if (phase != Phase.CONNECTED) return phase = Phase.RECONNECTING reconnectAttempt = 0 main.removeCallbacks(poll) notifyUpdate() scheduleReconnect() } private val reconnectRunnable = Runnable { reconnect() } private fun scheduleReconnect() { main.postDelayed(reconnectRunnable, 2_000L * (reconnectAttempt + 1)) } private fun reconnect() { val target = device ?: return if (phase != Phase.RECONNECTING) return val token = prefs(appContext).getString(KEY_TOKEN_FOR + target.name, null) val gen = generation reconnectAttempt++ onWorker { closeConnection() try { val conn = PcRemote.Connection.open(target) try { conn.request("hello") { put("token", token.orEmpty()) } } catch (e: IOException) { conn.close() throw e } connection = conn main.post { if (gen != generation || phase != Phase.RECONNECTING) return@post phase = Phase.CONNECTED notifyUpdate() main.removeCallbacks(poll) main.post(poll) } } catch (e: IOException) { main.post { if (gen != generation || phase != Phase.RECONNECTING) return@post if (e is PcRemote.RemoteException || reconnectAttempt >= RECONNECT_ATTEMPTS) { val name = device?.name.orEmpty() reset() notifyUpdate() notifyProblem(Problem.LOST, name) } else { scheduleReconnect() } } } } } // ------------------------------------------------------------------ Befehle und Stand private fun requestStatus() { // Bei langsamem WLAN nicht eine Abfrage pro Sekunde aufstauen. if (statusPending) return statusPending = true val gen = generation onWorker { try { val conn = connection if (conn == null) { main.post { statusPending = false } return@onWorker } val next = PcRemote.parseState(conn.request("status")) main.post { statusPending = false if (gen != generation || phase != Phase.CONNECTED) return@post if (next != null) { state = next notifyUpdate() } } } catch (_: IOException) { closeConnection() main.post { statusPending = false if (gen == generation) onConnectionLost() } } } } /** Befehl ohne Antwort; danach wird der Stand neu abgefragt. */ fun send(command: String, target: String = "auto", value: Double? = null) { request(command, { put("target", target) if (value != null) put("value", value) }) { requestStatus() } } /** Anfrage mit Antwort; [done] kommt auf dem Hauptthread (Fehler: RemoteException vom PC oder IOException). */ fun request(command: String, fill: JSONObject.() -> Unit = {}, done: (Result) -> Unit = {}) { val gen = generation onWorker { val conn = connection if (conn == null) { main.post { done(Result.failure(IOException("Nicht verbunden"))) } return@onWorker } try { val reply = conn.request(command, fill) main.post { done(Result.success(reply)) } } catch (e: PcRemote.RemoteException) { main.post { done(Result.failure(e)) } // Befehl abgelehnt - Verbindung bleibt } catch (e: IOException) { closeConnection() main.post { if (gen == generation) onConnectionLost() done(Result.failure(e)) } } } } private fun onWorker(block: () -> Unit) { try { worker.execute(block) } catch (_: RejectedExecutionException) { } } /** Nur auf [worker] aufrufen. */ private fun closeConnection() { connection?.close() connection = null } }