refactor(profiles): per-profile config with atomic server apply
Маршрутизирует чтение/запись клиентского конфига через конкретный профиль by-id либо legacy (онбординг). Добавляет applyServerConfig() — атомарное применение proxy-адресов, tcp-проброса, obf-профиля и ключа за одну транзакцию с единственным рестартом сервера/прокси. Вводит ServerHubStatus для агрегированного состояния серверного хаба. Удаляет ставшие мёртвыми после рефактора одиночные сеттеры (setDnsMode, setUseUdp, setObfProfile, setTcpForward и др.), приватный persistServer и неиспользуемые флоу/символы (ProxyViewModel.clientConfig/proxyListen/ proxyConnect, serverInstallStage, TunnelTransport.ALL, profilesFlow и пр.). Legacy-миграция transport: WIREGUARD с пустым конфигом нормализуется в NONE.
This commit is contained in:
1 parent
5faf1eb90e
commit
c339d91b78
8 files changed
+128
-181
No files matched your search
@@ -41,7 +41,6 @@ object ProxyServiceState {
|
||||
val logs: StateFlow<List<String>> = _logs.asStateFlow()
|
||||
|
||||
private val _logsEnabled = MutableStateFlow(true)
|
||||
val logsEnabled: StateFlow<Boolean> = _logsEnabled.asStateFlow()
|
||||
|
||||
private val _proxyFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
|
||||
val proxyFailed: SharedFlow<Unit> = _proxyFailed.asSharedFlow()
|
||||
|
||||
@@ -14,7 +14,6 @@ import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.catch
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import androidx.core.content.edit
|
||||
|
||||
@@ -56,10 +55,10 @@ object ObfProfile {
|
||||
* прокси, так что трафик устройства идёт через TURN-релей.
|
||||
*/
|
||||
object TunnelTransport {
|
||||
const val NONE = "none"
|
||||
const val WIREGUARD = "wireguard"
|
||||
/** Имя WG-туннеля по умолчанию (GoBackend). */
|
||||
const val DEFAULT_TUNNEL_NAME = "freeturn-wg"
|
||||
val ALL = listOf(WIREGUARD)
|
||||
val PERSISTED = listOf(NONE, WIREGUARD)
|
||||
}
|
||||
|
||||
/** Режим split-tunneling для WireGuard-интерфейса. */
|
||||
@@ -107,8 +106,8 @@ data class ClientConfig(
|
||||
val magicSwitch: Boolean = false,
|
||||
/** Адрес для флага -turn ядра, если magicSwitch включён. Пусто = не передавать. */
|
||||
val magicTurn: String = "",
|
||||
/** Транспорт туннельного приложения (пока только WireGuard). */
|
||||
val tunnelTransport: String = TunnelTransport.WIREGUARD,
|
||||
/** Транспорт туннеля: NONE (proxy) либо WIREGUARD (VPN). По умолчанию — без туннеля. */
|
||||
val tunnelTransport: String = TunnelTransport.NONE,
|
||||
/** Конфиг WireGuard (.conf). Пусто = WG-туннель не поднимается. */
|
||||
val wireGuardConfig: String = "",
|
||||
/** Имя WG-туннеля для GoBackend. */
|
||||
@@ -227,8 +226,12 @@ class AppPreferences(context: Context) {
|
||||
syncServerSwitches = prefs[CLIENT_SYNC_SERVER] ?: true,
|
||||
magicSwitch = prefs[CLIENT_MAGIC_SWITCH] ?: false,
|
||||
magicTurn = prefs[CLIENT_MAGIC_TURN] ?: "",
|
||||
tunnelTransport = (prefs[CLIENT_TUNNEL_TRANSPORT] ?: TunnelTransport.WIREGUARD).let {
|
||||
if (it in TunnelTransport.ALL) it else TunnelTransport.WIREGUARD
|
||||
tunnelTransport = (prefs[CLIENT_TUNNEL_TRANSPORT] ?: TunnelTransport.NONE).let {
|
||||
val t = if (it in TunnelTransport.PERSISTED) it else TunnelTransport.NONE
|
||||
// Legacy: старый ClientSetup всегда писал WIREGUARD; пустой конфиг = туннель
|
||||
// не выбран → читаем как NONE (proxy), чтобы режим не показывался как VPN.
|
||||
if (t == TunnelTransport.WIREGUARD && prefs[CLIENT_WG_CONFIG].isNullOrBlank())
|
||||
TunnelTransport.NONE else t
|
||||
},
|
||||
wireGuardConfig = prefs[CLIENT_WG_CONFIG] ?: "",
|
||||
wireGuardTunnelName = (prefs[CLIENT_WG_TUNNEL_NAME] ?: TunnelTransport.DEFAULT_TUNNEL_NAME)
|
||||
@@ -293,14 +296,6 @@ class AppPreferences(context: Context) {
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs -> prefs[TG_SUBSCRIBE_SHOWN] ?: false }
|
||||
|
||||
val profilesFlow: Flow<List<Profile>> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs -> ProfileJson.decodeList(prefs[PROFILES_JSON]) }
|
||||
|
||||
val activeProfileIdFlow: Flow<String?> = context.dataStore.data
|
||||
.catch { if (it is IOException) emit(emptyPreferences()) else throw it }
|
||||
.map { prefs -> prefs[ACTIVE_PROFILE_ID]?.takeIf { it.isNotBlank() } }
|
||||
|
||||
/** Заменяет весь список профилей. */
|
||||
suspend fun saveProfiles(list: List<Profile>) {
|
||||
context.dataStore.edit { prefs ->
|
||||
@@ -358,8 +353,8 @@ class AppPreferences(context: Context) {
|
||||
prefs[CLIENT_MAGIC_SWITCH] = config.magicSwitch
|
||||
prefs[CLIENT_MAGIC_TURN] = config.magicTurn.trim()
|
||||
prefs[CLIENT_TUNNEL_TRANSPORT] =
|
||||
if (config.tunnelTransport in TunnelTransport.ALL) config.tunnelTransport
|
||||
else TunnelTransport.WIREGUARD
|
||||
if (config.tunnelTransport in TunnelTransport.PERSISTED) config.tunnelTransport
|
||||
else TunnelTransport.NONE
|
||||
prefs[CLIENT_WG_CONFIG] = config.wireGuardConfig.trim()
|
||||
prefs[CLIENT_WG_TUNNEL_NAME] =
|
||||
config.wireGuardTunnelName.trim().ifBlank { TunnelTransport.DEFAULT_TUNNEL_NAME }
|
||||
|
||||
@@ -134,8 +134,11 @@ internal object ProfileJson {
|
||||
syncServerSwitches = cliO.optBoolean("syncServerSwitches", true),
|
||||
magicSwitch = cliO.optBoolean("magicSwitch", false),
|
||||
magicTurn = cliO.optString("magicTurn"),
|
||||
tunnelTransport = cliO.optString("tunnelTransport", TunnelTransport.WIREGUARD).let {
|
||||
if (it in TunnelTransport.ALL) it else TunnelTransport.WIREGUARD
|
||||
tunnelTransport = cliO.optString("tunnelTransport", TunnelTransport.NONE).let {
|
||||
val t = if (it in TunnelTransport.PERSISTED) it else TunnelTransport.NONE
|
||||
// Legacy: WIREGUARD c пустым конфигом = туннель не выбран → NONE (proxy).
|
||||
if (t == TunnelTransport.WIREGUARD && cliO.optString("wireGuardConfig").isBlank())
|
||||
TunnelTransport.NONE else t
|
||||
},
|
||||
wireGuardConfig = cliO.optString("wireGuardConfig"),
|
||||
wireGuardTunnelName = cliO.optString("wireGuardTunnelName").ifBlank { TunnelTransport.DEFAULT_TUNNEL_NAME },
|
||||
|
||||
@@ -17,7 +17,6 @@ import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -214,8 +213,4 @@ class LocalProxyManager(private val context: Context) {
|
||||
fun clearState() {
|
||||
_proxyState.value = ProxyState.Idle
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
scope.cancel()
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,29 @@ sealed class ServerState {
|
||||
data class Error(val message: String) : ServerState()
|
||||
}
|
||||
|
||||
sealed interface ServerHubStatus {
|
||||
/** Профиль не активен: живой SSH/ядро принадлежат активному. Предлагаем активировать. */
|
||||
data class Offline(val serverAddress: String?, val sshIp: String?) : ServerHubStatus
|
||||
/** Активен, но SSH не настроен — нечего подключать. */
|
||||
data object NotPaired : ServerHubStatus
|
||||
/** Идёт подключение/проверка (единая busy-фаза, skeleton). */
|
||||
data object Connecting : ServerHubStatus
|
||||
/** Идёт серверное действие (старт/стоп/установка). */
|
||||
data class Working(val action: String) : ServerHubStatus
|
||||
/** SSH установлен и состояние ядра известно. */
|
||||
data class Online(
|
||||
val running: Boolean,
|
||||
val installed: Boolean,
|
||||
val tcpMode: Boolean?,
|
||||
val obfProfile: String?,
|
||||
val version: String?,
|
||||
val installStage: String?,
|
||||
val sshIp: String
|
||||
) : ServerHubStatus
|
||||
/** Ошибка SSH или серверной команды. */
|
||||
data class Failed(val message: String?) : ServerHubStatus
|
||||
}
|
||||
|
||||
// Local proxy client states
|
||||
sealed class ProxyState {
|
||||
object Idle : ProxyState()
|
||||
|
||||
@@ -4,12 +4,9 @@ import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.freeturn.app.ProxyServiceState
|
||||
import com.freeturn.app.data.AppPreferences
|
||||
import com.freeturn.app.data.ClientConfig
|
||||
import com.freeturn.app.domain.LocalProxyManager
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class ProxyViewModel(
|
||||
@@ -21,15 +18,6 @@ class ProxyViewModel(
|
||||
val connectedSince: StateFlow<Long?> = ProxyServiceState.connectedSince
|
||||
val logs: StateFlow<List<String>> = ProxyServiceState.logs
|
||||
|
||||
val clientConfig: StateFlow<ClientConfig> = prefs.clientConfigFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ClientConfig())
|
||||
|
||||
val proxyListen: StateFlow<String> = prefs.proxyListenFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "0.0.0.0:56000")
|
||||
|
||||
val proxyConnect: StateFlow<String> = prefs.proxyConnectFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "127.0.0.1:40537")
|
||||
|
||||
fun startProxy() {
|
||||
viewModelScope.launch {
|
||||
val config = prefs.clientConfigFlow.first()
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.freeturn.app.viewmodel
|
||||
import android.content.Context
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import com.freeturn.app.ProxyServiceState
|
||||
import com.freeturn.app.data.AppPreferences
|
||||
import com.freeturn.app.data.SshConfig
|
||||
import com.freeturn.app.domain.ProxyOrchestrator
|
||||
@@ -13,10 +12,11 @@ import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
class ServerViewModel(
|
||||
private val sshRepository: SshRepository,
|
||||
@@ -40,11 +40,37 @@ class ServerViewModel(
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig())
|
||||
|
||||
private val _serverInstallStage = MutableStateFlow<String?>(null)
|
||||
val serverInstallStage: StateFlow<String?> = _serverInstallStage.asStateFlow()
|
||||
|
||||
private val _isRegeneratingObfKey = MutableStateFlow(false)
|
||||
val isRegeneratingObfKey: StateFlow<Boolean> = _isRegeneratingObfKey.asStateFlow()
|
||||
|
||||
/**
|
||||
* Сводный статус АКТИВНОГО сервера для хаба — одна модель из 3 потоков. Profile-контекст
|
||||
* (активность профиля, наличие SSH) добавляет экран. Промежуточные фазы коллапсятся в
|
||||
* [ServerHubStatus.Connecting]: от cold start до готовности — один переход в [ServerHubStatus.Online].
|
||||
*/
|
||||
val hubStatus: StateFlow<ServerHubStatus> =
|
||||
combine(sshState, serverState, _serverInstallStage) { ssh, server, stage ->
|
||||
when {
|
||||
ssh is SshConnectionState.Error -> ServerHubStatus.Failed(ssh.message)
|
||||
server is ServerState.Error -> ServerHubStatus.Failed(server.message)
|
||||
server is ServerState.Working -> ServerHubStatus.Working(server.action)
|
||||
ssh is SshConnectionState.Connected && server is ServerState.Known ->
|
||||
ServerHubStatus.Online(
|
||||
running = server.running,
|
||||
installed = server.installed,
|
||||
tcpMode = server.tcpMode,
|
||||
obfProfile = server.obfProfile,
|
||||
version = server.version,
|
||||
installStage = stage,
|
||||
sshIp = ssh.ip
|
||||
)
|
||||
// Disconnected / Connecting / Connected+Checking → единый busy-визуал.
|
||||
else -> ServerHubStatus.Connecting
|
||||
}
|
||||
}.distinctUntilChanged()
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ServerHubStatus.Connecting)
|
||||
|
||||
fun connectSsh(config: SshConfig) {
|
||||
viewModelScope.launch {
|
||||
prefs.saveSshConfig(config)
|
||||
@@ -92,8 +118,6 @@ class ServerViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun consumeInstallStage() { _serverInstallStage.value = null }
|
||||
|
||||
fun startServer() {
|
||||
viewModelScope.launch {
|
||||
val l = prefs.proxyListenFlow.first()
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.freeturn.app.data.ClientConfig
|
||||
import com.freeturn.app.data.ObfProfile
|
||||
import com.freeturn.app.data.Profile
|
||||
import com.freeturn.app.data.ProfilesSnapshot
|
||||
import com.freeturn.app.data.SshConfig
|
||||
import com.freeturn.app.domain.AppUpdater
|
||||
import com.freeturn.app.domain.LocalProxyManager
|
||||
import com.freeturn.app.domain.ProxyOrchestrator
|
||||
@@ -53,9 +52,6 @@ class SettingsViewModel(
|
||||
val dynamicTheme: StateFlow<Boolean> = prefs.dynamicThemeFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), true)
|
||||
|
||||
val tgSubscribeShown: StateFlow<Boolean> = prefs.tgSubscribeShownFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
|
||||
|
||||
val profilesSnapshot: StateFlow<ProfilesSnapshot> = prefs.profilesSnapshot
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot())
|
||||
|
||||
@@ -70,9 +66,6 @@ class SettingsViewModel(
|
||||
private val _initialTgSubscribeShown = MutableStateFlow(false)
|
||||
val initialTgSubscribeShown: StateFlow<Boolean> = _initialTgSubscribeShown.asStateFlow()
|
||||
|
||||
val onboardingDone: StateFlow<Boolean> = prefs.onboardingDoneFlow
|
||||
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
|
||||
|
||||
private val _privacyMode = MutableStateFlow(false)
|
||||
val privacyMode: StateFlow<Boolean> = _privacyMode.asStateFlow()
|
||||
|
||||
@@ -134,66 +127,6 @@ class SettingsViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun setDnsMode(value: String) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
val current = prefs.clientConfigFlow.first()
|
||||
if (current.dnsMode == value) return@withLock
|
||||
persistClient(current.copy(dnsMode = value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setUseUdp(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
val current = prefs.clientConfigFlow.first()
|
||||
if (current.useUdp == enabled) return@withLock
|
||||
persistClient(current.copy(useUdp = enabled))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setManualCaptcha(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
val current = prefs.clientConfigFlow.first()
|
||||
if (current.manualCaptcha == enabled) return@withLock
|
||||
persistClient(current.copy(manualCaptcha = enabled))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setUseCarrierDns(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
val current = prefs.clientConfigFlow.first()
|
||||
if (current.useCarrierDns == enabled) return@withLock
|
||||
persistClient(current.copy(useCarrierDns = enabled))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setDebugMode(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
val current = prefs.clientConfigFlow.first()
|
||||
if (current.debugMode == enabled) return@withLock
|
||||
persistClient(current.copy(debugMode = enabled))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setMagicSwitch(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
val current = prefs.clientConfigFlow.first()
|
||||
if (current.magicSwitch == enabled) return@withLock
|
||||
persistClient(current.copy(magicSwitch = enabled))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun setSplitTunnelMode(value: String) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
@@ -215,17 +148,6 @@ class SettingsViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun setLogsEnabled(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
val current = prefs.clientConfigFlow.first()
|
||||
if (current.logsEnabled == enabled) return@withLock
|
||||
persistClient(current.copy(logsEnabled = enabled))
|
||||
}
|
||||
ProxyServiceState.setLogsEnabled(enabled)
|
||||
}
|
||||
}
|
||||
|
||||
fun saveProxyServerConfig(listen: String, connect: String) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock { prefs.saveProxyConfig(listen, connect); mirrorActiveProfile() }
|
||||
@@ -289,11 +211,6 @@ class SettingsViewModel(
|
||||
mirrorActiveProfile()
|
||||
}
|
||||
|
||||
private suspend fun persistServer(opts: AppPreferences.ServerOpts) {
|
||||
prefs.saveServerOpts(opts)
|
||||
mirrorActiveProfile()
|
||||
}
|
||||
|
||||
fun renameProfile(id: String, name: String) {
|
||||
viewModelScope.launch {
|
||||
profileMutex.withLock {
|
||||
@@ -371,6 +288,30 @@ class SettingsViewModel(
|
||||
return "$trimmed ($i)"
|
||||
}
|
||||
|
||||
// --- Edit-by-id (новый Settings-флоу) ---
|
||||
// Правит client-конфиг профиля по id, НЕ требуя его активации. Для активного
|
||||
// профиля дополнительно зеркалит в legacy-ключи (рантаймовое ядро их читает) и
|
||||
// обновляет глобальный флаг логов. Для неактивного — пишет только сохранённый
|
||||
// снимок, рантайм не трогается (нужно для редактирования неактивных серверов).
|
||||
fun updateProfileClient(id: String, transform: (ClientConfig) -> ClientConfig) {
|
||||
viewModelScope.launch {
|
||||
var mirrored: ClientConfig? = null
|
||||
profileMutex.withLock {
|
||||
val snap = prefs.profilesSnapshot.first()
|
||||
val target = snap.list.firstOrNull { it.id == id } ?: return@withLock
|
||||
val updated = transform(target.client)
|
||||
if (updated == target.client) return@withLock
|
||||
val list = snap.list.map { if (it.id == id) it.copy(client = updated) else it }
|
||||
prefs.saveProfiles(list)
|
||||
if (id == snap.activeId) {
|
||||
prefs.saveClientConfig(updated)
|
||||
mirrored = updated
|
||||
}
|
||||
}
|
||||
mirrored?.let { ProxyServiceState.setLogsEnabled(it.logsEnabled) }
|
||||
}
|
||||
}
|
||||
|
||||
// --- Server & Proxy Switches (TcpForward, Bond, Obf, Sync) ---
|
||||
fun setBond(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
@@ -384,30 +325,6 @@ class SettingsViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun setObfProfile(profile: String) {
|
||||
viewModelScope.launch {
|
||||
val current = prefs.serverOptsFlow.first()
|
||||
val known = sshRepository.serverState.value as? ServerState.Known
|
||||
val storedMatches = current.obfProfile == profile
|
||||
val effectiveMatches = known?.obfProfile?.let { it == profile } ?: true
|
||||
if (storedMatches && effectiveMatches) return@launch
|
||||
val sync = prefs.clientConfigFlow.first().syncServerSwitches
|
||||
// generateObfKey — сетевой SSH-вызов, не держим под profileMutex.
|
||||
val generatedKey: String? =
|
||||
if (profile != ObfProfile.NONE && current.obfKey.isBlank() && sync)
|
||||
sshRepository.generateObfKey()?.takeIf { it.isNotBlank() }
|
||||
else null
|
||||
profileMutex.withLock {
|
||||
val latest = prefs.serverOptsFlow.first()
|
||||
var next = latest.copy(obfProfile = profile)
|
||||
if (generatedKey != null && next.obfKey.isBlank()) next = next.copy(obfKey = generatedKey)
|
||||
if (next != latest) persistServer(next)
|
||||
}
|
||||
if (sync) orchestrator.restartServerIfRunning()
|
||||
orchestrator.restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
|
||||
fun setSyncServerSwitches(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
val changed = profileMutex.withLock {
|
||||
@@ -423,42 +340,45 @@ class SettingsViewModel(
|
||||
}
|
||||
}
|
||||
|
||||
fun setObfKey(key: String) {
|
||||
/**
|
||||
* Атомарно применяет конфиг сервера (proxy-адреса + tcp-проброс + профиль обфускации
|
||||
* + obf-ключ) одной транзакцией и перезапускает сервер/прокси РОВНО один раз — для
|
||||
* apply-модели «Настроек сервера» (натыкали черновик → Применить). Если включается
|
||||
* обфускация без ключа в sync-режиме, ключ генерируется на сервере (SSH, вне mutex).
|
||||
*/
|
||||
fun applyServerConfig(
|
||||
listen: String,
|
||||
connect: String,
|
||||
tcpForward: Boolean,
|
||||
obfProfile: String,
|
||||
obfKey: String
|
||||
) {
|
||||
viewModelScope.launch {
|
||||
val trimmed = key.trim()
|
||||
val changed = profileMutex.withLock {
|
||||
val current = prefs.serverOptsFlow.first()
|
||||
if (current.obfKey == trimmed) return@withLock false
|
||||
persistServer(current.copy(obfKey = trimmed))
|
||||
true
|
||||
}
|
||||
if (!changed) return@launch
|
||||
if (prefs.clientConfigFlow.first().syncServerSwitches) orchestrator.restartServerIfRunning()
|
||||
orchestrator.restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
|
||||
fun setTcpForward(enabled: Boolean) {
|
||||
viewModelScope.launch {
|
||||
val current = prefs.clientConfigFlow.first()
|
||||
val known = sshRepository.serverState.value as? ServerState.Known
|
||||
val storedMatches = current.tcpForward == enabled
|
||||
val effectiveMatches = known?.tcpMode?.let { it == enabled } ?: true
|
||||
if (storedMatches && effectiveMatches) return@launch
|
||||
if (!storedMatches) {
|
||||
profileMutex.withLock {
|
||||
val latest = prefs.clientConfigFlow.first()
|
||||
if (latest.tcpForward != enabled) persistClient(latest.copy(tcpForward = enabled))
|
||||
val sync = prefs.clientConfigFlow.first().syncServerSwitches
|
||||
val trimmedKey = obfKey.trim()
|
||||
val generatedKey: String? =
|
||||
if (obfProfile != ObfProfile.NONE && trimmedKey.isBlank() && sync)
|
||||
sshRepository.generateObfKey()?.takeIf { it.isNotBlank() }
|
||||
else null
|
||||
var changed = false
|
||||
profileMutex.withLock {
|
||||
if (prefs.proxyListenFlow.first() != listen || prefs.proxyConnectFlow.first() != connect) {
|
||||
prefs.saveProxyConfig(listen, connect); changed = true
|
||||
}
|
||||
}
|
||||
if (current.syncServerSwitches) {
|
||||
val serverRunning = (sshRepository.serverState.value as? ServerState.Known)?.running == true
|
||||
if (serverRunning) {
|
||||
sshRepository.stopServer()
|
||||
orchestrator.startServerFromPrefs()
|
||||
val client = prefs.clientConfigFlow.first()
|
||||
if (client.tcpForward != tcpForward) {
|
||||
prefs.saveClientConfig(client.copy(tcpForward = tcpForward)); changed = true
|
||||
}
|
||||
val opts = prefs.serverOptsFlow.first()
|
||||
val effKey = trimmedKey.ifBlank { generatedKey ?: opts.obfKey }
|
||||
val nextOpts = opts.copy(obfProfile = obfProfile, obfKey = effKey)
|
||||
if (nextOpts != opts) { prefs.saveServerOpts(nextOpts); changed = true }
|
||||
if (changed) mirrorActiveProfile()
|
||||
}
|
||||
if (changed) {
|
||||
if (sync) orchestrator.restartServerIfRunning()
|
||||
orchestrator.restartProxyIfRunning()
|
||||
}
|
||||
orchestrator.restartProxyIfRunning()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user