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