mirror of
https://github.com/Michatec/Radio.git
synced 2026-11-17 05:26:53 +01:00
feat: add web remote control with translations
- Implement embedded Ktor remote control server (port 8080) - Add REST API endpoints for play/pause/next/prev/status - Add web UI with localization support - Add remote control preference toggle and settings integration - Translate remote control strings to all supported languages
This commit is contained in:
1 parent
925a40fa08
commit
8fa73ff6f9
26 files changed
+1511
-8
No files matched your search
@@ -20,6 +20,7 @@ object Keys {
|
||||
const val ACTION_COLLECTION_CHANGED: String = "com.michatec.radio.action.COLLECTION_CHANGED"
|
||||
const val ACTION_THEME_CHANGED: String = "com.michatec.radio.action.THEME_CHANGED"
|
||||
const val ACTION_START: String = "com.michatec.radio.action.START"
|
||||
const val ACTION_REMOTE_SERVER_ERROR: String = "com.michatec.radio.action.REMOTE_SERVER_ERROR"
|
||||
|
||||
// intent extras
|
||||
const val EXTRA_COLLECTION_MODIFICATION_DATE: String = "COLLECTION_MODIFICATION_DATE"
|
||||
@@ -97,6 +98,7 @@ object Keys {
|
||||
const val PREF_CUSTOM_THEME_ENABLED: String = "CUSTOM_THEME_ENABLED"
|
||||
const val PREF_CUSTOM_THEME_INDEX: String = "CUSTOM_THEME_INDEX"
|
||||
const val PREF_ARGUMENTS: String = "ARGUMENTS"
|
||||
const val PREF_REMOTE_CONTROL_ENABLED: String = "REMOTE_CONTROL_ENABLED"
|
||||
|
||||
// default const values
|
||||
const val DEFAULT_SIZE_OF_METADATA_HISTORY: Int = 25
|
||||
|
||||
@@ -20,10 +20,12 @@ import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.appcompat.widget.Toolbar
|
||||
import androidx.core.app.ActivityCompat
|
||||
import androidx.core.view.isVisible
|
||||
import androidx.localbroadcastmanager.content.LocalBroadcastManager
|
||||
import androidx.navigation.fragment.NavHostFragment
|
||||
import androidx.navigation.ui.AppBarConfiguration
|
||||
import androidx.navigation.ui.NavigationUI
|
||||
import androidx.navigation.ui.navigateUp
|
||||
import android.content.*
|
||||
import com.google.android.material.snackbar.Snackbar
|
||||
import com.michatec.radio.helpers.AppThemeHelper
|
||||
import com.michatec.radio.helpers.FileHelper
|
||||
@@ -132,6 +134,21 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
// register remote server error receiver
|
||||
LocalBroadcastManager.getInstance(this).registerReceiver(
|
||||
remoteServerErrorReceiver,
|
||||
IntentFilter(Keys.ACTION_REMOTE_SERVER_ERROR)
|
||||
)
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
super.onStop()
|
||||
// unregister remote server error receiver
|
||||
LocalBroadcastManager.getInstance(this).unregisterReceiver(remoteServerErrorReceiver)
|
||||
}
|
||||
|
||||
/* Hides the loading/splash overlay */
|
||||
private fun hideLoadingOverlay() {
|
||||
findViewById<View>(R.id.loading_layout)?.let { overlay ->
|
||||
@@ -220,6 +237,24 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Receiver for remote server error
|
||||
*/
|
||||
private val remoteServerErrorReceiver: BroadcastReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
if (intent.action == Keys.ACTION_REMOTE_SERVER_ERROR) {
|
||||
val snackbar = Snackbar.make(
|
||||
findViewById(R.id.main_root),
|
||||
R.string.error_webserver,
|
||||
Snackbar.LENGTH_LONG
|
||||
)
|
||||
snackbar.anchorView = findViewById(R.id.bottom_sheet)
|
||||
snackbar.show()
|
||||
}
|
||||
}
|
||||
}
|
||||
/*
|
||||
* End of declaration
|
||||
*/
|
||||
|
||||
@@ -60,6 +60,33 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc
|
||||
private var playLastStation: Boolean = false
|
||||
private var manuallyCancelledSleepTimer = false
|
||||
|
||||
private val remoteControlServer: RemoteControlServer by lazy {
|
||||
RemoteControlServer(this).apply {
|
||||
onPlayStation = { uuid ->
|
||||
playStation(uuid)
|
||||
}
|
||||
onPause = {
|
||||
player.pause()
|
||||
}
|
||||
onResume = {
|
||||
player.play()
|
||||
}
|
||||
onNext = {
|
||||
playNextStation()
|
||||
}
|
||||
onPrev = {
|
||||
playPreviousStation()
|
||||
}
|
||||
|
||||
onError = { error ->
|
||||
Log.e(TAG, "RemoteControlServer error: $error")
|
||||
PreferencesHelper.saveRemoteControlEnabled(false)
|
||||
val intent = Intent(Keys.ACTION_REMOTE_SERVER_ERROR)
|
||||
LocalBroadcastManager.getInstance(this@PlayerService).sendBroadcast(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Native Audio Processor instance
|
||||
private val nativeAudioProcessor = NativeAudioProcessor()
|
||||
|
||||
@@ -77,6 +104,13 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc
|
||||
// initialize player and session
|
||||
initializePlayer()
|
||||
initializeSession()
|
||||
|
||||
// start remote control server if enabled
|
||||
if (PreferencesHelper.loadRemoteControlEnabled()) {
|
||||
remoteControlServer.setPlayer(player)
|
||||
remoteControlServer.start()
|
||||
}
|
||||
|
||||
val notificationProvider: DefaultMediaNotificationProvider = CustomNotificationProvider()
|
||||
notificationProvider.setSmallIcon(R.drawable.ic_notification_app_icon_white_24dp)
|
||||
setMediaNotificationProvider(notificationProvider)
|
||||
@@ -105,6 +139,12 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc
|
||||
}
|
||||
|
||||
|
||||
/* Overrides onStartCommand from Service */
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
super.onStartCommand(intent, flags, startId)
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
/* Overrides onTaskRemoved from Service */
|
||||
override fun onTaskRemoved(rootIntent: Intent?) {
|
||||
if (!player.playWhenReady) {
|
||||
@@ -369,6 +409,14 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc
|
||||
castPlayer.volume = 1f
|
||||
}
|
||||
}
|
||||
Keys.PREF_REMOTE_CONTROL_ENABLED -> {
|
||||
if (PreferencesHelper.loadRemoteControlEnabled()) {
|
||||
remoteControlServer.setPlayer(player)
|
||||
remoteControlServer.start()
|
||||
} else {
|
||||
remoteControlServer.stop()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,6 +442,13 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc
|
||||
}
|
||||
}
|
||||
|
||||
/* Starts playback of a radio station by UUID (centralized logic) */
|
||||
fun playStation(uuid: String) {
|
||||
val station = CollectionHelper.getStation(collection, uuid)
|
||||
if (station.isValid()) {
|
||||
playStation(station)
|
||||
}
|
||||
}
|
||||
|
||||
/* Starts playback of a radio station */
|
||||
private fun playStation(station: Station) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
@@ -13,21 +14,31 @@ import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.net.toUri
|
||||
import androidx.media3.common.util.UnstableApi
|
||||
import androidx.navigation.fragment.findNavController
|
||||
import androidx.preference.*
|
||||
import androidx.preference.EditTextPreference
|
||||
import androidx.preference.Preference
|
||||
import androidx.preference.PreferenceCategory
|
||||
import androidx.preference.PreferenceFragmentCompat
|
||||
import com.google.android.material.snackbar.Snackbar
|
||||
import com.michatec.radio.dialogs.ErrorDialog
|
||||
import com.michatec.radio.dialogs.LanguageSelectionDialog
|
||||
import com.michatec.radio.dialogs.PresetSelectionDialog
|
||||
import com.michatec.radio.dialogs.ThemeSelectionDialog
|
||||
import com.michatec.radio.dialogs.YesNoDialog
|
||||
import com.michatec.radio.helpers.*
|
||||
import android.content.pm.PackageManager
|
||||
import com.michatec.radio.helpers.AppThemeHelper
|
||||
import com.michatec.radio.helpers.BackupHelper
|
||||
import com.michatec.radio.helpers.FileHelper
|
||||
import com.michatec.radio.helpers.LanguageHelper
|
||||
import com.michatec.radio.helpers.MarqueeSwitchPreference
|
||||
import com.michatec.radio.helpers.NetworkHelper
|
||||
import com.michatec.radio.helpers.PreferencesHelper
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers.IO
|
||||
import kotlinx.coroutines.launch
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
|
||||
/*
|
||||
@@ -59,6 +70,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
|
||||
}
|
||||
|
||||
/* Overrides onCreatePreferences from PreferenceFragmentCompat */
|
||||
@UnstableApi
|
||||
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
|
||||
|
||||
val context = preferenceManager.context
|
||||
@@ -182,6 +194,29 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
|
||||
PreferencesHelper.loadEditStreamUrisEnabled(context)
|
||||
}
|
||||
|
||||
// set up "Remote Control" preference
|
||||
val preferenceRemoteControl = MarqueeSwitchPreference(context)
|
||||
preferenceRemoteControl.title = getString(R.string.pref_remote_control_title)
|
||||
preferenceRemoteControl.setIcon(R.drawable.ic_network_check_24dp)
|
||||
preferenceRemoteControl.key = Keys.PREF_REMOTE_CONTROL_ENABLED
|
||||
val localIp = NetworkHelper.getLocalIpAddress(context)
|
||||
preferenceRemoteControl.summary = if (localIp != null) {
|
||||
getString(R.string.pref_remote_control_url, localIp)
|
||||
} else {
|
||||
getString(R.string.pref_remote_control_summary)
|
||||
}
|
||||
preferenceRemoteControl.setDefaultValue(PreferencesHelper.loadRemoteControlEnabled())
|
||||
preferenceRemoteControl.setOnPreferenceChangeListener { _, newValue ->
|
||||
val enabled = newValue as Boolean
|
||||
if (enabled) {
|
||||
val intent = Intent(activity, PlayerService::class.java).apply {
|
||||
action = Keys.ACTION_START
|
||||
}
|
||||
activity?.startService(intent)
|
||||
}
|
||||
return@setOnPreferenceChangeListener true
|
||||
}
|
||||
|
||||
// set up "Arguments" preference
|
||||
val preferenceArguments = EditTextPreference(context)
|
||||
preferenceArguments.title = getString(R.string.pref_arguments_title)
|
||||
@@ -501,6 +536,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList
|
||||
preferenceCategoryAdvanced.addPreference(preferenceBufferSize)
|
||||
preferenceCategoryAdvanced.addPreference(preferenceEnableEditingGeneral)
|
||||
preferenceCategoryAdvanced.addPreference(preferenceEnableEditingStreamUri)
|
||||
preferenceCategoryAdvanced.addPreference(preferenceRemoteControl)
|
||||
preferenceCategoryAdvanced.addPreference(preferenceArguments)
|
||||
|
||||
screen.addPreference(preferenceCategoryLinks)
|
||||
|
||||
@@ -34,6 +34,21 @@ object NetworkHelper {
|
||||
}
|
||||
|
||||
|
||||
/* Gets the IP address of the device on the local network */
|
||||
fun getLocalIpAddress(context: Context): String? {
|
||||
val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val activeNetwork: Network = connMgr.activeNetwork ?: return null
|
||||
val linkProperties = connMgr.getLinkProperties(activeNetwork) ?: return null
|
||||
for (linkAddress in linkProperties.linkAddresses) {
|
||||
val address = linkAddress.address
|
||||
if (!address.isLoopbackAddress && address is InetAddress && address.hostAddress?.contains(":") == false) {
|
||||
return address.hostAddress
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
|
||||
/* Detects content type (mime type) from given URL string - async using coroutine - use only on separate threat */
|
||||
fun detectContentType(urlString: String): ContentType {
|
||||
Log.v(TAG, "Determining content type - Thread: ${Thread.currentThread().name}")
|
||||
|
||||
@@ -406,6 +406,18 @@ object PreferencesHelper {
|
||||
return arguments.any { it.lowercase().sha256() == targetHash }
|
||||
}
|
||||
|
||||
/* Loads whether remote control is enabled */
|
||||
fun loadRemoteControlEnabled(): Boolean {
|
||||
return sharedPreferences.getBoolean(Keys.PREF_REMOTE_CONTROL_ENABLED, false)
|
||||
}
|
||||
|
||||
/* Saves whether remote control is enabled */
|
||||
fun saveRemoteControlEnabled(enabled: Boolean) {
|
||||
sharedPreferences.edit {
|
||||
putBoolean(Keys.PREF_REMOTE_CONTROL_ENABLED, enabled)
|
||||
}
|
||||
}
|
||||
|
||||
/* SHA-256 helper */
|
||||
private fun String.sha256(): String {
|
||||
return try {
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
package com.michatec.radio.helpers
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.media3.common.Player
|
||||
import com.michatec.radio.BuildConfig
|
||||
import io.ktor.http.*
|
||||
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.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import kotlinx.coroutines.*
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import java.io.File
|
||||
import java.net.BindException
|
||||
import kotlin.time.Duration.Companion.milliseconds
|
||||
|
||||
class RemoteControlServer(private val context: Context) {
|
||||
|
||||
private var server: EmbeddedServer<NettyApplicationEngine, NettyApplicationEngine.Configuration>? = null
|
||||
private var player: Player? = null
|
||||
private val serverScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||
private val lifecycleMutex = Mutex()
|
||||
var onPlayStation: ((String) -> Unit)? = null
|
||||
var onPause: (() -> Unit)? = null
|
||||
var onResume: (() -> Unit)? = null
|
||||
var onNext: (() -> Unit)? = null
|
||||
var onPrev: (() -> Unit)? = null
|
||||
var onError: ((String) -> Unit)? = null
|
||||
|
||||
fun setPlayer(player: Player?) {
|
||||
this.player = player
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
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 p = player
|
||||
if (p == null) {
|
||||
call.respond(HttpStatusCode.ServiceUnavailable, mapOf("error" to "Player not available"))
|
||||
} else {
|
||||
try {
|
||||
val status = withContext(Dispatchers.Main) {
|
||||
val metadataHistory = PreferencesHelper.loadMetadataHistory()
|
||||
val currentTrack = if (metadataHistory.isNotEmpty()) metadataHistory.last() else ""
|
||||
val mediaId = p.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid()
|
||||
|
||||
mapOf(
|
||||
"isPlaying" to p.isPlaying,
|
||||
"playbackState" to p.playbackState,
|
||||
"currentStationUuid" to mediaId,
|
||||
"metadata" to currentTrack
|
||||
)
|
||||
}
|
||||
call.respond(status)
|
||||
} catch (e: Exception) {
|
||||
call.respond(HttpStatusCode.InternalServerError, mapOf("error" to e.message))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get("/api/stations") {
|
||||
try {
|
||||
val collection = withContext(Dispatchers.IO) {
|
||||
FileHelper.readCollection(context)
|
||||
}
|
||||
val simplifiedStations = collection.stations.map {
|
||||
mapOf(
|
||||
"uuid" to it.uuid,
|
||||
"name" to it.name,
|
||||
"hasImage" to it.smallImage.isNotEmpty()
|
||||
)
|
||||
}
|
||||
call.respond(simplifiedStations)
|
||||
} 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()) {
|
||||
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"))
|
||||
}
|
||||
}
|
||||
}
|
||||
server = newServer
|
||||
newServer.start(wait = false)
|
||||
Log.i("RemoteControlServer", "Server successfully started on port 8080")
|
||||
return@withLock
|
||||
} catch (e: Exception) {
|
||||
if (e is BindException || e.cause is BindException) {
|
||||
Log.w("RemoteControlServer", "Port 8080 busy, retrying in 1s...")
|
||||
delay(1000.milliseconds)
|
||||
attempt++
|
||||
} else {
|
||||
Log.e("RemoteControlServer", "Critical server error", e)
|
||||
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.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
serverScope.launch {
|
||||
lifecycleMutex.withLock {
|
||||
stopInternal()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopInternal() {
|
||||
val s = server
|
||||
server = null
|
||||
if (s != null) {
|
||||
try {
|
||||
Log.i("RemoteControlServer", "Stopping server...")
|
||||
s.stop(50, 100)
|
||||
Log.i("RemoteControlServer", "Server stopped")
|
||||
} catch (e: Exception) {
|
||||
Log.e("RemoteControlServer", "Error stopping server", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user