From 14f2eeabe1d7076c042676987cef5da255f48be5 Mon Sep 17 00:00:00 2001 From: Michatec Date: Mon, 10 Aug 2026 22:56:56 +0200 Subject: [PATCH] feat(remote-control): add remote authentication plugin and enhance API routes --- .../com/michatec/radio/helpers/FileHelper.kt | 8 + .../radio/helpers/RemoteControlServer.kt | 470 +++++------------- .../com/michatec/radio/remote/AuthPlugin.kt | 52 ++ .../michatec/radio/remote/KtorExtensions.kt | 20 + .../michatec/radio/remote/RemoteConstants.kt | 37 ++ .../com/michatec/radio/remote/RemoteDtos.kt | 35 ++ .../com/michatec/radio/remote/RemoteRoutes.kt | 140 ++++++ 7 files changed, 414 insertions(+), 348 deletions(-) create mode 100644 app/src/main/java/com/michatec/radio/remote/AuthPlugin.kt create mode 100644 app/src/main/java/com/michatec/radio/remote/KtorExtensions.kt create mode 100644 app/src/main/java/com/michatec/radio/remote/RemoteConstants.kt create mode 100644 app/src/main/java/com/michatec/radio/remote/RemoteDtos.kt create mode 100644 app/src/main/java/com/michatec/radio/remote/RemoteRoutes.kt diff --git a/app/src/main/java/com/michatec/radio/helpers/FileHelper.kt b/app/src/main/java/com/michatec/radio/helpers/FileHelper.kt index e085eef..edfc20a 100644 --- a/app/src/main/java/com/michatec/radio/helpers/FileHelper.kt +++ b/app/src/main/java/com/michatec/radio/helpers/FileHelper.kt @@ -477,4 +477,12 @@ object FileHelper { return File(folder, ".nomedia") } + /* Returns the image file for a given station UUID */ + fun getStationImageFile(context: Context, stationUuid: String): File { + return File( + context.getExternalFilesDir(""), + determineDestinationFolderPath(Keys.FILE_TYPE_IMAGE, stationUuid) + "/" + Keys.STATION_IMAGE_FILE + ) + } + } diff --git a/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt b/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt index d008870..de2faed 100644 --- a/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt +++ b/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt @@ -6,26 +6,20 @@ import androidx.media3.common.MediaItem import androidx.media3.common.Metadata import androidx.media3.common.Player import androidx.media3.common.util.UnstableApi -import com.michatec.radio.BuildConfig import com.google.gson.Gson -import io.ktor.http.* +import com.michatec.radio.remote.* import io.ktor.serialization.gson.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.plugins.contentnegotiation.* -import io.ktor.server.request.* -import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.websocket.* -import io.ktor.websocket.* -import java.util.concurrent.ConcurrentHashMap import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock -import java.io.File import java.net.BindException import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds @@ -37,95 +31,9 @@ class RemoteControlServer(private val context: Context) { private var serverScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val lifecycleMutex = Mutex() private val gson = Gson() - private val failedAttemptsMap = ConcurrentHashMap() - private val _statusUpdates = MutableSharedFlow>(extraBufferCapacity = 1) + private val _statusUpdates = MutableSharedFlow(extraBufferCapacity = 1) private val statusUpdates = _statusUpdates.asSharedFlow() - private val playerListener = object : Player.Listener { - override fun onIsPlayingChanged(isPlaying: Boolean) { - broadcastStatus() - } - - override fun onPlaybackStateChanged(playbackState: Int) { - broadcastStatus() - } - - override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) { - broadcastStatus() - } - - @UnstableApi - override fun onMetadata(metadata: Metadata) { - broadcastStatus() - } - } - - private suspend fun getStationsList(): List> { - val collection = onGetCollection?.invoke() ?: withContext(Dispatchers.IO) { - FileHelper.readCollection(context) - } - return collection.stations.map { - val imageFile = File(context.getExternalFilesDir(""), FileHelper.determineDestinationFolderPath(com.michatec.radio.Keys.FILE_TYPE_IMAGE, it.uuid) + "/" + com.michatec.radio.Keys.STATION_IMAGE_FILE) - val lastModified = if (imageFile.exists()) imageFile.lastModified() else 0L - mapOf( - "uuid" to it.uuid, - "name" to it.name, - "hasImage" to it.smallImage.isNotEmpty(), - "starred" to it.starred, - "lastModified" to lastModified - ) - } - } - - fun notifyCollectionChanged() { - serverScope.launch { - try { - val stations = getStationsList() - _statusUpdates.emit(mapOf("type" to "stations", "data" to stations)) - } catch (e: Exception) { - Log.e("RemoteControlServer", "Error broadcasting stations", e) - } - } - } - - private fun broadcastStatus() { - serverScope.launch { - val status = getStatusMap() - if (status != null) { - _statusUpdates.emit(mapOf("type" to "status", "data" to status)) - } - } - } - - private suspend fun getStatusMap(): Map? { - val p = player ?: return null - return try { - val collection = onGetCollection?.invoke() ?: withContext(Dispatchers.IO) { - FileHelper.readCollection(context) - } - - withContext(Dispatchers.Main) { - val metadataHistory = PreferencesHelper.loadMetadataHistory() - val currentTrack = if (metadataHistory.isNotEmpty()) metadataHistory.last() else "" - val mediaId = p.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid() - - val station = CollectionHelper.getStation(collection, mediaId) - - mapOf( - "isPlaying" to p.isPlaying, - "playWhenReady" to p.playWhenReady, - "playbackState" to p.playbackState, - "currentStationUuid" to mediaId, - "metadata" to currentTrack, - "starred" to station.starred - ) - } - } catch (e: Exception) { - Log.e("RemoteControlServer", "Error getting status map", e) - null - } - } - var onPlayStation: ((String) -> Unit)? = null var onGetCollection: (() -> com.michatec.radio.core.Collection)? = null var onPause: (() -> Unit)? = null @@ -135,274 +43,150 @@ class RemoteControlServer(private val context: Context) { var onError: ((String) -> Unit)? = null var onAuthFailed: ((String) -> Unit)? = null + private val playerListener = object : Player.Listener { + override fun onIsPlayingChanged(isPlaying: Boolean) = broadcastStatus() + override fun onPlaybackStateChanged(playbackState: Int) = broadcastStatus() + override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) = broadcastStatus() + @UnstableApi override fun onMetadata(metadata: Metadata) = broadcastStatus() + } + + private suspend fun getStationsList(): List { + val collection = onGetCollection?.invoke() ?: withContext(Dispatchers.IO) { + FileHelper.readCollection(context) + } + return collection.stations.map { + val imageFile = FileHelper.getStationImageFile(context, it.uuid) + StationDto( + uuid = it.uuid, + name = it.name, + hasImage = it.smallImage.isNotEmpty(), + starred = it.starred, + lastModified = if (imageFile.exists()) imageFile.lastModified() else 0L, + ) + } + } + + fun notifyCollectionChanged() { + serverScope.launch { + try { + _statusUpdates.emit(WebSocketMessage(RemoteConstants.WebSocket.TYPE_STATIONS, getStationsList())) + } catch (e: Exception) { + if (e is CancellationException) throw e + Log.e("RemoteControlServer", "Error broadcasting stations", e) + } + } + } + + private fun broadcastStatus() { + serverScope.launch { + getStatusMap()?.let { + _statusUpdates.emit(WebSocketMessage(RemoteConstants.WebSocket.TYPE_STATUS, it)) + } + } + } + + private suspend fun getStatusMap(): StatusResponse? { + val p = player ?: return null + return try { + val collection = onGetCollection?.invoke() ?: withContext(Dispatchers.IO) { + FileHelper.readCollection(context) + } + + withContext(Dispatchers.Main) { + val metadataHistory = PreferencesHelper.loadMetadataHistory() + val currentTrack = if (metadataHistory.isNotEmpty()) metadataHistory.last() else "" + val mediaId = p.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid() + val station = CollectionHelper.getStation(collection, mediaId) + + StatusResponse( + isPlaying = p.isPlaying, + playWhenReady = p.playWhenReady, + playbackState = p.playbackState, + currentStationUuid = mediaId, + metadata = currentTrack, + starred = station.starred, + ) + } + } catch (e: Exception) { + if (e is CancellationException) throw e + Log.e("RemoteControlServer", "Error getting status map", e) + null + } + } + + private suspend fun runOnMain(action: () -> Unit) = withContext(Dispatchers.Main) { + action() + } + fun setPlayer(player: Player?) { this.player?.removeListener(playerListener) this.player = player this.player?.addListener(playerListener) } - private fun safeReadAsset(path: String): ByteArray? { - return try { - context.assets.open(path).use { it.readBytes() } - } catch (e: Exception) { - Log.e("RemoteControlServer", "Failed to read asset: $path", e) - null - } - } - fun start() { serverScope.launch { lifecycleMutex.withLock { - if (server != null) { - Log.d("RemoteControlServer", "Server is already running.") - return@withLock - } + if (server != null) return@withLock var attempt = 1 val maxAttempts = 5 while (attempt <= maxAttempts) { try { - Log.i("RemoteControlServer", "Starting server (attempt $attempt)...") - val newServer = embeddedServer(Netty, port = 8080, host = "0.0.0.0") { - install(ContentNegotiation) { - gson() - } - install(WebSockets) { - pingPeriod = 30.seconds - timeout = 60.seconds - maxFrameSize = Long.MAX_VALUE - masking = false - } - - intercept(ApplicationCallPipeline.Plugins) { - val authEnabled = PreferencesHelper.loadRemoteControlAuthEnabled() - if (authEnabled) { - val secret = PreferencesHelper.loadRemoteControlSecretToken() - val requestPath = call.request.path() - val isStatic = requestPath == "/" || - requestPath == "/style.css" || - requestPath == "/script.js" || - requestPath == "/favicon.png" || - requestPath == "/translations.json" - - if (!isStatic) { - val providedKey = call.request.headers["X-Remote-Key"] - ?: call.request.queryParameters["token"] - val remoteHost = call.request.local.remoteHost - - if (providedKey != secret) { - val attempts = (failedAttemptsMap[remoteHost] ?: 0) + 1 - failedAttemptsMap[remoteHost] = attempts - - if (attempts >= 10) { - withContext(Dispatchers.Main) { - onAuthFailed?.invoke(remoteHost) - } - } - delay(2000.milliseconds) - call.respond(HttpStatusCode.Unauthorized, mapOf("error" to "Unauthorized")) - finish() - } else { - failedAttemptsMap.remove(remoteHost) - } + val routes = RemoteRoutes( + context = context, + gson = gson, + getStatus = { getStatusMap() }, + getStations = { getStationsList() }, + statusUpdates = statusUpdates + ) { action, data -> + runOnMain { + when (action) { + "play" -> onPlayStation?.invoke(data!!) + "pause" -> onPause?.invoke() + "resume" -> { + if (player?.playbackState == Player.STATE_IDLE) { + onPlayStation?.invoke(player?.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid()) + } else onResume?.invoke() } - } - } - - routing { - get("/") { - val content = safeReadAsset("web/index.html") - if (content != null) { - call.response.header(HttpHeaders.CacheControl, "no-cache, no-store, must-revalidate") - call.respondBytes(content, ContentType.Text.Html) - } else { - call.respond(HttpStatusCode.NotFound) - } - } - get("/style.css") { - val content = safeReadAsset("web/style.css") - if (content != null) { - call.respondBytes(content, ContentType.Text.CSS) - } else { - call.respond(HttpStatusCode.NotFound) - } - } - get("/script.js") { - val content = safeReadAsset("web/script.js") - if (content != null) { - call.response.header(HttpHeaders.CacheControl, "no-cache, no-store, must-revalidate") - call.respondBytes(content, ContentType.Application.JavaScript) - } else { - call.respond(HttpStatusCode.NotFound) - } - } - get("/translations.json") { - val content = safeReadAsset("web/translations.json") - if (content != null) { - call.respondBytes(content, ContentType.Application.Json) - } else { - call.respond(HttpStatusCode.NotFound) - } - } - get("/favicon.png") { - val content = safeReadAsset("web/favicon.png") - if (content != null) { - call.respondBytes(content, ContentType.Image.PNG) - } else { - call.respond(HttpStatusCode.NotFound) - } - } - - get("/api/config") { - try { - call.respond(mapOf("version" to BuildConfig.VERSION_NAME)) - } catch (e: Exception) { - call.respond(HttpStatusCode.InternalServerError, mapOf("error" to e.message)) - } - } - - get("/api/status") { - val status = getStatusMap() - if (status == null) { - call.respond(HttpStatusCode.ServiceUnavailable, mapOf("error" to "Player not available")) - } else { - call.respond(status) - } - } - - webSocket("/api/updates") { - // Send current status and stations immediately on connect - try { - getStatusMap()?.let { send(Frame.Text(gson.toJson(mapOf("type" to "status", "data" to it)))) } - val stations = getStationsList() - send(Frame.Text(gson.toJson(mapOf("type" to "stations", "data" to stations)))) - } catch (_: Exception) { } - - val job = launch { - statusUpdates.collect { update -> - try { - send(Frame.Text(gson.toJson(update))) - } catch (_: Exception) { } - } - } - try { - for (frame in incoming) { - frame.takeIf { it is Frame.Text } ?: continue - } - } catch (_: Exception) { - Log.d("RemoteControlServer", "WebSocket client disconnected") - } finally { - job.cancel() - } - } - - get("/api/stations") { - try { - val stations = getStationsList() - call.respond(stations) - } catch (e: Exception) { - call.respond(HttpStatusCode.InternalServerError, mapOf("error" to e.message)) - } - } - - get("/api/image/{uuid}") { - val uuid = call.parameters["uuid"] - if (uuid != null) { - try { - val collection = withContext(Dispatchers.IO) { - FileHelper.readCollection(context) - } - val station = CollectionHelper.getStation(collection, uuid) - if (station.smallImage.isNotEmpty()) { - val imageFile = File(context.getExternalFilesDir(""), FileHelper.determineDestinationFolderPath(com.michatec.radio.Keys.FILE_TYPE_IMAGE, uuid) + "/" + com.michatec.radio.Keys.STATION_IMAGE_FILE) - if (imageFile.exists()) { - val lastModified = imageFile.lastModified() - val etag = "W/\"${lastModified}-${imageFile.length()}\"" - - if (call.request.headers[HttpHeaders.IfNoneMatch] == etag) { - call.respond(HttpStatusCode.NotModified) - } else { - call.response.header(HttpHeaders.CacheControl, "public, max-age=86400") - call.response.header(HttpHeaders.ETag, etag) - call.respondBytes(imageFile.readBytes(), ContentType.Image.JPEG) - } - } else { - call.respond(HttpStatusCode.NotFound) - } - } else { - call.respond(HttpStatusCode.NotFound) - } - } catch (_: Exception) { - call.respond(HttpStatusCode.InternalServerError) - } - } else { - call.respond(HttpStatusCode.BadRequest) - } - } - - post("/api/play/{uuid}") { - val uuid = call.parameters["uuid"] - if (uuid != null) { - Log.i("RemoteControlServer", "Play request for: $uuid") - withContext(Dispatchers.Main) { - onPlayStation?.invoke(uuid) - } - call.respond(mapOf("status" to "ok")) - } - } - - post("/api/pause") { - Log.i("RemoteControlServer", "Pause request") - withContext(Dispatchers.Main) { - onPause?.invoke() - } - call.respond(mapOf("status" to "ok")) - } - - post("/api/resume") { - Log.i("RemoteControlServer", "Resume request") - withContext(Dispatchers.Main) { - onResume?.invoke() - } - call.respond(mapOf("status" to "ok")) - } - - post("/api/next") { - Log.i("RemoteControlServer", "Next request") - withContext(Dispatchers.Main) { - onNext?.invoke() - } - call.respond(mapOf("status" to "ok")) - } - - post("/api/prev") { - Log.i("RemoteControlServer", "Prev request") - withContext(Dispatchers.Main) { - onPrev?.invoke() - } - call.respond(mapOf("status" to "ok")) + "next" -> onNext?.invoke() + "prev" -> onPrev?.invoke() } } } - server = newServer - newServer.start(wait = false) - Log.i("RemoteControlServer", "Server successfully started on port 8080") + + server = embeddedServer(Netty, port = RemoteConstants.PORT, host = RemoteConstants.HOST) { + install(ContentNegotiation) { gson() } + install(WebSockets) { + pingPeriod = 30.seconds + timeout = 60.seconds + } + install(RemoteAuthPlugin) { + onAuthFailed = { ip -> + serverScope.launch(Dispatchers.Main) { this@RemoteControlServer.onAuthFailed?.invoke(ip) } + } + } + routing { + with(routes) { installRoutes() } + } + }.apply { start(wait = false) } + + Log.i("RemoteControlServer", "Server successfully started on port ${RemoteConstants.PORT}") return@withLock } catch (e: Exception) { - if (e is BindException || e.cause is BindException) { - Log.w("RemoteControlServer", "Port 8080 busy, retrying in 1s...") + if ((e is BindException) || (e.cause is BindException)) { + Log.w("RemoteControlServer", "Port busy, retrying...") delay(1000.milliseconds) attempt++ } else { Log.e("RemoteControlServer", "Critical server error", e) - onError?.invoke(e.localizedMessage ?: "Critical error") + runOnMain { onError?.invoke(e.localizedMessage ?: "Critical error") } break } } } - Log.e("RemoteControlServer", "Failed to start after $maxAttempts attempts") - onError?.invoke("Port 8080 is blocked by another process.") + runOnMain { onError?.invoke("Port 8080 is blocked.") } } } } @@ -411,24 +195,14 @@ class RemoteControlServer(private val context: Context) { val oldScope = serverScope oldScope.launch { lifecycleMutex.withLock { - stopInternal() + server?.let { + Log.i("RemoteControlServer", "Stopping server...") + it.stop(500, 2000) + server = null + } } oldScope.cancel() } serverScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) } - - private fun stopInternal() { - val s = server - server = null - if (s != null) { - try { - Log.i("RemoteControlServer", "Stopping server...") - s.stop(500, 2000) // Higher grace period and timeout - Log.i("RemoteControlServer", "Server stopped") - } catch (e: Exception) { - Log.e("RemoteControlServer", "Error stopping server", e) - } - } - } } diff --git a/app/src/main/java/com/michatec/radio/remote/AuthPlugin.kt b/app/src/main/java/com/michatec/radio/remote/AuthPlugin.kt new file mode 100644 index 0000000..155c297 --- /dev/null +++ b/app/src/main/java/com/michatec/radio/remote/AuthPlugin.kt @@ -0,0 +1,52 @@ +package com.michatec.radio.remote + +import io.ktor.http.* +import io.ktor.server.application.* +import io.ktor.server.request.* +import io.ktor.server.response.* +import kotlinx.coroutines.delay +import java.util.concurrent.ConcurrentHashMap +import kotlin.time.Duration.Companion.milliseconds +import com.michatec.radio.helpers.PreferencesHelper + +class AuthConfiguration { + var onAuthFailed: ((String) -> Unit)? = null +} + +val RemoteAuthPlugin = createApplicationPlugin(name = "RemoteAuthPlugin", createConfiguration = ::AuthConfiguration) { + val failedAttemptsMap = ConcurrentHashMap() + val onAuthFailed = pluginConfig.onAuthFailed + + onCall { call -> + val authEnabled = PreferencesHelper.loadRemoteControlAuthEnabled() + if (!authEnabled) return@onCall + + val requestPath = call.request.path() + val isStatic = (requestPath == RemoteConstants.Routes.ROOT) || + (requestPath == RemoteConstants.Routes.STYLE) || + (requestPath == RemoteConstants.Routes.SCRIPT) || + (requestPath == RemoteConstants.Routes.FAVICON) || + (requestPath == RemoteConstants.Routes.TRANSLATIONS) + + if (isStatic) return@onCall + + val secret = PreferencesHelper.loadRemoteControlSecretToken() + val providedKey = call.request.headers[RemoteConstants.Auth.HEADER_KEY] + ?: call.request.queryParameters[RemoteConstants.Auth.QUERY_PARAM_TOKEN] + val remoteHost = call.request.local.remoteHost + + if (providedKey != secret) { + val attempts = (failedAttemptsMap[remoteHost] ?: 0) + 1 + failedAttemptsMap[remoteHost] = attempts + + if (attempts >= RemoteConstants.Auth.MAX_FAILED_ATTEMPTS) { + onAuthFailed?.invoke(remoteHost) + } + + delay(2000.milliseconds) + call.respond(HttpStatusCode.Unauthorized, ErrorResponse("Unauthorized")) + } else { + failedAttemptsMap.remove(remoteHost) + } + } +} diff --git a/app/src/main/java/com/michatec/radio/remote/KtorExtensions.kt b/app/src/main/java/com/michatec/radio/remote/KtorExtensions.kt new file mode 100644 index 0000000..bafb53e --- /dev/null +++ b/app/src/main/java/com/michatec/radio/remote/KtorExtensions.kt @@ -0,0 +1,20 @@ +package com.michatec.radio.remote + +import android.content.Context +import io.ktor.http.* +import io.ktor.server.application.* +import io.ktor.server.response.* +import android.util.Log + +suspend fun ApplicationCall.respondAsset(context: Context, path: String, contentType: ContentType) { + try { + val bytes = context.assets.open(path).use { it.readBytes() } + if (contentType == ContentType.Text.Html) { + response.header(HttpHeaders.CacheControl, "no-cache, no-store, must-revalidate") + } + respondBytes(bytes, contentType) + } catch (e: Exception) { + Log.e("RemoteControlServer", "Failed to read asset: $path", e) + respond(HttpStatusCode.NotFound) + } +} diff --git a/app/src/main/java/com/michatec/radio/remote/RemoteConstants.kt b/app/src/main/java/com/michatec/radio/remote/RemoteConstants.kt new file mode 100644 index 0000000..ac869f1 --- /dev/null +++ b/app/src/main/java/com/michatec/radio/remote/RemoteConstants.kt @@ -0,0 +1,37 @@ +package com.michatec.radio.remote + +object RemoteConstants { + const val PORT = 8080 + const val HOST = "0.0.0.0" + + object Routes { + const val ROOT = "/" + const val STYLE = "/style.css" + const val SCRIPT = "/script.js" + const val TRANSLATIONS = "/translations.json" + const val FAVICON = "/favicon.png" + + const val API_CONFIG = "/api/config" + const val API_STATUS = "/api/status" + const val API_STATIONS = "/api/stations" + const val API_UPDATES = "/api/updates" + const val API_IMAGE = "/api/image/{uuid}" + + const val API_PLAY = "/api/play/{uuid}" + const val API_PAUSE = "/api/pause" + const val API_RESUME = "/api/resume" + const val API_NEXT = "/api/next" + const val API_PREV = "/api/prev" + } + + object Auth { + const val HEADER_KEY = "X-Remote-Key" + const val QUERY_PARAM_TOKEN = "token" + const val MAX_FAILED_ATTEMPTS = 10 + } + + object WebSocket { + const val TYPE_STATUS = "status" + const val TYPE_STATIONS = "stations" + } +} diff --git a/app/src/main/java/com/michatec/radio/remote/RemoteDtos.kt b/app/src/main/java/com/michatec/radio/remote/RemoteDtos.kt new file mode 100644 index 0000000..9c92309 --- /dev/null +++ b/app/src/main/java/com/michatec/radio/remote/RemoteDtos.kt @@ -0,0 +1,35 @@ +package com.michatec.radio.remote + +data class ConfigResponse( + val version: String +) + +data class StatusResponse( + val isPlaying: Boolean, + val playWhenReady: Boolean, + val playbackState: Int, + val currentStationUuid: String, + val metadata: String, + val starred: Boolean +) + +data class StationDto( + val uuid: String, + val name: String, + val hasImage: Boolean, + val starred: Boolean, + val lastModified: Long +) + +data class WebSocketMessage( + val type: String, + val data: Any +) + +data class ErrorResponse( + val error: String +) + +data class GenericResponse( + val status: String = "ok" +) diff --git a/app/src/main/java/com/michatec/radio/remote/RemoteRoutes.kt b/app/src/main/java/com/michatec/radio/remote/RemoteRoutes.kt new file mode 100644 index 0000000..a4a2a61 --- /dev/null +++ b/app/src/main/java/com/michatec/radio/remote/RemoteRoutes.kt @@ -0,0 +1,140 @@ +package com.michatec.radio.remote + +import android.content.Context +import com.google.gson.Gson +import com.michatec.radio.BuildConfig +import com.michatec.radio.helpers.CollectionHelper +import com.michatec.radio.helpers.FileHelper +import com.michatec.radio.remote.RemoteConstants.Routes +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.server.response.header +import io.ktor.server.response.respond +import io.ktor.server.response.respondBytes +import io.ktor.server.routing.Routing +import io.ktor.server.routing.get +import io.ktor.server.routing.post +import io.ktor.server.websocket.webSocket +import io.ktor.websocket.Frame +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File + +class RemoteRoutes( + private val context: Context, + private val gson: Gson, + private val getStatus: suspend () -> StatusResponse?, + private val getStations: suspend () -> List, + private val statusUpdates: SharedFlow, + private val onAction: suspend (String, String?) -> Unit, +) { + + fun Routing.installRoutes() { + // Static Content + get(Routes.ROOT) { call.respondAsset(context, "web/index.html", ContentType.Text.Html) } + get(Routes.STYLE) { call.respondAsset(context, "web/style.css", ContentType.Text.CSS) } + get(Routes.SCRIPT) { call.respondAsset(context, "web/script.js", ContentType.Application.JavaScript) } + get(Routes.TRANSLATIONS) { call.respondAsset(context, "web/translations.json", ContentType.Application.Json) } + get(Routes.FAVICON) { call.respondAsset(context, "web/favicon.png", ContentType.Image.PNG) } + + // API + get(Routes.API_CONFIG) { + call.respond(ConfigResponse(BuildConfig.VERSION_NAME)) + } + + get(Routes.API_STATUS) { + val status = getStatus() + if (status == null) { + call.respond(HttpStatusCode.ServiceUnavailable, ErrorResponse("Player not available")) + } else { + call.respond(status) + } + } + + get(Routes.API_STATIONS) { + call.respond(getStations()) + } + + get(Routes.API_IMAGE) { + val uuid = call.parameters["uuid"] ?: return@get call.respond(HttpStatusCode.BadRequest) + try { + val collection = withContext(Dispatchers.IO) { FileHelper.readCollection(context) } + val station = CollectionHelper.getStation(collection, uuid) + + if (station.smallImage.isNotEmpty()) { + val imageFile = File(context.getExternalFilesDir(""), FileHelper.determineDestinationFolderPath(com.michatec.radio.Keys.FILE_TYPE_IMAGE, uuid) + "/" + com.michatec.radio.Keys.STATION_IMAGE_FILE) + if (imageFile.exists()) { + val lastModified = imageFile.lastModified() + val etag = "W/\"$lastModified-${imageFile.length()}\"" + + if (call.request.headers[HttpHeaders.IfNoneMatch] == etag) { + call.respond(HttpStatusCode.NotModified) + } else { + call.response.header(HttpHeaders.CacheControl, "public, max-age=86400") + call.response.header(HttpHeaders.ETag, etag) + call.respondBytes(imageFile.readBytes(), ContentType.Image.JPEG) + } + } else { + call.respond(HttpStatusCode.NotFound) + } + } else { + call.respond(HttpStatusCode.NotFound) + } + } catch (_: Exception) { + call.respond(HttpStatusCode.InternalServerError) + } + } + + // WebSockets + webSocket(Routes.API_UPDATES) { + try { + getStatus()?.let { send(Frame.Text(gson.toJson(WebSocketMessage(RemoteConstants.WebSocket.TYPE_STATUS, it)))) } + send(Frame.Text(gson.toJson(WebSocketMessage(RemoteConstants.WebSocket.TYPE_STATIONS, getStations())))) + } catch (_: Exception) { } + + val job = launch { + statusUpdates.collect { update -> + try { + send(Frame.Text(gson.toJson(update))) + } catch (_: Exception) { } + } + } + try { + for (frame in incoming) { /* Keep alive */ frame.takeIf { it is Frame.Text } ?: continue } + } catch (_: Exception) { + } finally { + job.cancel() + } + } + + // Control Actions + post(Routes.API_PLAY) { + val uuid = call.parameters["uuid"] ?: return@post call.respond(HttpStatusCode.BadRequest) + onAction("play", uuid) + call.respond(GenericResponse()) + } + + post(Routes.API_PAUSE) { + onAction("pause", null) + call.respond(GenericResponse()) + } + + post(Routes.API_RESUME) { + onAction("resume", null) + call.respond(GenericResponse()) + } + + post(Routes.API_NEXT) { + onAction("next", null) + call.respond(GenericResponse()) + } + + post(Routes.API_PREV) { + onAction("prev", null) + call.respond(GenericResponse()) + } + } +}