refactor: переименовать «профили» в «серверы» по всему коду

Profile -> Server (data/Server.kt), ProfilesSnapshot -> ServersSnapshot,
ProfileJson -> ServerJson, поле Server.server -> Server.opts.
Методы VM: applyProfile -> applyServer, deleteProfile -> deleteServer,
renameProfile -> renameServer, updateProfileClient -> updateServerClient,
applyProfileServerConfig -> updateServerConfig. Nav-аргумент profileId -> serverId,
строковые ресурсы profile_* -> server_*.

Не тронуто: ObfProfile / -obf-profile (wire-профиль обфускации ядра),
persisted-ключи DataStore (profiles_json, active_profile_id) и JSON-схема
снимка — совместимость с данными пользователей.
This commit is contained in:
samosvalishe committed 2026-06-10 22:30:13 +03:00
1 parent 137ff49713
commit a92da813e9
15 files changed
+249 -245

No files matched your search

@@ -175,8 +175,10 @@ class AppPreferences(context: Context) {
val DYNAMIC_THEME = booleanPreferencesKey("dynamic_theme")
val NERD_MODE = booleanPreferencesKey("nerd_mode")
val TG_SUBSCRIBE_SHOWN = booleanPreferencesKey("tg_subscribe_shown")
val PROFILES_JSON = stringPreferencesKey("profiles_json")
val ACTIVE_PROFILE_ID = stringPreferencesKey("active_profile_id")
// Имена ключей legacy («profiles_json», «active_profile_id») — не менять,
// иначе сохранённые серверы пользователей потеряются при обновлении.
val SERVERS_JSON = stringPreferencesKey("profiles_json")
val ACTIVE_SERVER_ID = stringPreferencesKey("active_profile_id")
}
// Шифрованное хранилище для SSH-пароля и ключа (Android Keystore + AES-256)
@@ -299,17 +301,17 @@ class AppPreferences(context: Context) {
val tgSubscribeShownFlow: Flow<Boolean> = prefFlow { prefs -> prefs[TG_SUBSCRIBE_SHOWN] ?: false }
/** Заменяет весь список профилей. */
suspend fun saveProfiles(list: List<Profile>) {
/** Заменяет весь список серверов. */
suspend fun saveServers(list: List<Server>) {
context.dataStore.edit { prefs ->
prefs[PROFILES_JSON] = ProfileJson.encodeList(list)
prefs[SERVERS_JSON] = ServerJson.encodeList(list)
}
}
suspend fun setActiveProfileId(id: String?) {
suspend fun setActiveServerId(id: String?) {
context.dataStore.edit { prefs ->
if (id == null) prefs.remove(ACTIVE_PROFILE_ID)
else prefs[ACTIVE_PROFILE_ID] = id
if (id == null) prefs.remove(ACTIVE_SERVER_ID)
else prefs[ACTIVE_SERVER_ID] = id
}
}
@@ -393,10 +395,10 @@ class AppPreferences(context: Context) {
* Снимок: список + id активного. Объединено в один Flow, чтобы UI получал
* консистентную пару (нет окна, в котором активный id указывает на удалённый).
*/
val profilesSnapshot: Flow<ProfilesSnapshot> = prefFlow { prefs ->
ProfilesSnapshot(
list = ProfileJson.decodeList(prefs[PROFILES_JSON]),
activeId = prefs[ACTIVE_PROFILE_ID]?.takeIf { it.isNotBlank() },
val serversSnapshot: Flow<ServersSnapshot> = prefFlow { prefs ->
ServersSnapshot(
list = ServerJson.decodeList(prefs[SERVERS_JSON]),
activeId = prefs[ACTIVE_SERVER_ID]?.takeIf { it.isNotBlank() },
loaded = true
)
}
@@ -6,38 +6,40 @@ import java.util.UUID
/**
* Именованный снимок настроек: SSH-сервер + клиентские параметры.
* Хранится сериализованным в DataStore. Активный профиль — это id из общего
* Именованный сервер: SSH-доступ + клиентские параметры + серверные опции.
* Хранится сериализованным в DataStore. Активный сервер — это id из общего
* списка; его SshConfig/ClientConfig дублируются в legacy-ключах prefs, чтобы
* существующие экраны и ViewModel могли работать без переписывания.
*/
data class Profile(
data class Server(
val id: String = UUID.randomUUID().toString(),
val name: String,
val ssh: SshConfig = SshConfig(),
val client: ClientConfig = ClientConfig(),
val proxyListen: String = "0.0.0.0:56000",
val proxyConnect: String = "127.0.0.1:40537",
val server: AppPreferences.ServerOpts = AppPreferences.ServerOpts()
val opts: AppPreferences.ServerOpts = AppPreferences.ServerOpts()
)
data class ProfilesSnapshot(
val list: List<Profile> = emptyList(),
data class ServersSnapshot(
val list: List<Server> = emptyList(),
val activeId: String? = null,
/** false = initial-значение stateIn до первой эмиссии DataStore. */
val loaded: Boolean = false
) {
val active: Profile? get() = list.firstOrNull { it.id == activeId }
val active: Server? get() = list.firstOrNull { it.id == activeId }
}
internal object ProfileJson {
fun encodeList(list: List<Profile>): String {
// JSON-ключи («server», «obfProfile», …) — legacy-схема хранения, не менять:
// иначе сохранённые серверы пользователей не распарсятся.
internal object ServerJson {
fun encodeList(list: List<Server>): String {
val arr = JSONArray()
list.forEach { arr.put(encode(it)) }
return arr.toString()
}
fun decodeList(raw: String?): List<Profile> {
fun decodeList(raw: String?): List<Server> {
if (raw.isNullOrBlank()) return emptyList()
return try {
val arr = JSONArray(raw)
@@ -47,7 +49,7 @@ internal object ProfileJson {
}
}
private fun encode(p: Profile): JSONObject = JSONObject().apply {
private fun encode(p: Server): JSONObject = JSONObject().apply {
put("id", p.id)
put("name", p.name)
put("ssh", JSONObject().apply {
@@ -90,16 +92,16 @@ internal object ProfileJson {
put("proxyListen", p.proxyListen)
put("proxyConnect", p.proxyConnect)
put("server", JSONObject().apply {
put("obfProfile", p.server.obfProfile)
put("obfKey", p.server.obfKey)
put("obfProfile", p.opts.obfProfile)
put("obfKey", p.opts.obfKey)
})
}
private fun decode(o: JSONObject): Profile {
private fun decode(o: JSONObject): Server {
val sshO = o.optJSONObject("ssh") ?: JSONObject()
val cliO = o.optJSONObject("client") ?: JSONObject()
val srvO = o.optJSONObject("server") ?: JSONObject()
return Profile(
return Server(
id = o.optString("id").ifBlank { UUID.randomUUID().toString() },
name = o.optString("name").ifBlank { "Без названия" },
ssh = SshConfig(
@@ -152,7 +154,7 @@ internal object ProfileJson {
),
proxyListen = o.optString("proxyListen").ifBlank { "0.0.0.0:56000" },
proxyConnect = o.optString("proxyConnect").ifBlank { "127.0.0.1:40537" },
server = AppPreferences.ServerOpts(
opts = AppPreferences.ServerOpts(
obfProfile = srvO.optString("obfProfile", ObfProfile.NONE).let {
if (it in ObfProfile.ALL) it else ObfProfile.NONE
},
@@ -68,7 +68,7 @@ fun ServerRow(
val iconTint = if (isActive) MaterialTheme.colorScheme.onPrimary
else MaterialTheme.colorScheme.onSurfaceVariant
val activeBadge = stringResource(R.string.profile_active_badge)
val activeBadge = stringResource(R.string.server_active_badge)
val rowDesc = if (isActive) "$name, $activeBadge" else name
Surface(shape = shape, color = container, modifier = Modifier.fillMaxWidth()) {
@@ -79,11 +79,11 @@ object Routes {
const val ABOUT = "about"
const val ADVANCED = "advanced"
const val SERVERS_LIST = "servers_list"
const val SERVER_DETAIL = "server_detail/{profileId}"
const val CONNECTION_MODE = "connection_mode/{profileId}"
const val CLIENT_SETUP = "client_setup/{profileId}"
const val SERVER_MANAGEMENT = "server_management/{profileId}"
const val NERD_INFO = "nerd_info/{profileId}"
const val SERVER_DETAIL = "server_detail/{serverId}"
const val CONNECTION_MODE = "connection_mode/{serverId}"
const val CLIENT_SETUP = "client_setup/{serverId}"
const val SERVER_MANAGEMENT = "server_management/{serverId}"
const val NERD_INFO = "nerd_info/{serverId}"
fun serverDetail(id: String) = "server_detail/$id"
fun connectionMode(id: String) = "connection_mode/$id"
@@ -292,9 +292,9 @@ private fun AppNavHost(
}
composable(Routes.SERVER_DETAIL) { entry ->
val id = entry.arguments?.getString("profileId").orEmpty()
val id = entry.arguments?.getString("serverId").orEmpty()
ServerDetailScreen(
profileId = id,
serverId = id,
settingsViewModel = settingsViewModel,
serverViewModel = serverViewModel,
onBack = { navController.popBackStack() },
@@ -307,9 +307,9 @@ private fun AppNavHost(
}
composable(Routes.NERD_INFO) { entry ->
val id = entry.arguments?.getString("profileId").orEmpty()
val id = entry.arguments?.getString("serverId").orEmpty()
NerdScreen(
profileId = id,
serverId = id,
settingsViewModel = settingsViewModel,
serverViewModel = serverViewModel,
onBack = { navController.popBackStack() }
@@ -317,32 +317,32 @@ private fun AppNavHost(
}
composable(Routes.CONNECTION_MODE) { entry ->
val id = entry.arguments?.getString("profileId").orEmpty()
val id = entry.arguments?.getString("serverId").orEmpty()
ConnectionModeScreen(
settingsViewModel = settingsViewModel,
proxyViewModel = proxyViewModel,
profileId = id,
serverId = id,
onBack = { navController.popBackStack() }
)
}
composable(Routes.SERVER_MANAGEMENT) { entry ->
val id = entry.arguments?.getString("profileId").orEmpty()
val id = entry.arguments?.getString("serverId").orEmpty()
ServerManagementScreen(
serverViewModel = serverViewModel,
settingsViewModel = settingsViewModel,
profileId = id,
serverId = id,
onBack = { navController.popBackStack() },
onEditConnection = { navController.navigate(Routes.SSH_SETUP) }
)
}
composable(Routes.CLIENT_SETUP) { entry ->
val id = entry.arguments?.getString("profileId").orEmpty()
val id = entry.arguments?.getString("serverId").orEmpty()
ClientSetupScreen(
settingsViewModel = settingsViewModel,
serverViewModel = serverViewModel,
profileId = id,
serverId = id,
onBack = { navController.popBackStack() }
)
}
@@ -72,31 +72,31 @@ import kotlinx.coroutines.delay
fun ClientSetupScreen(
settingsViewModel: SettingsViewModel,
serverViewModel: ServerViewModel,
// null = legacy-режим (профиль ещё не создан, пишем в legacy-ключи).
// не-null = редактируем конкретный профиль по id (Settings-флоу).
profileId: String? = null,
// null = legacy-режим (сервер ещё не создан, пишем в legacy-ключи).
// не-null = редактируем конкретный сервер по id (Settings-флоу).
serverId: String? = null,
onBack: (() -> Unit)? = null
) {
val snapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle()
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val legacyClient by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val sshConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle()
val serverState by serverViewModel.serverState.collectAsStateWithLifecycle()
val legacyProxyListen by settingsViewModel.proxyListen.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
// Источник данных: конкретный профиль по id либо legacy-конфиг.
val profile = profileId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
val saved = profile?.client ?: legacyClient
// Активный профиль (или legacy-режим) рулит живым рантаймом: SSH-сессия, рестарты,
// Источник данных: конкретный сервер по id либо legacy-конфиг.
val server = serverId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
val saved = server?.client ?: legacyClient
// Активный сервер (или legacy-режим) рулит живым рантаймом: SSH-сессия, рестарты,
// sync с сервером. Для неактивного редактируем только хранимые данные.
val isActive = profileId == null || profileId == snapshot.activeId
val effSshIp = profile?.ssh?.ip ?: sshConfig.ip
val effProxyListen = profile?.proxyListen ?: legacyProxyListen
val isActive = serverId == null || serverId == snapshot.activeId
val effSshIp = server?.ssh?.ip ?: sshConfig.ip
val effProxyListen = server?.proxyListen ?: legacyProxyListen
// Единая точка записи client-конфига: профиль by-id либо legacy.
// Единая точка записи client-конфига: сервер by-id либо legacy.
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
if (profileId != null) {
settingsViewModel.updateProfileClient(profileId, transform)
if (serverId != null) {
settingsViewModel.updateServerClient(serverId, transform)
} else {
settingsViewModel.saveClientConfig(transform(settingsViewModel.clientConfig.value), snapshot.activeId)
}
@@ -112,7 +112,7 @@ fun ClientSetupScreen(
val context = LocalContext.current
// remember, НЕ rememberSaveable: rememberSaveable восстановил бы stale-поля из
// bundle при возврате на экран, и авто-сейв зеркалил бы их в чужой профиль.
// bundle при возврате на экран, и авто-сейв зеркалил бы их в чужой сервер.
var serverAddress by remember(saved.serverAddress) { mutableStateOf(saved.serverAddress) }
var vkLink by remember(saved.vkLink) { mutableStateOf(saved.vkLink) }
var threads by remember(saved.threads) { mutableFloatStateOf(saved.threads.toFloat()) }
@@ -130,7 +130,7 @@ fun ClientSetupScreen(
}
// Авто-сохранение с дебаунсом 600 мс для текстовых полей и ползунков.
// clientEdit сам маршрутизирует запись в профиль by-id либо в legacy и под
// clientEdit сам маршрутизирует запись в сервер by-id либо в legacy и под
// mutex сверяет цель — защита от гонки переключения за время дебаунса.
LaunchedEffect(
serverAddress, vkLink, threads, streamsPerCred, localPort, magicTurn, customDns
@@ -76,21 +76,21 @@ import kotlinx.coroutines.withContext
fun ConnectionModeScreen(
settingsViewModel: SettingsViewModel,
proxyViewModel: ProxyViewModel,
profileId: String? = null,
serverId: String? = null,
onBack: (() -> Unit)? = null
) {
val snapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle()
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val legacyClient by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val proxyState by proxyViewModel.proxyState.collectAsStateWithLifecycle()
val profile = profileId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
val saved = profile?.client ?: legacyClient
val isActive = profileId == null || profileId == snapshot.activeId
val server = serverId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
val saved = server?.client ?: legacyClient
val isActive = serverId == null || serverId == snapshot.activeId
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
if (profileId != null) {
settingsViewModel.updateProfileClient(profileId, transform)
if (serverId != null) {
settingsViewModel.updateServerClient(serverId, transform)
} else {
settingsViewModel.saveClientConfig(transform(settingsViewModel.clientConfig.value), snapshot.activeId)
}
@@ -102,7 +102,7 @@ fun ConnectionModeScreen(
// userPickedVpn держит VPN-выбор на сессию экрана: пока конфиг пуст, транспорт при
// чтении нормализуется в NONE (WIREGUARD без конфига = выключен, см. AppPreferences),
// и без локального флага сегмент мигал бы обратно на Proxy. Сброс по saved.tunnelTransport.
var userPickedVpn by remember(profileId, saved.tunnelTransport) { mutableStateOf<Boolean?>(null) }
var userPickedVpn by remember(serverId, saved.tunnelTransport) { mutableStateOf<Boolean?>(null) }
val isVpn = userPickedVpn ?: (saved.tunnelTransport == TunnelTransport.WIREGUARD)
var wgConfig by remember(saved.wireGuardConfig) { mutableStateOf(saved.wireGuardConfig) }
@@ -127,8 +127,8 @@ fun ConnectionModeScreen(
// Дебаунс WG-полей 600 мс. Первый прогон (значения = saved) пропускаем, чтобы не писать
// на входе. pendingSave → flush при выходе: dispose отменяет корутину и теряет правку.
var wgDirty by remember(profileId) { mutableStateOf(false) }
var pendingSave by remember(profileId) { mutableStateOf(false) }
var wgDirty by remember(serverId) { mutableStateOf(false) }
var pendingSave by remember(serverId) { mutableStateOf(false) }
LaunchedEffect(wgConfig, wgName) {
if (!wgDirty) { wgDirty = true; return@LaunchedEffect }
pendingSave = true
@@ -143,11 +143,11 @@ fun HomeScreen(
}
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val profilesSnapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle()
val serversSnapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val showSplitSheet = rememberSaveable { mutableStateOf(false) }
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
// Standard bottom sheet: свёрнутый peek = карточка активного профиля,
// Standard bottom sheet: свёрнутый peek = карточка активного сервера,
// тянется вверх до полного списка серверов. skipHiddenState — sheet всегда
// виден, не прячется полностью.
val sheetScaffoldState = rememberBottomSheetScaffoldState(
@@ -185,7 +185,7 @@ fun HomeScreen(
sheetContent = {
ServersSheetContent(
settingsViewModel = settingsViewModel,
snapshot = profilesSnapshot,
snapshot = serversSnapshot,
privacyMode = privacyMode,
onCollapse = {
scope.launch { sheetScaffoldState.bottomSheetState.partialExpand() }
@@ -497,8 +497,8 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
}
/**
* Прилипшая к низу M3 «карточка» — единственная точка входа в управление профилями.
* Виден всегда: с сохранённым активным профилем показывает его имя, без — лейбл
* Прилипшая к низу M3 «карточка» — единственная точка входа в управление серверами.
* Виден всегда: с сохранённым активным сервером показывает его имя, без — лейбл
* «несохранённая конфигурация» с приглашением открыть sheet.
*/
internal fun String.redact(enabled: Boolean) = if (enabled) "••••••" else this
@@ -87,32 +87,32 @@ fun ServerManagementScreen(
settingsViewModel: SettingsViewModel,
// Кнопка смены сервера (overflow ⋮).
onEditConnection: (() -> Unit)? = null,
// null = legacy. Не-null = настройки сервера конкретного профиля (Settings).
profileId: String? = null,
// null = legacy. Не-null = настройки конкретного сервера по id (Settings).
serverId: String? = null,
onBack: () -> Unit
) {
val snapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle()
val profile = profileId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val server = serverId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
// Живая SSH-сессия и состояние сервера принадлежат активному серверу. Управлять
// ядром можно только когда редактируемый профиль активен (legacy-режим без id
// ядром можно только когда редактируемый сервер активен (legacy-режим без id
// считается активным).
val isActive = profileId == null || profileId == snapshot.activeId
val isActive = serverId == null || serverId == snapshot.activeId
val sshState by serverViewModel.sshState.collectAsStateWithLifecycle()
val serverState by serverViewModel.serverState.collectAsStateWithLifecycle()
val sshConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle()
val legacyListen by settingsViewModel.proxyListen.collectAsStateWithLifecycle()
val legacyConnect by settingsViewModel.proxyConnect.collectAsStateWithLifecycle()
val savedListen = profile?.proxyListen ?: legacyListen
val savedConnect = profile?.proxyConnect ?: legacyConnect
val savedListen = server?.proxyListen ?: legacyListen
val savedConnect = server?.proxyConnect ?: legacyConnect
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val clientCfg by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val serverOpts by serverViewModel.serverOpts.collectAsStateWithLifecycle()
val isRegen by serverViewModel.isRegeneratingObfKey.collectAsStateWithLifecycle()
// Источник серверных черновиков: активный профиль рулит ЖИВЫМ конфигом (legacy/global —
// его обновляет regen на сервере), неактивный — снимком профиля by-id (sync OFF, клиент-локально).
val effClient = if (isActive) clientCfg else (profile?.client ?: clientCfg)
val effServer = if (isActive) serverOpts else (profile?.server ?: serverOpts)
// Источник серверных черновиков: активный сервер рулит ЖИВЫМ конфигом (legacy/global —
// его обновляет regen на сервере), неактивный — снимком сервера by-id (sync OFF, клиент-локально).
val effClient = if (isActive) clientCfg else (server?.client ?: clientCfg)
val effServer = if (isActive) serverOpts else (server?.opts ?: serverOpts)
// --- Черновики конфигурации (без авто-сохранения) ---
var proxyListenIp by rememberSaveable(savedListen) {
@@ -130,8 +130,8 @@ fun ServerManagementScreen(
val context = LocalContext.current
val snackbarHostState = remember { SnackbarHostState() }
var showServerMenu by rememberSaveable { mutableStateOf(false) }
// «Подключено» = ЖИВОЙ SSH ЭТОГО профиля. Живая сессия принадлежит активному серверу,
// поэтому для неактивного профиля всегда false (иначе чужой коннект протёк бы сюда).
// «Подключено» = ЖИВОЙ SSH ЭТОГО сервера. Живая сессия принадлежит активному серверу,
// поэтому для неактивного всегда false (иначе чужой коннект протёк бы сюда).
val isConnected = isActive && sshState is SshConnectionState.Connected
val syncOn = effClient.syncServerSwitches
val isWorking = serverState is ServerState.Working || serverState is ServerState.Checking
@@ -158,12 +158,12 @@ fun ServerManagementScreen(
configDirty && keyOkForApply && !isWorking
fun applyConfig() {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
// Активный — apply в живой рантайм (один рестарт). Неактивный — пишем только снимок профиля.
// Активный — apply в живой рантайм (один рестарт). Неактивный — пишем только снимок сервера.
if (isActive) {
settingsViewModel.applyServerConfig(listenFull, proxyConnect, tcpDraft, obfDraft, keyDraft)
} else {
profileId?.let {
settingsViewModel.applyProfileServerConfig(it, listenFull, proxyConnect, tcpDraft, obfDraft, keyDraft)
serverId?.let {
settingsViewModel.updateServerConfig(it, listenFull, proxyConnect, tcpDraft, obfDraft, keyDraft)
}
}
onBack()
@@ -246,9 +246,9 @@ fun ServerManagementScreen(
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
// Неактивный профиль + sync ON: серверные правки нужно пушить на сервер, а
// Неактивный сервер + sync ON: серверные правки нужно пушить на сервер, а
// живая SSH-сессия принадлежит активному. Предлагаем сделать активным.
// При sync OFF настройки клиент-локальны — редактируем снимок профиля ниже.
// При sync OFF настройки клиент-локальны — редактируем снимок сервера ниже.
if (!isActive && syncOn) {
HeroCard(
iconRes = R.drawable.host_24px,
@@ -257,7 +257,7 @@ fun ServerManagementScreen(
actionLabel = stringResource(R.string.make_active),
onAction = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
profileId?.let { settingsViewModel.applyProfile(it) }
serverId?.let { settingsViewModel.applyServer(it) }
}
)
Spacer(Modifier.height(24.dp))
@@ -478,7 +478,7 @@ fun ServerManagementScreen(
}
/**
* Hero-карточка состояния (неактивный профиль / потеря связи): тональный контейнер,
* Hero-карточка состояния (неактивный сервер / потеря связи): тональный контейнер,
* центрированная иконка + заголовок + пояснение + основная кнопка. Один источник стиля
* для пустых/аварийных состояний экрана.
*/
@@ -42,7 +42,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.ProfilesSnapshot
import com.freeturn.app.data.ServersSnapshot
import com.freeturn.app.data.Provider
import com.freeturn.app.ui.components.EmptyServersState
import com.freeturn.app.ui.components.ServerRow
@@ -58,7 +58,7 @@ import com.freeturn.app.viewmodel.SettingsViewModel
@Composable
fun ServersSheetContent(
settingsViewModel: SettingsViewModel,
snapshot: ProfilesSnapshot,
snapshot: ServersSnapshot,
privacyMode: Boolean = false,
onCollapse: () -> Unit = {},
onOpenServerSettings: (String) -> Unit = {}
@@ -78,19 +78,19 @@ fun ServersSheetContent(
.padding(horizontal = 24.dp, vertical = 4.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
val profileName = when {
val serverName = when {
active != null -> active.name
snapshot.loaded -> stringResource(R.string.profile_unsaved_label)
snapshot.loaded -> stringResource(R.string.server_unsaved_label)
else -> ""
}
TooltipBox(
positionProvider = TooltipDefaults.rememberTooltipPositionProvider(TooltipAnchorPosition.Above),
tooltip = { PlainTooltip { Text(profileName) } },
tooltip = { PlainTooltip { Text(serverName) } },
state = rememberTooltipState(),
enableUserInput = active != null
) {
Text(
profileName,
serverName,
style = MaterialTheme.typography.titleLarge,
textAlign = TextAlign.Center,
maxLines = 1,
@@ -104,7 +104,7 @@ fun ServersSheetContent(
?: it.ssh.ip.takeIf { a -> a.isNotBlank() })?.redact(privacyMode)
}
// Подзаголовок рендерим всегда: пустой Text держит высоту строки, иначе без
// профиля контент подъезжает и бейдж провайдера выглядывает из peek-зоны.
// сервера контент подъезжает и бейдж провайдера выглядывает из peek-зоны.
Spacer(Modifier.height(4.dp))
Text(
sub.orEmpty(),
@@ -137,7 +137,7 @@ fun ServersSheetContent(
)
} else {
Text(
stringResource(R.string.profiles_servers_title),
stringResource(R.string.servers_sheet_title),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(start = 24.dp, end = 16.dp, bottom = 8.dp)
)
@@ -163,7 +163,7 @@ fun ServersSheetContent(
inactiveContainer = MaterialTheme.colorScheme.surfaceContainerHigh,
onClick = {
if (!isActive) {
settingsViewModel.applyProfile(p.id)
settingsViewModel.applyServer(p.id)
onCollapse()
}
},
@@ -86,7 +86,7 @@ import androidx.compose.ui.text.font.FontFamily
import com.freeturn.app.R
import com.freeturn.app.data.CoreArgs
import com.freeturn.app.data.ObfProfile
import com.freeturn.app.data.Profile
import com.freeturn.app.data.Server
import com.freeturn.app.domain.server.ServerCommand
import com.freeturn.app.domain.server.ServerOptions
import com.freeturn.app.ui.HapticUtil
@@ -237,14 +237,14 @@ fun AdvancedScreen(
}
}
/** Список добавленных серверов (профилей). Клик по серверу → его детальный экран. */
/** Список добавленных серверов. Клик по серверу → его детальный экран. */
@Composable
fun ServersListScreen(
settingsViewModel: SettingsViewModel,
onBack: () -> Unit,
onOpenServer: (String) -> Unit
) {
val snapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle()
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
@@ -277,14 +277,14 @@ fun ServersListScreen(
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 12.dp)
) {
// Активный профиль закрепляем сверху — быстрый доступ к текущему серверу.
// Активный сервер закрепляем сверху — быстрый доступ к нему.
val ordered = remember(snapshot.list, snapshot.activeId) {
snapshot.list.sortedByDescending { it.id == snapshot.activeId }
}
SettingsGroup {
ordered.forEachIndexed { index, p ->
ServerListRow(
profile = p,
server = p,
isActive = snapshot.activeId == p.id,
privacyMode = privacyMode,
shape = settingsItemShape(index, ordered.size),
@@ -299,7 +299,7 @@ fun ServersListScreen(
@Composable
private fun ServerListRow(
profile: Profile,
server: Server,
isActive: Boolean,
privacyMode: Boolean,
shape: Shape,
@@ -308,11 +308,11 @@ private fun ServerListRow(
// Подзаголовок: адрес сервера + метка «SSH», если сопряжение настроено. Сам SSH-ip
// не дублируем (он уже не несёт пользе в списке) — достаточно факта наличия.
val sub = listOfNotNull(
profile.client.serverAddress.takeIf { it.isNotBlank() }?.redact(privacyMode),
stringResource(R.string.profile_has_ssh).takeIf { profile.ssh.ip.isNotBlank() }
server.client.serverAddress.takeIf { it.isNotBlank() }?.redact(privacyMode),
stringResource(R.string.server_has_ssh).takeIf { server.ssh.ip.isNotBlank() }
).joinToString(" · ").ifBlank { "—" }
ServerRow(
name = profile.name,
name = server.name,
subtitle = sub,
isActive = isActive,
shape = shape,
@@ -327,7 +327,7 @@ private fun ServerListRow(
*/
@Composable
fun ServerDetailScreen(
profileId: String,
serverId: String,
settingsViewModel: SettingsViewModel,
serverViewModel: ServerViewModel,
onBack: () -> Unit,
@@ -338,27 +338,27 @@ fun ServerDetailScreen(
onConfigureSsh: () -> Unit
) {
val context = LocalContext.current
val snapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle()
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val sshState by serverViewModel.sshState.collectAsStateWithLifecycle()
val sshConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle()
val coreStatus by serverViewModel.hubStatus.collectAsStateWithLifecycle()
val nerdMode by settingsViewModel.nerdMode.collectAsStateWithLifecycle()
val profile = snapshot.list.firstOrNull { it.id == profileId }
val isActive = snapshot.activeId == profileId
val server = snapshot.list.firstOrNull { it.id == serverId }
val isActive = snapshot.activeId == serverId
// Профиль удалён (например, из этого же экрана) — выходим назад.
if (snapshot.loaded && profile == null) {
// Сервер удалён (например, из этого же экрана) — выходим назад.
if (snapshot.loaded && server == null) {
LaunchedEffect(Unit) { onBack() }
return
}
// Единая статус-модель хаба: core-статус от VM (активный сервер) + profile-контекст.
// Единая статус-модель хаба: core-статус от VM (активный сервер) + server-контекст.
// Порядок гарантирует отсутствие мигания: пока снапшот не загружен — skeleton, а не Offline.
val status: ServerHubStatus = when {
!snapshot.loaded -> ServerHubStatus.Connecting
!isActive -> ServerHubStatus.Offline
profile?.ssh?.ip.isNullOrBlank() -> ServerHubStatus.NotPaired
server?.ssh?.ip.isNullOrBlank() -> ServerHubStatus.NotPaired
else -> coreStatus
}
// Вход в «Настройки сервера» доступен только при живом ядре (Online).
@@ -382,7 +382,7 @@ fun ServerDetailScreen(
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
// Подзаголовок hero-шапки: адрес сервера либо SSH-ip (что есть).
val headerSubtitle = profile?.let { p ->
val headerSubtitle = server?.let { p ->
p.client.serverAddress.takeIf { it.isNotBlank() }?.redact(privacyMode)
?: p.ssh.ip.takeIf { it.isNotBlank() }?.let { "SSH ${it.redact(privacyMode)}" }
}
@@ -392,7 +392,7 @@ fun ServerDetailScreen(
topBar = {
LargeFlexibleTopAppBar(
title = {
Text(profile?.name ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(server?.name ?: "", maxLines = 1, overflow = TextOverflow.Ellipsis)
},
subtitle = headerSubtitle?.let { sub ->
{ Text(sub, maxLines = 1, overflow = TextOverflow.Ellipsis) }
@@ -503,15 +503,15 @@ fun ServerDetailScreen(
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
if (profile != null) {
if (server != null) {
// SSH не настроен → синхронизировать нечего: тоггл гасим и держим OFF.
val sshConfigured = profile.ssh.ip.isNotBlank()
val sshConfigured = server.ssh.ip.isNotBlank()
ServerStatusCard(
status = status,
syncOn = sshConfigured && profile.client.syncServerSwitches,
syncOn = sshConfigured && server.client.syncServerSwitches,
onActivate = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
settingsViewModel.applyProfile(profileId)
settingsViewModel.applyServer(serverId)
},
onRetry = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
@@ -528,11 +528,11 @@ fun ServerDetailScreen(
SettingsSwitchRow(
title = stringResource(R.string.sync_server_switches),
iconRes = R.drawable.cached_24px,
checked = sshConfigured && profile.client.syncServerSwitches,
checked = sshConfigured && server.client.syncServerSwitches,
enabled = sshConfigured,
onCheckedChange = { v ->
if (isActive) settingsViewModel.setSyncServerSwitches(v)
else settingsViewModel.updateProfileClient(profileId) { it.copy(syncServerSwitches = v) }
else settingsViewModel.updateServerClient(serverId) { it.copy(syncServerSwitches = v) }
}
)
}
@@ -542,15 +542,15 @@ fun ServerDetailScreen(
// «Настройки сервера»: при sync ON правки пушатся на сервер → нужен живой
// SSH; при sync OFF клиент-локальны → вход доступен и оффлайн. Правило
// общее с ServerManagementScreen — serverSettingsAvailable.
val syncOn = profile?.client?.syncServerSwitches == true
val syncOn = server?.client?.syncServerSwitches == true
// Connecting/Working — transient: SSH ещё поднимается. Пункт не должен мигать,
// держим его видимым на время подключения (сам экран при входе покажет
// дебаунс-карту потери связи, а не пустоту). Прячем только в терминальных
// disconnected-состояниях (Failed/NotPaired) при sync ON.
val connecting = status is ServerHubStatus.Connecting || status is ServerHubStatus.Working
// Без isActive-гейта: неактивный профиль форсит status=Offline → connected/connecting=false,
// Без isActive-гейта: неактивный сервер форсит status=Offline → connected/connecting=false,
// поэтому serverSettingsAvailable даёт true только при sync OFF (клиент-локальные настройки),
// а при sync ON остаётся скрытым (пушить на сервер нечем без живого SSH активного профиля).
// а при sync ON остаётся скрытым (пушить на сервер нечем без живого SSH активного сервера).
val showServerSettings = serverSettingsAvailable(connected || connecting, syncOn)
val entryCount = if (showServerSettings) 3 else 2
SettingsGroup {
@@ -559,7 +559,7 @@ fun ServerDetailScreen(
iconRes = R.drawable.mobile_24px,
title = stringResource(R.string.provider_connection_settings),
subtitle = stringResource(R.string.provider_connection_settings_desc),
onClick = { onOpenConnection(profileId) }
onClick = { onOpenConnection(serverId) }
)
}
SettingsGroupItem(1, entryCount) {
@@ -567,7 +567,7 @@ fun ServerDetailScreen(
iconRes = R.drawable.wifi_24px,
title = stringResource(R.string.connection_mode_title),
subtitle = stringResource(R.string.provider_connection_mode_desc),
onClick = { onOpenConnectionMode(profileId) }
onClick = { onOpenConnectionMode(serverId) }
)
}
if (showServerSettings) {
@@ -576,7 +576,7 @@ fun ServerDetailScreen(
iconRes = R.drawable.database_24px,
title = stringResource(R.string.provider_server_settings),
subtitle = stringResource(R.string.provider_server_settings_desc),
onClick = { onOpenServerSettings(profileId) }
onClick = { onOpenServerSettings(serverId) }
)
}
}
@@ -584,13 +584,13 @@ fun ServerDetailScreen(
// «Отладочная информация» — отдельный экран, вход гейтится глобальным
// nerdMode (Продвинутые → Режим отладки).
if (nerdMode && profile != null) {
if (nerdMode && server != null) {
SettingsCard {
SettingsEntryRow(
iconRes = R.drawable.terminal_24px,
title = stringResource(R.string.nerd_section_title),
subtitle = stringResource(R.string.nerd_section_desc),
onClick = { onOpenNerdInfo(profileId) }
onClick = { onOpenNerdInfo(serverId) }
)
}
}
@@ -598,24 +598,24 @@ fun ServerDetailScreen(
}
}
if (showDelete && profile != null) {
if (showDelete && server != null) {
AlertDialog(
onDismissRequest = { showDelete = false },
title = { Text(stringResource(R.string.server_delete_confirm_title)) },
text = { Text(stringResource(R.string.server_delete_confirm_desc, profile.name)) },
text = { Text(stringResource(R.string.server_delete_confirm_desc, server.name)) },
confirmButton = {
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.ERROR)
settingsViewModel.deleteProfile(profileId)
settingsViewModel.deleteServer(serverId)
showDelete = false
// Навигацию назад делает null-guard выше (profile станет null
// Навигацию назад делает null-guard выше (server станет null
// после async-удаления) — не зовём pop тут, иначе двойной pop.
},
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
)
) { Text(stringResource(R.string.profile_delete)) }
) { Text(stringResource(R.string.server_delete)) }
},
dismissButton = {
TextButton(onClick = { showDelete = false }) { Text(stringResource(R.string.cancel)) }
@@ -623,8 +623,8 @@ fun ServerDetailScreen(
)
}
if (showRename && profile != null) {
var newName by remember(profile.id) { mutableStateOf(profile.name) }
if (showRename && server != null) {
var newName by remember(server.id) { mutableStateOf(server.name) }
AlertDialog(
onDismissRequest = { showRename = false },
title = { Text(stringResource(R.string.rename_server_title)) },
@@ -641,7 +641,7 @@ fun ServerDetailScreen(
TextButton(
onClick = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
settingsViewModel.renameProfile(profileId, newName)
settingsViewModel.renameServer(serverId, newName)
showRename = false
},
enabled = newName.isNotBlank()
@@ -847,7 +847,7 @@ private fun FailedContent(onRetry: () -> Unit) {
}
}
/** Неактивный профиль — hero + «Сделать активным». Адреса не дублируем: они в шапке хаба. */
/** Неактивный сервер — hero + «Сделать активным». Адреса не дублируем: они в шапке хаба. */
@Composable
private fun OfflineContent(onActivate: () -> Unit) {
StatusHero(
@@ -880,24 +880,24 @@ private fun versionLabel(version: String): String = "v${version.removePrefix("v"
/**
* «Отладочная информация» — отдельный экран (вход из хаба, гейт по nerdMode): отладочные
* per-profile флаги (подробные логи, показ логов) + состояние ядра + журнал сервера
* per-server флаги (подробные логи, показ логов) + состояние ядра + журнал сервера
* и SSH-лог. Потоки логов собираем только здесь — хаб на них не подписан.
*/
@Composable
fun NerdScreen(
profileId: String,
serverId: String,
settingsViewModel: SettingsViewModel,
serverViewModel: ServerViewModel,
onBack: () -> Unit
) {
val snapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle()
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val coreStatus by serverViewModel.hubStatus.collectAsStateWithLifecycle()
val profile = snapshot.list.firstOrNull { it.id == profileId }
val isActive = snapshot.activeId == profileId
val server = snapshot.list.firstOrNull { it.id == serverId }
val isActive = snapshot.activeId == serverId
// Профиль удалён — выходим назад (как в хабе).
if (snapshot.loaded && profile == null) {
// Сервер удалён — выходим назад (как в хабе).
if (snapshot.loaded && server == null) {
LaunchedEffect(Unit) { onBack() }
return
}
@@ -932,9 +932,9 @@ fun NerdScreen(
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
if (profile != null) {
if (server != null) {
NerdContent(
profile = profile,
server = server,
online = online,
privacyMode = privacyMode,
settingsViewModel = settingsViewModel,
@@ -948,19 +948,19 @@ fun NerdScreen(
@Composable
private fun NerdContent(
profile: Profile,
server: Server,
online: ServerHubStatus.Online?,
privacyMode: Boolean,
settingsViewModel: SettingsViewModel,
serverViewModel: ServerViewModel
) {
val context = LocalContext.current
val profileId = profile.id
val client = profile.client
val serverId = server.id
val client = server.client
val sshLog by serverViewModel.sshLog.collectAsStateWithLifecycle()
val journalLoading by serverViewModel.journalLoading.collectAsStateWithLifecycle()
// Per-profile отладочные флаги. updateProfileClient разводит active/inactive и
// Per-server отладочные флаги. updateServerClient разводит active/inactive и
// применяет logsEnabled живьём — отдельные VM-сеттеры не нужны.
SettingsGroup {
SettingsGroupItem(0, 2) {
@@ -969,7 +969,7 @@ private fun NerdContent(
subtitle = stringResource(R.string.debug_mode_desc),
checked = client.debugMode,
onCheckedChange = { v ->
settingsViewModel.updateProfileClient(profileId) { it.copy(debugMode = v) }
settingsViewModel.updateServerClient(serverId) { it.copy(debugMode = v) }
}
)
}
@@ -979,7 +979,7 @@ private fun NerdContent(
subtitle = stringResource(R.string.logs_enabled_desc),
checked = client.logsEnabled,
onCheckedChange = { v ->
settingsViewModel.updateProfileClient(profileId) { it.copy(logsEnabled = v) }
settingsViewModel.updateServerClient(serverId) { it.copy(logsEnabled = v) }
}
)
}
@@ -989,7 +989,7 @@ private fun NerdContent(
if (online != null) CoreStateCard(online, privacyMode)
// Параметры запуска реконструируются из конфига — видны всегда, даже оффлайн.
LaunchParamsCard(profile, privacyMode)
LaunchParamsCard(server, privacyMode)
// Единый SSH-лог: копит весь вывод команд (включая ошибки сопряжения и server.log,
// который тянется кнопкой ниже). Показываем при живом SSH (нужна кнопка журнала)
@@ -1035,7 +1035,7 @@ private fun CoreStateCard(online: ServerHubStatus.Online, privacyMode: Boolean)
online.version?.takeIf { it.isNotBlank() }?.let {
NerdStateRow(stringResource(R.string.nerd_version_label), versionLabel(it), mono = true)
}
NerdStateRow(stringResource(R.string.profile_has_ssh), online.sshIp.redact(privacyMode), mono = true)
NerdStateRow(stringResource(R.string.server_has_ssh), online.sshIp.redact(privacyMode), mono = true)
}
}
}
@@ -1070,9 +1070,9 @@ private fun NerdStateRow(label: String, value: String, mono: Boolean = false) {
* Секреты (obf-ключ, vk-ссылка, адрес пира/TURN) маскируются под privacyMode.
*/
@Composable
private fun LaunchParamsCard(profile: Profile, privacyMode: Boolean) {
val serverCmd = remember(profile, privacyMode) { serverCommandLine(profile, privacyMode) }
val clientCmd = remember(profile, privacyMode) { clientCommandLine(profile, privacyMode) }
private fun LaunchParamsCard(server: Server, privacyMode: Boolean) {
val serverCmd = remember(server, privacyMode) { serverCommandLine(server, privacyMode) }
val clientCmd = remember(server, privacyMode) { clientCommandLine(server, privacyMode) }
Surface(
shape = MaterialTheme.shapes.large,
color = MaterialTheme.colorScheme.surfaceContainerLow,
@@ -1105,8 +1105,8 @@ private fun LaunchParamBlock(label: String, commandLine: String) {
private val CLIENT_SECRET_FLAGS = setOf("-peer", "-link", "-obf-key", "-turn")
/** Командная строка клиентского ядра (как в движке) с маской секретов. */
private fun clientCommandLine(profile: Profile, privacy: Boolean): String {
val argv = CoreArgs.client(profile.client, profile.server)
private fun clientCommandLine(server: Server, privacy: Boolean): String {
val argv = CoreArgs.client(server.client, server.opts)
val sb = StringBuilder("freeturn")
var i = 0
while (i < argv.size) {
@@ -1123,13 +1123,13 @@ private fun clientCommandLine(profile: Profile, privacy: Boolean): String {
}
/** Командная строка серверного ядра (как уходит по SSH в free-turn-control.sh). */
private fun serverCommandLine(profile: Profile, privacy: Boolean): String {
private fun serverCommandLine(server: Server, privacy: Boolean): String {
val opts = ServerOptions(
listen = profile.proxyListen,
connect = profile.proxyConnect,
tcpMode = profile.client.tcpForward,
obfProfile = if (profile.server.obfEnabled) profile.server.obfProfile else ObfProfile.NONE,
obfKey = if (profile.server.obfEnabled) profile.server.obfKey else ""
listen = server.proxyListen,
connect = server.proxyConnect,
tcpMode = server.client.tcpForward,
obfProfile = if (server.opts.obfEnabled) server.opts.obfProfile else ObfProfile.NONE,
obfKey = if (server.opts.obfEnabled) server.opts.obfKey else ""
)
// Серверные флаги в форме --flag=value: маскируем хвост после '=' у секретов.
val shown = ServerCommand.Start(opts).toArgv().joinToString(" ") { tok ->
@@ -95,7 +95,7 @@ fun SplitTunnelModal(
/**
* Лист split-tunneling с главного экрана. Один общий sheet: свитч вкл/выкл,
* выбор режима (include/exclude), поиск и список приложений с иконками/чекбоксами.
* Всё пишется сразу в активный профиль через ViewModel — без буфера и «сохранить».
* Всё пишется сразу в активный сервер через ViewModel — без буфера и «сохранить».
*
* Свитч выкл == режим [SplitTunnelMode.ALL] (весь трафик в туннель). Пока прокси
* активен (`locked`), любые изменения запрещены — контролы disabled.
@@ -82,9 +82,9 @@ fun SshSetupScreen(
onConnected: () -> Unit,
onBack: () -> Unit
) {
// Экран не профиль-скоупный (правит активный SSH). Все профили удалены, пока экран
// Экран не сервер-скоупный (правит активный SSH). Все серверы удалены, пока экран
// висел в стеке вкладки — выходим назад: иначе форма пишет в осиротевший конфиг.
val snapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle()
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
if (snapshot.loaded && snapshot.list.isEmpty()) {
LaunchedEffect(Unit) { onBack() }
return
@@ -43,8 +43,8 @@ class ServerViewModel(
val isRegeneratingObfKey: StateFlow<Boolean> = _isRegeneratingObfKey.asStateFlow()
/**
* Сводный статус АКТИВНОГО сервера для хаба — одна модель из 2 потоков. Profile-контекст
* (активность профиля, наличие SSH) добавляет экран. Промежуточные фазы коллапсятся в
* Сводный статус АКТИВНОГО сервера для хаба — одна модель из 2 потоков. Server-контекст
* (активность сервера, наличие SSH) добавляет экран. Промежуточные фазы коллапсятся в
* [ServerHubStatus.Connecting]: от cold start до готовности — один переход в [ServerHubStatus.Online].
*/
val hubStatus: StateFlow<ServerHubStatus> =
@@ -9,8 +9,8 @@ import com.freeturn.app.ProxyServiceState
import com.freeturn.app.data.AppPreferences
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.Server
import com.freeturn.app.data.ServersSnapshot
import com.freeturn.app.domain.AppUpdater
import com.freeturn.app.domain.LocalProxyManager
import com.freeturn.app.domain.ProxyOrchestrator
@@ -58,8 +58,8 @@ class SettingsViewModel(
val nerdMode: StateFlow<Boolean> = prefs.nerdModeFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val profilesSnapshot: StateFlow<ProfilesSnapshot> = prefs.profilesSnapshot
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot())
val serversSnapshot: StateFlow<ServersSnapshot> = prefs.serversSnapshot
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ServersSnapshot())
val updateState: StateFlow<UpdateState> = appUpdater.state
@@ -72,7 +72,7 @@ class SettingsViewModel(
private val _privacyMode = MutableStateFlow(false)
val privacyMode: StateFlow<Boolean> = _privacyMode.asStateFlow()
private val profileMutex = Mutex()
private val serverMutex = Mutex()
// Дебаунс быстрых тыков тоггла синка: persist мгновенный, а дорогой сетевой
// side-effect (SSH stop+start + рестарт прокси) откладывается и коалесцируется.
@@ -106,12 +106,12 @@ class SettingsViewModel(
viewModelScope.launch { prefs.setTgSubscribeShown() }
}
// expectedActiveId — профиль, который правил экран. Сменился за время дебаунса —
// сейв отбрасываем, иначе старые поля затрут чужой профиль. null — legacy-режим.
// expectedActiveId — сервер, который правил экран. Сменился за время дебаунса —
// сейв отбрасываем, иначе старые поля затрут чужой сервер. null — legacy-режим.
fun saveClientConfig(config: ClientConfig, expectedActiveId: String? = null) {
viewModelScope.launch {
val saved = profileMutex.withLock {
val activeId = prefs.profilesSnapshot.first().activeId
val saved = serverMutex.withLock {
val activeId = prefs.serversSnapshot.first().activeId
if (expectedActiveId != null && expectedActiveId != activeId) return@withLock false
persistClient(config)
true
@@ -120,12 +120,12 @@ class SettingsViewModel(
}
}
// Во всех сеттерах read-modify-write выполняется ВНУТРИ profileMutex: чтение
// Во всех сеттерах read-modify-write выполняется ВНУТРИ serverMutex: чтение
// current вне лока давало lost update — два параллельных сеттера читали один
// снапшот, затем по очереди писали свой copy(), и второй затирал первого.
fun setSplitTunnelMode(value: String) {
viewModelScope.launch {
profileMutex.withLock {
serverMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.splitTunnelMode == value) return@withLock
persistClient(current.copy(splitTunnelMode = value))
@@ -135,7 +135,7 @@ class SettingsViewModel(
fun setSplitTunnelApps(value: String) {
viewModelScope.launch {
profileMutex.withLock {
serverMutex.withLock {
val current = prefs.clientConfigFlow.first()
val trimmed = value.trim()
if (current.splitTunnelApps == trimmed) return@withLock
@@ -146,22 +146,22 @@ class SettingsViewModel(
fun saveProxyServerConfig(listen: String, connect: String) {
viewModelScope.launch {
profileMutex.withLock { prefs.saveProxyConfig(listen, connect); mirrorActiveProfile() }
serverMutex.withLock { prefs.saveProxyConfig(listen, connect); mirrorActiveServer() }
}
}
// --- Profiles ---
// Создание профиля (сервера) ушло из листа на главном: появится отдельным
// --- Servers ---
// Создание сервера ушло из листа на главном: появится отдельным
// экраном добавления сервера.
private suspend fun mirrorActiveProfile() {
val current = prefs.profilesSnapshot.first()
private suspend fun mirrorActiveServer() {
val current = prefs.serversSnapshot.first()
val activeId = current.activeId ?: return
val ssh = prefs.sshConfigFlow.first()
val client = prefs.clientConfigFlow.first()
val listen = prefs.proxyListenFlow.first()
val connect = prefs.proxyConnectFlow.first()
val server = prefs.serverOptsFlow.first()
val serverOpts = prefs.serverOptsFlow.first()
val updated = current.list.map {
if (it.id == activeId)
it.copy(
@@ -169,45 +169,45 @@ class SettingsViewModel(
client = client,
proxyListen = listen,
proxyConnect = connect,
server = server
opts = serverOpts
)
else it
}
if (updated != current.list) prefs.saveProfiles(updated)
if (updated != current.list) prefs.saveServers(updated)
}
// Пишет legacy + зеркалит в активный профиль. Только под profileMutex; НЕ из
// applyProfile/deleteProfile (там грузится снимок, mirror словил бы гонку).
// Пишет legacy + зеркалит в активный сервер. Только под serverMutex; НЕ из
// applyServer/deleteServer (там грузится снимок, mirror словил бы гонку).
private suspend fun persistClient(config: ClientConfig) {
prefs.saveClientConfig(config)
mirrorActiveProfile()
mirrorActiveServer()
}
fun renameProfile(id: String, name: String) {
fun renameServer(id: String, name: String) {
viewModelScope.launch {
profileMutex.withLock {
val current = prefs.profilesSnapshot.first()
serverMutex.withLock {
val current = prefs.serversSnapshot.first()
val target = current.list.firstOrNull { it.id == id } ?: return@withLock
val base = name.trim().ifBlank { target.name }
val unique = uniqueProfileName(base, current.list, id)
val unique = uniqueServerName(base, current.list, id)
val updated = current.list.map {
if (it.id == id) it.copy(name = unique) else it
}
prefs.saveProfiles(updated)
prefs.saveServers(updated)
}
}
}
fun applyProfile(id: String) {
fun applyServer(id: String) {
viewModelScope.launch {
val target = profileMutex.withLock {
val current = prefs.profilesSnapshot.first()
val target = serverMutex.withLock {
val current = prefs.serversSnapshot.first()
val t = current.list.firstOrNull { it.id == id } ?: return@withLock null
prefs.saveSshConfig(t.ssh)
prefs.saveClientConfig(t.client)
prefs.saveProxyConfig(t.proxyListen, t.proxyConnect)
prefs.saveServerOpts(t.server)
prefs.setActiveProfileId(t.id)
prefs.saveServerOpts(t.opts)
prefs.setActiveServerId(t.id)
t
} ?: return@launch
@@ -224,27 +224,27 @@ class SettingsViewModel(
}
}
fun deleteProfile(id: String) {
fun deleteServer(id: String) {
viewModelScope.launch {
profileMutex.withLock {
val current = prefs.profilesSnapshot.first()
serverMutex.withLock {
val current = prefs.serversSnapshot.first()
val remaining = current.list.filterNot { it.id == id }
prefs.saveProfiles(remaining)
prefs.saveServers(remaining)
if (current.activeId == id) {
val next = remaining.firstOrNull()
prefs.setActiveProfileId(next?.id)
prefs.setActiveServerId(next?.id)
if (next != null) {
prefs.saveSshConfig(next.ssh)
prefs.saveClientConfig(next.client)
prefs.saveProxyConfig(next.proxyListen, next.proxyConnect)
prefs.saveServerOpts(next.server)
prefs.saveServerOpts(next.opts)
}
}
}
}
}
private fun uniqueProfileName(base: String, existing: List<Profile>, excludingId: String?): String {
private fun uniqueServerName(base: String, existing: List<Server>, excludingId: String?): String {
val taken = existing
.filter { it.id != excludingId }
.map { it.name.trim().lowercase() }
@@ -257,20 +257,20 @@ class SettingsViewModel(
}
// --- Edit-by-id (новый Settings-флоу) ---
// Правит client-конфиг профиля по id, НЕ требуя его активации. Для активного
// профиля дополнительно зеркалит в legacy-ключи (рантаймовое ядро их читает) и
// Правит client-конфиг сервера по id, НЕ требуя его активации. Для активного
// сервера дополнительно зеркалит в legacy-ключи (рантаймовое ядро их читает) и
// обновляет глобальный флаг логов. Для неактивного — пишет только сохранённый
// снимок, рантайм не трогается (нужно для редактирования неактивных серверов).
fun updateProfileClient(id: String, transform: (ClientConfig) -> ClientConfig) {
fun updateServerClient(id: String, transform: (ClientConfig) -> ClientConfig) {
viewModelScope.launch {
var mirrored: ClientConfig? = null
profileMutex.withLock {
val snap = prefs.profilesSnapshot.first()
serverMutex.withLock {
val snap = prefs.serversSnapshot.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)
prefs.saveServers(list)
if (id == snap.activeId) {
prefs.saveClientConfig(updated)
mirrored = updated
@@ -283,7 +283,7 @@ class SettingsViewModel(
// --- Server & Proxy Switches (TcpForward, Bond, Obf, Sync) ---
fun setBond(enabled: Boolean) {
viewModelScope.launch {
val changed = profileMutex.withLock {
val changed = serverMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.bond == enabled) return@withLock false
persistClient(current.copy(bond = enabled))
@@ -295,7 +295,7 @@ class SettingsViewModel(
fun setSyncServerSwitches(enabled: Boolean) {
viewModelScope.launch {
val changed = profileMutex.withLock {
val changed = serverMutex.withLock {
val current = prefs.clientConfigFlow.first()
if (current.syncServerSwitches == enabled) return@withLock false
persistClient(current.copy(syncServerSwitches = enabled))
@@ -345,7 +345,7 @@ class SettingsViewModel(
sshRepository.generateObfKey()?.takeIf { it.isNotBlank() }
else null
var changed = false
profileMutex.withLock {
serverMutex.withLock {
if (prefs.proxyListenFlow.first() != listen || prefs.proxyConnectFlow.first() != connect) {
prefs.saveProxyConfig(listen, connect); changed = true
}
@@ -357,7 +357,7 @@ class SettingsViewModel(
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) mirrorActiveServer()
}
if (changed) {
if (sync) orchestrator.restartServerIfRunning()
@@ -367,12 +367,12 @@ class SettingsViewModel(
}
/**
* Apply-модель «Настроек сервера» для НЕактивного профиля (sync OFF): серверные
* параметры тут клиент-локальны, поэтому пишем ТОЛЬКО снимок профиля по id — ни
* Apply-модель «Настроек сервера» для НЕактивного сервера (sync OFF): серверные
* параметры тут клиент-локальны, поэтому пишем ТОЛЬКО снимок сервера по id — ни
* legacy-ключи, ни рантайм (SSH/прокси активного сервера) не трогаем. Без живого SSH
* obf-ключ на сервере не генерим: пустой остаётся пустым (клиент стартует как есть).
*/
fun applyProfileServerConfig(
fun updateServerConfig(
id: String,
listen: String,
connect: String,
@@ -381,18 +381,18 @@ class SettingsViewModel(
obfKey: String
) {
viewModelScope.launch {
profileMutex.withLock {
val snap = prefs.profilesSnapshot.first()
serverMutex.withLock {
val snap = prefs.serversSnapshot.first()
val target = snap.list.firstOrNull { it.id == id } ?: return@withLock
val effKey = obfKey.trim().ifBlank { target.server.obfKey }
val effKey = obfKey.trim().ifBlank { target.opts.obfKey }
val next = target.copy(
proxyListen = listen,
proxyConnect = connect,
client = target.client.copy(tcpForward = tcpForward),
server = target.server.copy(obfProfile = obfProfile, obfKey = effKey)
opts = target.opts.copy(obfProfile = obfProfile, obfKey = effKey)
)
if (next == target) return@withLock
prefs.saveProfiles(snap.list.map { if (it.id == id) next else it })
prefs.saveServers(snap.list.map { if (it.id == id) next else it })
}
}
}
+7 -7
View File
@@ -173,9 +173,9 @@
<string name="tg_subscribe_btn">Подписаться</string>
<string name="tg_not_now">Не сейчас</string>
<!-- Profiles -->
<string name="profile_delete">Удалить</string>
<string name="profile_unsaved_label">Не сохранено</string>
<!-- Servers -->
<string name="server_delete">Удалить</string>
<string name="server_unsaved_label">Не сохранено</string>
<!-- Notification & Tile -->
<string name="notif_proxy_stop_action">Отключить</string>
@@ -197,8 +197,8 @@
<string name="split_tunnel_status_off">Раздельное туннелирование выключено</string>
<string name="split_tunnel_status_on">Раздельное туннелирование включено</string>
<!-- Profiles sheet (servers) -->
<string name="profiles_servers_title">Серверы</string>
<!-- Servers sheet -->
<string name="servers_sheet_title">Серверы</string>
<!-- Логи -->
<string name="logs_enabled">Показывать логи</string>
@@ -254,8 +254,8 @@
<string name="server_inactive_title">Сервер не активен</string>
<string name="server_inactive_desc">Чтобы управлять ядром и SSH-подключением, сделайте этот сервер активным.</string>
<string name="make_active">Сделать активным</string>
<string name="profile_active_badge">Активный</string>
<string name="profile_has_ssh">SSH</string>
<string name="server_active_badge">Активный</string>
<string name="server_has_ssh">SSH</string>
<string name="menu_delete_server">Удалить сервер</string>
<string name="menu_rename_server">Переименовать</string>
<string name="rename_server_title">Переименовать сервер</string>