fix(profiles): корректное сохранение и переключение профилей

Profile теперь хранит ServerOpts (wrapEnabled, wrapKey, vlessBond, kcpFec) —
раньше серверные опции были глобальными и перетекали между профилями.

profileMutex сериализует все операции над списком и зеркалирование активного
профиля. Параллельные viewModelScope.launch (apply + mirror) больше не
способны прочитать устаревший snapshot и затереть чужие данные.

mirrorActiveProfile принимает *Override параметры — пишет в профиль только
что сохранённое значение напрямую, без гонки на Flow.first() сразу после
DataStore.edit.

applyProfile дополнительно вызывает saveServerOpts(target.server) и
перезапускает сервер если он был активен.
This commit is contained in:
samosvalishe committed 2026-05-12 02:00:13 +03:00
1 parent f5509367bb
commit 26f4ebdbf8
2 files changed
+167 -73

No files matched your search

@@ -17,7 +17,8 @@ data class Profile(
val ssh: SshConfig = SshConfig(), val ssh: SshConfig = SshConfig(),
val client: ClientConfig = ClientConfig(), val client: ClientConfig = ClientConfig(),
val proxyListen: String = "0.0.0.0:56000", val proxyListen: String = "0.0.0.0:56000",
val proxyConnect: String = "127.0.0.1:40537" val proxyConnect: String = "127.0.0.1:40537",
val server: AppPreferences.ServerOpts = AppPreferences.ServerOpts()
) )
data class ProfilesSnapshot( data class ProfilesSnapshot(
@@ -78,11 +79,18 @@ internal object ProfileJson {
}) })
put("proxyListen", p.proxyListen) put("proxyListen", p.proxyListen)
put("proxyConnect", p.proxyConnect) put("proxyConnect", p.proxyConnect)
put("server", JSONObject().apply {
put("vlessBond", p.server.vlessBond)
put("wrapEnabled", p.server.wrapEnabled)
put("wrapKey", p.server.wrapKey)
put("kcpFec", p.server.kcpFec)
})
} }
private fun decode(o: JSONObject): Profile { private fun decode(o: JSONObject): Profile {
val sshO = o.optJSONObject("ssh") ?: JSONObject() val sshO = o.optJSONObject("ssh") ?: JSONObject()
val cliO = o.optJSONObject("client") ?: JSONObject() val cliO = o.optJSONObject("client") ?: JSONObject()
val srvO = o.optJSONObject("server") ?: JSONObject()
return Profile( return Profile(
id = o.optString("id").ifBlank { UUID.randomUUID().toString() }, id = o.optString("id").ifBlank { UUID.randomUUID().toString() },
name = o.optString("name").ifBlank { "Без названия" }, name = o.optString("name").ifBlank { "Без названия" },
@@ -120,7 +128,13 @@ internal object ProfileJson {
magicTurn = cliO.optString("magicTurn") magicTurn = cliO.optString("magicTurn")
), ),
proxyListen = o.optString("proxyListen").ifBlank { "0.0.0.0:56000" }, proxyListen = o.optString("proxyListen").ifBlank { "0.0.0.0:56000" },
proxyConnect = o.optString("proxyConnect").ifBlank { "127.0.0.1:40537" } proxyConnect = o.optString("proxyConnect").ifBlank { "127.0.0.1:40537" },
server = AppPreferences.ServerOpts(
vlessBond = srvO.optBoolean("vlessBond", false),
wrapEnabled = srvO.optBoolean("wrapEnabled", false),
wrapKey = srvO.optString("wrapKey"),
kcpFec = srvO.optBoolean("kcpFec", false)
)
) )
} }
} }
@@ -24,6 +24,8 @@ import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.withTimeoutOrNull
class MainViewModel(application: Application) : AndroidViewModel(application) { class MainViewModel(application: Application) : AndroidViewModel(application) {
@@ -108,25 +110,36 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
val profilesSnapshot: StateFlow<ProfilesSnapshot> = prefs.profilesSnapshot val profilesSnapshot: StateFlow<ProfilesSnapshot> = prefs.profilesSnapshot
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot()) .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot())
/**
* Сериализует все операции над списком профилей и зеркалирование активного
* профиля. Без этого параллельные viewModelScope.launch'и могли прочитать
* устаревший snapshot и затереть/перетянуть данные между профилями.
*/
private val profileMutex = Mutex()
/** Сохранить текущие настройки как новый профиль и сделать активным. */ /** Сохранить текущие настройки как новый профиль и сделать активным. */
fun saveCurrentAsProfile(name: String) { fun saveCurrentAsProfile(name: String) {
viewModelScope.launch { viewModelScope.launch {
val current = prefs.profilesSnapshot.first() profileMutex.withLock {
val ssh = prefs.sshConfigFlow.first() val current = prefs.profilesSnapshot.first()
val client = prefs.clientConfigFlow.first() val ssh = prefs.sshConfigFlow.first()
val listen = prefs.proxyListenFlow.first() val client = prefs.clientConfigFlow.first()
val connect = prefs.proxyConnectFlow.first() val listen = prefs.proxyListenFlow.first()
val base = name.trim().ifBlank { defaultProfileName(client.serverAddress) } val connect = prefs.proxyConnectFlow.first()
val profile = Profile( val server = prefs.serverOptsFlow.first()
id = UUID.randomUUID().toString(), val base = name.trim().ifBlank { defaultProfileName(client.serverAddress) }
name = uniqueProfileName(base, current.list, excludingId = null), val profile = Profile(
ssh = ssh, id = UUID.randomUUID().toString(),
client = client, name = uniqueProfileName(base, current.list, excludingId = null),
proxyListen = listen, ssh = ssh,
proxyConnect = connect client = client,
) proxyListen = listen,
prefs.saveProfiles(current.list + profile) proxyConnect = connect,
prefs.setActiveProfileId(profile.id) server = server
)
prefs.saveProfiles(current.list + profile)
prefs.setActiveProfileId(profile.id)
}
} }
} }
@@ -153,25 +166,44 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
/** Публичный триггер пересохранения активного профиля текущими настройками. */ /** Публичный триггер пересохранения активного профиля текущими настройками. */
fun updateActiveProfileFromCurrent() { fun updateActiveProfileFromCurrent() {
viewModelScope.launch { mirrorActiveProfile() } viewModelScope.launch { profileMutex.withLock { mirrorActiveProfile() } }
} }
/** /**
* Зеркалирует текущие prefs (ssh+client) в активный профиль. Источник истины — * Зеркалирует текущие prefs (ssh+client+server) в активный профиль. Источник истины —
* профиль, но legacy-ключи остаются «scratch»-областью для случая «нет профилей». * профиль, но legacy-ключи остаются «scratch»-областью для случая «нет профилей».
* Вызывается автоматически после каждой записи ssh/client конфига, чтобы * Вызывается автоматически после каждой записи ssh/client/server конфига, чтобы
* пользовательские правки не терялись при переключении профилей. * пользовательские правки не терялись при переключении профилей.
*
* Параметры `*Override` позволяют передать значение, которое мы только что
* записали в DataStore, не полагаясь на асинхронную эмиссию Flow.first() —
* иначе возможен race, когда .first() возвращает доcоставочный snapshot.
*
* ВАЖНО: вызывать только под profileMutex.
*/ */
private suspend fun mirrorActiveProfile() { private suspend fun mirrorActiveProfile(
sshOverride: SshConfig? = null,
clientOverride: ClientConfig? = null,
listenOverride: String? = null,
connectOverride: String? = null,
serverOverride: AppPreferences.ServerOpts? = null,
) {
val current = prefs.profilesSnapshot.first() val current = prefs.profilesSnapshot.first()
val activeId = current.activeId ?: return val activeId = current.activeId ?: return
val ssh = prefs.sshConfigFlow.first() val ssh = sshOverride ?: prefs.sshConfigFlow.first()
val client = prefs.clientConfigFlow.first() val client = clientOverride ?: prefs.clientConfigFlow.first()
val listen = prefs.proxyListenFlow.first() val listen = listenOverride ?: prefs.proxyListenFlow.first()
val connect = prefs.proxyConnectFlow.first() val connect = connectOverride ?: prefs.proxyConnectFlow.first()
val server = serverOverride ?: prefs.serverOptsFlow.first()
val updated = current.list.map { val updated = current.list.map {
if (it.id == activeId) if (it.id == activeId)
it.copy(ssh = ssh, client = client, proxyListen = listen, proxyConnect = connect) it.copy(
ssh = ssh,
client = client,
proxyListen = listen,
proxyConnect = connect,
server = server
)
else it else it
} }
if (updated != current.list) prefs.saveProfiles(updated) if (updated != current.list) prefs.saveProfiles(updated)
@@ -179,35 +211,43 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
fun renameProfile(id: String, name: String) { fun renameProfile(id: String, name: String) {
viewModelScope.launch { viewModelScope.launch {
val current = prefs.profilesSnapshot.first() profileMutex.withLock {
val target = current.list.firstOrNull { it.id == id } ?: return@launch val current = prefs.profilesSnapshot.first()
val base = name.trim().ifBlank { target.name } val target = current.list.firstOrNull { it.id == id } ?: return@withLock
val unique = uniqueProfileName(base, current.list, excludingId = id) val base = name.trim().ifBlank { target.name }
val updated = current.list.map { val unique = uniqueProfileName(base, current.list, excludingId = id)
if (it.id == id) it.copy(name = unique) else it val updated = current.list.map {
if (it.id == id) it.copy(name = unique) else it
}
prefs.saveProfiles(updated)
} }
prefs.saveProfiles(updated)
} }
} }
/** /**
* Применяет профиль: загружает его ssh/client в legacy-ключи (которые читают * Применяет профиль: загружает его ssh/client/server в legacy-ключи и помечает
* существующие экраны) и помечает активным. Если прокси запущен — перезапускает, * активным. Если прокси/сервер запущены — перезапускает.
* иначе логика клиента продолжит использовать старые настройки.
*/ */
fun applyProfile(id: String) { fun applyProfile(id: String) {
viewModelScope.launch { viewModelScope.launch {
val current = prefs.profilesSnapshot.first() val target = profileMutex.withLock {
val target = current.list.firstOrNull { it.id == id } ?: return@launch val current = prefs.profilesSnapshot.first()
prefs.saveSshConfig(target.ssh) val t = current.list.firstOrNull { it.id == id } ?: return@withLock null
prefs.saveClientConfig(target.client) prefs.saveSshConfig(t.ssh)
prefs.saveProxyConfig(target.proxyListen, target.proxyConnect) prefs.saveClientConfig(t.client)
prefs.setActiveProfileId(target.id) prefs.saveProxyConfig(t.proxyListen, t.proxyConnect)
prefs.saveServerOpts(t.server)
prefs.setActiveProfileId(t.id)
t
} ?: return@launch
// Рестарт вне лока, чтобы не блокировать другие профильные операции
// на время stop/start (может занять секунды).
val serverRunning = (serverState.value as? ServerState.Known)?.running == true
if (serverRunning) restartServerIfRunning()
if (ProxyServiceState.isRunning.value) { if (ProxyServiceState.isRunning.value) {
proxyManager.stopProxy() proxyManager.stopProxy()
// Ждём фактической остановки сервиса вместо магического delay,
// иначе onStartCommand может стартовать со старыми аргументами.
withTimeoutOrNull(2_000) { withTimeoutOrNull(2_000) {
ProxyServiceState.isRunning.first { !it } ProxyServiceState.isRunning.first { !it }
} }
@@ -218,16 +258,19 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
fun deleteProfile(id: String) { fun deleteProfile(id: String) {
viewModelScope.launch { viewModelScope.launch {
val current = prefs.profilesSnapshot.first() profileMutex.withLock {
val remaining = current.list.filterNot { it.id == id } val current = prefs.profilesSnapshot.first()
prefs.saveProfiles(remaining) val remaining = current.list.filterNot { it.id == id }
if (current.activeId == id) { prefs.saveProfiles(remaining)
val next = remaining.firstOrNull() if (current.activeId == id) {
prefs.setActiveProfileId(next?.id) val next = remaining.firstOrNull()
if (next != null) { prefs.setActiveProfileId(next?.id)
prefs.saveSshConfig(next.ssh) if (next != null) {
prefs.saveClientConfig(next.client) prefs.saveSshConfig(next.ssh)
prefs.saveProxyConfig(next.proxyListen, next.proxyConnect) prefs.saveClientConfig(next.client)
prefs.saveProxyConfig(next.proxyListen, next.proxyConnect)
prefs.saveServerOpts(next.server)
}
} }
} }
} }
@@ -253,13 +296,17 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
// SSH // SSH
fun connectSsh(config: SshConfig) { fun connectSsh(config: SshConfig) {
viewModelScope.launch { viewModelScope.launch {
prefs.saveSshConfig(config) profileMutex.withLock {
mirrorActiveProfile() prefs.saveSshConfig(config)
mirrorActiveProfile(sshOverride = config)
}
val (success, fp) = sshRepository.connectSsh(config) val (success, fp) = sshRepository.connectSsh(config)
if (success) { if (success) {
if (config.hostFingerprint.isEmpty() && fp != null) { if (config.hostFingerprint.isEmpty() && fp != null) {
prefs.saveSshFingerprint(fp) profileMutex.withLock {
mirrorActiveProfile() prefs.saveSshFingerprint(fp)
mirrorActiveProfile(sshOverride = config.copy(hostFingerprint = fp))
}
} }
HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS) HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS)
} else { } else {
@@ -301,7 +348,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
if (current.wrapKey.isBlank()) { if (current.wrapKey.isBlank()) {
val key = sshRepository.generateWrapKey() val key = sshRepository.generateWrapKey()
if (!key.isNullOrBlank()) { if (!key.isNullOrBlank()) {
prefs.saveServerOpts(current.copy(wrapKey = key)) val next = current.copy(wrapKey = key)
profileMutex.withLock {
prefs.saveServerOpts(next)
mirrorActiveProfile(serverOverride = next)
}
} }
} }
} }
@@ -343,7 +394,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch { viewModelScope.launch {
val current = prefs.serverOptsFlow.first() val current = prefs.serverOptsFlow.first()
if (current.kcpFec == enabled) return@launch if (current.kcpFec == enabled) return@launch
prefs.saveServerOpts(current.copy(kcpFec = enabled)) val next = current.copy(kcpFec = enabled)
profileMutex.withLock {
prefs.saveServerOpts(next)
mirrorActiveProfile(serverOverride = next)
}
if (clientConfig.value.syncServerSwitches) restartServerIfRunning() if (clientConfig.value.syncServerSwitches) restartServerIfRunning()
restartProxyIfRunning() restartProxyIfRunning()
} }
@@ -353,7 +408,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch { viewModelScope.launch {
val current = prefs.serverOptsFlow.first() val current = prefs.serverOptsFlow.first()
if (current.vlessBond == enabled) return@launch if (current.vlessBond == enabled) return@launch
prefs.saveServerOpts(current.copy(vlessBond = enabled)) val next = current.copy(vlessBond = enabled)
profileMutex.withLock {
prefs.saveServerOpts(next)
mirrorActiveProfile(serverOverride = next)
}
if (clientConfig.value.syncServerSwitches) restartServerIfRunning() if (clientConfig.value.syncServerSwitches) restartServerIfRunning()
restartProxyIfRunning() restartProxyIfRunning()
} }
@@ -371,7 +430,10 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
val key = sshRepository.generateWrapKey() val key = sshRepository.generateWrapKey()
if (!key.isNullOrBlank()) next = next.copy(wrapKey = key) if (!key.isNullOrBlank()) next = next.copy(wrapKey = key)
} }
prefs.saveServerOpts(next) profileMutex.withLock {
prefs.saveServerOpts(next)
mirrorActiveProfile(serverOverride = next)
}
if (sync) restartServerIfRunning() if (sync) restartServerIfRunning()
restartProxyIfRunning() restartProxyIfRunning()
} }
@@ -386,8 +448,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
viewModelScope.launch { viewModelScope.launch {
val current = prefs.clientConfigFlow.first() val current = prefs.clientConfigFlow.first()
if (current.syncServerSwitches == enabled) return@launch if (current.syncServerSwitches == enabled) return@launch
prefs.saveClientConfig(current.copy(syncServerSwitches = enabled)) val next = current.copy(syncServerSwitches = enabled)
mirrorActiveProfile() profileMutex.withLock {
prefs.saveClientConfig(next)
mirrorActiveProfile(clientOverride = next)
}
if (enabled) { if (enabled) {
restartServerIfRunning() restartServerIfRunning()
restartProxyIfRunning() restartProxyIfRunning()
@@ -405,7 +470,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
val current = prefs.serverOptsFlow.first() val current = prefs.serverOptsFlow.first()
val trimmed = key.trim() val trimmed = key.trim()
if (current.wrapKey == trimmed) return@launch if (current.wrapKey == trimmed) return@launch
prefs.saveServerOpts(current.copy(wrapKey = trimmed)) val next = current.copy(wrapKey = trimmed)
profileMutex.withLock {
prefs.saveServerOpts(next)
mirrorActiveProfile(serverOverride = next)
}
if (clientConfig.value.syncServerSwitches) restartServerIfRunning() if (clientConfig.value.syncServerSwitches) restartServerIfRunning()
restartProxyIfRunning() restartProxyIfRunning()
} }
@@ -418,7 +487,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
try { try {
val key = sshRepository.generateWrapKey() ?: return@launch val key = sshRepository.generateWrapKey() ?: return@launch
val current = prefs.serverOptsFlow.first() val current = prefs.serverOptsFlow.first()
prefs.saveServerOpts(current.copy(wrapKey = key)) val next = current.copy(wrapKey = key)
profileMutex.withLock {
prefs.saveServerOpts(next)
mirrorActiveProfile(serverOverride = next)
}
if (clientConfig.value.syncServerSwitches) restartServerIfRunning() if (clientConfig.value.syncServerSwitches) restartServerIfRunning()
restartProxyIfRunning() restartProxyIfRunning()
} finally { } finally {
@@ -479,8 +552,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
val current = clientConfig.value val current = clientConfig.value
if (current.vlessMode == enabled) return if (current.vlessMode == enabled) return
viewModelScope.launch { viewModelScope.launch {
prefs.saveClientConfig(current.copy(vlessMode = enabled)) val next = current.copy(vlessMode = enabled)
mirrorActiveProfile() profileMutex.withLock {
prefs.saveClientConfig(next)
mirrorActiveProfile(clientOverride = next)
}
if (current.syncServerSwitches) { if (current.syncServerSwitches) {
val serverRunning = (serverState.value as? ServerState.Known)?.running == true val serverRunning = (serverState.value as? ServerState.Known)?.running == true
if (serverRunning) { if (serverRunning) {
@@ -514,15 +590,19 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
// Preferences // Preferences
fun saveClientConfig(config: ClientConfig) { fun saveClientConfig(config: ClientConfig) {
viewModelScope.launch { viewModelScope.launch {
prefs.saveClientConfig(config) profileMutex.withLock {
mirrorActiveProfile() prefs.saveClientConfig(config)
mirrorActiveProfile(clientOverride = config)
}
} }
} }
fun saveProxyServerConfig(listen: String, connect: String) { fun saveProxyServerConfig(listen: String, connect: String) {
viewModelScope.launch { viewModelScope.launch {
prefs.saveProxyConfig(listen, connect) profileMutex.withLock {
mirrorActiveProfile() prefs.saveProxyConfig(listen, connect)
mirrorActiveProfile(listenOverride = listen, connectOverride = connect)
}
} }
} }