Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class DeeprApplication : Application() {
}

single<LocalServerRepository> {
LocalServerRepositoryImpl(androidContext(), get(), get(), get())
LocalServerRepositoryImpl(androidContext(), get(), get(), get(), get())
}

viewModel {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class AppPreferenceDataStore(
private val LAST_BACKUP_TIME = longPreferencesKey("last_backup_time")
private val DEFAULT_PAGE_FAVOURITES = booleanPreferencesKey("default_page_favourites")
private val IS_THUMBNAIL_ENABLE = booleanPreferencesKey("is_thumbnail_enable")
private val SERVER_PORT = stringPreferencesKey("server_port")
}

val getSortingOrder: Flow<@SortType String> =
Expand Down Expand Up @@ -87,6 +88,11 @@ class AppPreferenceDataStore(
preferences[IS_THUMBNAIL_ENABLE] ?: false
}

val getServerPort: Flow<String> =
context.appDataStore.data.map { preferences ->
preferences[SERVER_PORT] ?: "" // Default to empty string
}

suspend fun setSortingOrder(order: @SortType String) {
context.appDataStore.edit { prefs ->
prefs[SORTING_ORDER] = order
Expand Down Expand Up @@ -158,4 +164,10 @@ class AppPreferenceDataStore(
prefs[IS_THUMBNAIL_ENABLE] = thumbnail
}
}

suspend fun setServerPort(port: String) {
context.appDataStore.edit { prefs ->
prefs[SERVER_PORT] = port
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import kotlinx.coroutines.flow.StateFlow
interface LocalServerRepository {
val isRunning: StateFlow<Boolean>
val serverUrl: StateFlow<String?>
val serverPort: StateFlow<Int>

suspend fun startServer()

suspend fun stopServer()

suspend fun setServerPort(port: Int)
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import android.net.wifi.WifiManager
import android.util.Log
import com.yogeshpaliyal.deepr.DeeprQueries
import com.yogeshpaliyal.deepr.data.NetworkRepository
import com.yogeshpaliyal.deepr.preference.AppPreferenceDataStore
import com.yogeshpaliyal.deepr.viewmodel.AccountViewModel
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
Expand All @@ -21,9 +22,12 @@ import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.net.NetworkInterface
Expand All @@ -34,6 +38,7 @@ class LocalServerRepositoryImpl(
private val deeprQueries: DeeprQueries,
private val accountViewModel: AccountViewModel,
private val networkRepository: NetworkRepository,
private val preferenceDataStore: AppPreferenceDataStore,
) : LocalServerRepository {
private var server: EmbeddedServer<CIOApplicationEngine, CIOApplicationEngine.Configuration>? = null
private val _isRunning = MutableStateFlow(false)
Expand All @@ -42,7 +47,29 @@ class LocalServerRepositoryImpl(
private val _serverUrl = MutableStateFlow<String?>(null)
override val serverUrl: StateFlow<String?> = _serverUrl.asStateFlow()

private val port = 8080
private val _serverPort = MutableStateFlow(8080)
override val serverPort: StateFlow<Int> = _serverPort.asStateFlow()

init {
// Load saved port on initialization
CoroutineScope(Dispatchers.IO).launch {
preferenceDataStore.getServerPort.collect { portString ->
val port = portString.toIntOrNull()
if (port != null && port in 1024..65535) {
_serverPort.value = port
} else {
_serverPort.value = 8080
}
}
}
}

override suspend fun setServerPort(port: Int) {
if (port in 1024..65535) {
_serverPort.value = port
preferenceDataStore.setServerPort(port.toString())
}
}

override suspend fun startServer() {
if (_isRunning.value) {
Expand All @@ -57,6 +84,8 @@ class LocalServerRepositoryImpl(
return
}

val port = _serverPort.value

server =
embeddedServer(CIO, host = "0.0.0.0", port = port) {
install(ContentNegotiation) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import compose.icons.TablerIcons
import compose.icons.tablericons.ArrowLeft
import compose.icons.tablericons.Copy
import compose.icons.tablericons.DeviceMobile
import compose.icons.tablericons.Edit
import compose.icons.tablericons.InfoCircle
import compose.icons.tablericons.Qrcode
import compose.icons.tablericons.Server
Expand All @@ -87,11 +88,17 @@ fun LocalNetworkServerScreen(
val hapticFeedback = LocalHapticFeedback.current
val isRunning by viewModel.isRunning.collectAsStateWithLifecycle()
val serverUrl by viewModel.serverUrl.collectAsStateWithLifecycle()
val serverPort by viewModel.serverPort.collectAsStateWithLifecycle()
val isRtl = LocalLayoutDirection.current == LayoutDirection.Rtl

// Track if user wants to start the server (used for permission flow)
var pendingStart by remember { mutableStateOf(false) }

// Port configuration dialog
var showPortDialog by remember { mutableStateOf(false) }
var portInput by remember { mutableStateOf("") }
var portError by remember { mutableStateOf(false) }

// Request notification permission for Android 13+
val notificationPermissionState =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
Expand Down Expand Up @@ -142,9 +149,19 @@ fun LocalNetworkServerScreen(
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
// Server Status Card

ServerSwitch(isRunning, { pendingStart = it }, notificationPermissionState)

// Port Configuration Card
PortConfigurationCard(
currentPort = serverPort,
isServerRunning = isRunning,
onChangePort = {
portInput = serverPort.toString()
portError = false
showPortDialog = true
},
)

// Server Details Section
AnimatedVisibility(
visible = isRunning && serverUrl != null,
Expand Down Expand Up @@ -328,14 +345,86 @@ fun LocalNetworkServerScreen(
}
}
}

// Port Configuration Dialog
if (showPortDialog) {
androidx.compose.material3.AlertDialog(
onDismissRequest = { showPortDialog = false },
title = { Text(stringResource(R.string.change_port)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = stringResource(R.string.port_range_hint),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
androidx.compose.material3.OutlinedTextField(
value = portInput,
onValueChange = {
portInput = it
portError = false
},
label = { Text(stringResource(R.string.port_number)) },
placeholder = { Text(stringResource(R.string.default_port)) },
isError = portError,
supportingText =
if (portError) {
{ Text(stringResource(R.string.invalid_port)) }
} else {
null
},
keyboardOptions =
androidx.compose.foundation.text.KeyboardOptions(
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number,
),
singleLine = true,
modifier = Modifier.fillMaxWidth(),
)
if (isRunning) {
Text(
text = stringResource(R.string.port_changed_restart),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.error,
)
}
}
},
confirmButton = {
androidx.compose.material3.TextButton(
onClick = {
val port = portInput.toIntOrNull()
if (port != null && port in 1024..65535) {
viewModel.setServerPort(port)
showPortDialog = false
Toast
.makeText(
context,
if (isRunning) context.getString(R.string.port_changed_restart) else context.getString(R.string.saved),
Toast.LENGTH_SHORT,
).show()
} else {
portError = true
}
},
) {
Text(stringResource(R.string.save))
}
},
dismissButton = {
androidx.compose.material3.TextButton(onClick = { showPortDialog = false }) {
Text(stringResource(R.string.cancel))
}
},
)
}
}

@Preview()
@OptIn(ExperimentalPermissionsApi::class)
@Composable
private fun ServerSwitch(
isRunning: Boolean,
setPendingStart: (Boolean) -> Unit,
isRunning: Boolean = false,
setPendingStart: (Boolean) -> Unit = {},
notificationPermissionState: PermissionState? = null,
) {
val hapticFeedback = LocalHapticFeedback.current
Expand Down Expand Up @@ -568,3 +657,58 @@ private fun ApiEndpointItem(
}
}
}

@Composable
private fun PortConfigurationCard(
currentPort: Int,
isServerRunning: Boolean,
onChangePort: () -> Unit,
) {
val hapticFeedback = LocalHapticFeedback.current
Card(
modifier = Modifier.fillMaxWidth(),
colors =
CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.surfaceContainer,
),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(8.dp),
) {
Icon(
TablerIcons.Server,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(20.dp),
)
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.server_port),
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.SemiBold,
)
Text(
text = "$currentPort",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.Medium,
)
}
IconButton(
onClick = {
hapticFeedback.performHapticFeedback(HapticFeedbackType.LongPress)
onChangePort()
},
modifier = Modifier.size(40.dp),
) {
Icon(
TablerIcons.Edit,
contentDescription = stringResource(R.string.change_port),
tint = MaterialTheme.colorScheme.primary,
)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
package com.yogeshpaliyal.deepr.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yogeshpaliyal.deepr.server.LocalServerRepository
import kotlinx.coroutines.launch

class LocalServerViewModel(
localServerRepository: LocalServerRepository,
private val localServerRepository: LocalServerRepository,
) : ViewModel() {
val isRunning = localServerRepository.isRunning
val serverUrl = localServerRepository.serverUrl
val serverPort = localServerRepository.serverPort

fun setServerPort(port: Int) {
viewModelScope.launch {
localServerRepository.setServerPort(port)
}
}
}
8 changes: 8 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -205,4 +205,12 @@
<string name="local_server_notification_text">Server URL: %s</string>
<string name="local_server_starting">Starting server…</string>
<string name="stop">Stop</string>
<string name="server_port">Server Port</string>
<string name="custom_port">Custom Port</string>
<string name="port_number">Port Number</string>
<string name="default_port">Default: 8080</string>
<string name="port_range_hint">Enter port (1024-65535)</string>
<string name="invalid_port">Invalid port number. Must be between 1024 and 65535.</string>
<string name="port_changed_restart">Port changed. Please restart the server to apply changes.</string>
<string name="change_port">Change Port</string>
</resources>