Выпуск WDTT Plus v7

This commit is contained in:
Ivan4537 committed 2026-07-05 21:58:23 +03:00
1 parent 1b8aee591c
commit b1418ff3d8
15 files changed
+1200 -201

No files matched your search

+16
View File
@@ -2,6 +2,22 @@
Здесь фиксируются заметные пользовательские изменения WDTT Plus. Здесь фиксируются заметные пользовательские изменения WDTT Plus.
## v7 — 05.07.2026
### Надёжность и данные
- Установка сервера больше не заменяет сохранённые данные владельца пустыми или стандартными полями вкладки «Туннель».
- Полный и частичный экспорт сервера получили отдельные описания и строгую проверку состава; полный экспорт требует WireGuard-ключи сервера.
- Импорт сервера создаёт страховочную копию, проверяет перенесённые данные и восстанавливает прежнее состояние при ошибке.
- При добавлении данных на существующий сервер проверяются конфликты устройств, а совпадающие внутренние IP безопасно переназначаются.
- Автоматическое обновление клиентов и состояния выходного IP выполняется один раз за запуск для текущего сервера; результат сохраняется при переключении вкладок, ручное обновление остаётся доступным.
### Интерфейс
- Блок «Клиенты и сервер» свёрнут по умолчанию и получил карточку состояния с временем проверки и отдельный блок серверных действий.
- Верхняя панель вкладки «Исключения» плавно скрывается и возвращается вместе с обычной и инерционной прокруткой списка приложений.
- Исправлено переименование VPN-профилей: названия могут содержать пробелы между словами.
## v6 — 05.07.2026 ## v6 — 05.07.2026
### Интерфейс ### Интерфейс
+2 -2
View File
@@ -45,7 +45,7 @@
### Что изменено в модификации ### Что изменено в модификации
- **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Клиента можно перенести отдельно через QR, камеру, изображение, файл, Android Share или код передачи; создать с автоматическим или заданным вручную паролем и безопасно сменить пароль без перезапуска сервера. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями. - **Расширенное управление сервером:** клиентов и основные параметры сервера можно обслуживать прямо из приложения без Telegram. Клиента можно перенести отдельно через QR, камеру, изображение, файл, Android Share или код передачи; создать с автоматическим или заданным вручную паролем и безопасно сменить пароль без перезапуска сервера. Telegram-бот остаётся альтернативным удалённым пультом с теми же основными операциями.
- **Обновление, восстановление и перенос сервера:** повторный деплой предлагает безопасное обновление с сохранением данных или чистую установку. Перед обновлением создаётся страховочная копия сервера; новая служба и целостность доступов проверяются, а при ошибке выполняется откат. Экспорт/импорт переносит базу доступов и при необходимости WireGuard-ключи. - **Обновление, восстановление и перенос сервера:** повторный деплой предлагает безопасное обновление с сохранением данных или чистую установку. Перед обновлением и прямым импортом создаётся страховочная копия; служба и целостность доступов проверяются, а при ошибке выполняется откат. Частичный экспорт переносит базу WDTT Plus, полный дополнительно сохраняет WireGuard-ключи сервера.
- **Ссылки, роли и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Импорт проверяется и занимает свободный VPN-профиль; при трёх занятых приложение запрашивает выбор профиля для замены. Переименованный профиль передаёт своё название вместе с подключением. Для администратора доступен защищённый паролем перенос локальных настроек. - **Ссылки, роли и перенос между устройствами:** подключение можно передать ссылкой, файлом или QR-кодом, а получить — также камерой и из изображения. Импорт проверяется и занимает свободный VPN-профиль; при трёх занятых приложение запрашивает выбор профиля для замены. Переименованный профиль передаёт своё название вместе с подключением. Для администратора доступен защищённый паролем перенос локальных настроек.
- **Проверка VK-хешей:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Хеши можно копировать по одному или все заполненные сразу в порядке слотов. Настройка мощности сопровождается пояснением о потоках, нагрузке и частоте проверок VK. - **Проверка VK-хешей:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Хеши можно копировать по одному или все заполненные сразу в порядке слотов. Настройка мощности сопровождается пояснением о потоках, нагрузке и частоте проверок VK.
- **Настраиваемый выходной IP:** из Android и Telegram-бота управляются прямой выход, прокси VPS, внешний TCP-прокси, бесплатный WARP, готовый VPN/WireGuard-файл и WireGuard-выход через другой сервер. Приложение показывает состояние режимов на сервере, проверяет конфликтные маршруты перед включением и откатывается при ошибке. - **Настраиваемый выходной IP:** из Android и Telegram-бота управляются прямой выход, прокси VPS, внешний TCP-прокси, бесплатный WARP, готовый VPN/WireGuard-файл и WireGuard-выход через другой сервер. Приложение показывает состояние режимов на сервере, проверяет конфликтные маршруты перед включением и откатывается при ошибке.
@@ -110,7 +110,7 @@ Android-приложение → VpnService / WireGuard GoBackend → локал
Если на сервере уже есть установленный WDTT Plus, приложение покажет предупреждение перед деплоем. Режим **«Обновить с сохранением»** заменит серверный бинарник и применит настройки из текущих полей деплоя, сохранив выданные ссылки, привязки устройств, историю и WireGuard-ключи. Режим **«Начать с нуля»** удалит серверные данные WDTT Plus и развернёт чистую установку. Если на сервере уже есть установленный WDTT Plus, приложение покажет предупреждение перед деплоем. Режим **«Обновить с сохранением»** заменит серверный бинарник и применит настройки из текущих полей деплоя, сохранив выданные ссылки, привязки устройств, историю и WireGuard-ключи. Режим **«Начать с нуля»** удалит серверные данные WDTT Plus и развернёт чистую установку.
Для переноса на другой сервер во вкладке **«Деплой»** используйте блок **«Перенос сервера»**. Экспорт проверяет доступ к серверу и структуру базы перед сохранением файла, затем сохраняет пароли, Telegram-настройки, привязки устройств и историю. Полный экспорт дополнительно сохраняет WireGuard-ключи сервера/клиентов: это полезно при переезде своего сервера, чтобы привязки устройств и серверная WireGuard-идентичность сохранились. Старые `wdtt://` ссылки останутся рабочими без перевыдачи только если в них был домен и DNS этого домена теперь указывает на новый сервер; ссылки со старым IP нужно сгенерировать и отправить пользователям заново. Импорт можно выполнить при деплое или на уже работающем сервере: режим **«Заменить»** подходит для переезда, режим **«Добавить»** добавляет отсутствующие записи без перезаписи конфликтов. Перед применением приложение показывает подтверждение и берёт новый адрес сервера, порты и DNS из текущих полей деплоя. Настройки выходного IP, прокси, WARP и VPN/WireGuard-файлы серверным экспортом не переносятся — после переезда нужный режим выхода включается на новом сервере заново. Для переноса на другой сервер во вкладке **«Деплой»** используйте блок **«Перенос сервера»**. Частичный экспорт сохраняет базу WDTT Plus: профиль владельца, Telegram-настройки, клиентов, привязки устройств, статистику и историю. Полный экспорт дополнительно требует и сохраняет WireGuard-ключи сервера. Старые `wdtt://` ссылки останутся рабочими без перевыдачи, если в них был домен, DNS указывает на новый сервер и сохранены прежние порты; для ссылок со старым IP или при смене портов создайте новые. Импорт можно выполнить при деплое или на работающем сервере: режим **«Заменить»** подходит для переезда, режим **«Добавить»** переносит отсутствующие записи, проверяет конфликты устройств и назначает свободные внутренние IP. Перед изменением создаётся страховочная копия, после импорта проверяются данные и служба, а при ошибке выполняется откат. Настройки выходного IP, прокси, WARP и VPN/WireGuard-файлы серверным экспортом не переносятся.
## Получение VK-хеша ## Получение VK-хеша
+25 -8
View File
@@ -1279,8 +1279,16 @@ func adminUpdateAdminProfile(configDir string, loaded *Database, args []string)
if err := fs.Parse(args); err != nil { if err := fs.Parse(args); err != nil {
return adminResponse{}, err return adminResponse{}, err
} }
provided := make(map[string]bool)
fs.Visit(func(value *flag.Flag) {
provided[value.Name] = true
})
if len(provided) == 0 {
return adminResponse{OK: true, Message: "Профиль владельца не изменён", Server: buildAdminServerInfo(configDir, loaded)}, nil
}
profile := loaded.AdminProfile profile := normalizeAdminProfileForStorage(loaded.AdminProfile, loaded.DefaultPorts)
if provided["vk-hashes"] {
profile.VkHashes = "" profile.VkHashes = ""
if strings.TrimSpace(*vkHashes) != "" { if strings.TrimSpace(*vkHashes) != "" {
normalized, err := normalizeVKHashesInput(*vkHashes) normalized, err := normalizeVKHashesInput(*vkHashes)
@@ -1289,6 +1297,8 @@ func adminUpdateAdminProfile(configDir string, loaded *Database, args []string)
} }
profile.VkHashes = normalized profile.VkHashes = normalized
} }
}
if provided["secondary-vk-hash"] {
profile.SecondaryVkHash = "" profile.SecondaryVkHash = ""
if strings.TrimSpace(*secondaryVkHash) != "" { if strings.TrimSpace(*secondaryVkHash) != "" {
normalized, err := normalizeVKHashesInput(*secondaryVkHash) normalized, err := normalizeVKHashesInput(*secondaryVkHash)
@@ -1297,35 +1307,42 @@ func adminUpdateAdminProfile(configDir string, loaded *Database, args []string)
} }
profile.SecondaryVkHash = normalized profile.SecondaryVkHash = normalized
} }
}
if provided["profile-name"] {
profile.ProfileName = normalizeAdminProfileName(*profileName) profile.ProfileName = normalizeAdminProfileName(*profileName)
}
if provided["workers"] {
if *workers < 1 || *workers > 128 { if *workers < 1 || *workers > 128 {
return adminResponse{}, errors.New("workers должен быть 1..128") return adminResponse{}, errors.New("workers должен быть 1..128")
} }
profile.WorkersPerHash = *workers profile.WorkersPerHash = *workers
}
if provided["protocol"] {
normalizedProtocol, err := normalizeAdminProfileProtocol(*protocol) normalizedProtocol, err := normalizeAdminProfileProtocol(*protocol)
if err != nil { if err != nil {
return adminResponse{}, err return adminResponse{}, err
} }
profile.Protocol = normalizedProtocol profile.Protocol = normalizedProtocol
if strings.TrimSpace(*ports) != "" { }
if provided["ports"] {
normalizedPorts, err := parsePortsSpec(*ports) normalizedPorts, err := parsePortsSpec(*ports)
if err != nil { if err != nil {
return adminResponse{}, err return adminResponse{}, err
} }
profile.Ports = normalizedPorts profile.Ports = normalizedPorts
} else {
profile.Ports = loaded.DefaultPorts
} }
if *listenPort < 0 || *listenPort > 65535 { if provided["listen-port"] {
if *listenPort < 1 || *listenPort > 65535 {
return adminResponse{}, errors.New("listen-port должен быть 1..65535") return adminResponse{}, errors.New("listen-port должен быть 1..65535")
} }
if *listenPort > 0 {
profile.ListenPort = *listenPort profile.ListenPort = *listenPort
} else {
profile.ListenPort = adminProfileDefaultListenPort(profile.Ports)
} }
if provided["sni"] {
profile.SNI = normalizeAdminProfileSNI(*sni) profile.SNI = normalizeAdminProfileSNI(*sni)
}
if provided["no-dns"] {
profile.NoDNS = *noDNS profile.NoDNS = *noDNS
}
profile.UpdatedAt = time.Now().Unix() profile.UpdatedAt = time.Now().Unix()
profile = normalizeAdminProfileForStorage(profile, loaded.DefaultPorts) profile = normalizeAdminProfileForStorage(profile, loaded.DefaultPorts)
+16
View File
@@ -123,6 +123,22 @@ func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) {
t.Fatalf("owner profile on disk differs from live state: disk=%#v live=%#v", persisted.AdminProfile, profile) t.Fatalf("owner profile on disk differs from live state: disk=%#v live=%#v", persisted.AdminProfile, profile)
} }
request("update-admin-profile", "--vk-hashes", "fedcba9876543210")
patchedOwner := request("list").Server.AdminProfile
if patchedOwner.VkHashes != "fedcba9876543210" {
t.Fatalf("owner profile patch did not update VK hashes: %#v", patchedOwner)
}
if patchedOwner.SecondaryVkHash != profile.SecondaryVkHash ||
patchedOwner.ProfileName != profile.ProfileName ||
patchedOwner.WorkersPerHash != profile.WorkersPerHash ||
patchedOwner.Protocol != profile.Protocol ||
patchedOwner.ListenPort != profile.ListenPort ||
patchedOwner.SNI != profile.SNI ||
patchedOwner.NoDNS != profile.NoDNS ||
patchedOwner.Ports != profile.Ports {
t.Fatalf("owner profile patch erased fields that were not provided: before=%#v after=%#v", profile, patchedOwner)
}
dbMutex.Lock() dbMutex.Lock()
db.Devices["phone"] = &ClientDevice{DeviceID: "phone", IP: "10.66.66.2"} db.Devices["phone"] = &ClientDevice{DeviceID: "phone", IP: "10.66.66.2"}
db.Devices["orphan"] = &ClientDevice{DeviceID: "orphan", IP: "10.66.66.3"} db.Devices["orphan"] = &ClientDevice{DeviceID: "orphan", IP: "10.66.66.3"}
+2 -2
View File
@@ -5,7 +5,7 @@ plugins {
id("org.jetbrains.kotlin.plugin.compose") id("org.jetbrains.kotlin.plugin.compose")
} }
val appVersionName = "6" val appVersionName = "7"
val releaseApkBaseName = "WDTT-Plus" val releaseApkBaseName = "WDTT-Plus"
val localProperties = Properties() val localProperties = Properties()
@@ -22,7 +22,7 @@ android {
applicationId = "com.wdtt.plus" applicationId = "com.wdtt.plus"
minSdk = 28 minSdk = 28
targetSdk = 35 targetSdk = 35
versionCode = 6 versionCode = 7
versionName = appVersionName versionName = appVersionName
buildConfigField("String", "MOD_RELEASE_DATE", "\"05.07.2026\"") buildConfigField("String", "MOD_RELEASE_DATE", "\"05.07.2026\"")
@@ -284,21 +284,10 @@ object ServerAdminClient {
"--public-ip", publicHost.ifBlank { "auto" } "--public-ip", publicHost.ifBlank { "auto" }
)) ))
suspend fun updateAdminProfile(target: ServerAdminTarget, profile: ServerAdminProfileInfo): ServerAdminActionResult { suspend fun updateAdminProfileFromTunnel(
val args = mutableListOf( target: ServerAdminTarget,
"update-admin-profile", profile: ServerAdminProfileInfo
"--vk-hashes", profile.vkHashes.trim(), ): ServerAdminActionResult = runArgsAction(target, buildAdminProfilePatchArgs(profile))
"--secondary-vk-hash", profile.secondaryVkHash.trim(),
"--profile-name", profile.profileName.trim(),
"--workers", profile.workersPerHash.coerceIn(1, 128).toString(),
"--protocol", profile.protocol.trim().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
"--listen-port", profile.listenPort.coerceIn(1, 65535).toString(),
"--sni", profile.sni.trim(),
"--ports", profile.ports.trim().ifBlank { "56000,56001,9000" }
)
if (profile.noDns) args += "--no-dns"
return runArgsAction(target, args)
}
suspend fun refreshPublicHost(target: ServerAdminTarget): ServerAdminActionResult = suspend fun refreshPublicHost(target: ServerAdminTarget): ServerAdminActionResult =
runArgsAction(target, listOf("refresh-public-ip")) runArgsAction(target, listOf("refresh-public-ip"))
@@ -558,6 +547,46 @@ object ServerAdminClient {
} }
} }
internal fun hasMeaningfulAdminProfileFields(profile: ServerAdminProfileInfo): Boolean =
buildAdminProfilePatchArgs(profile).size > 1
internal fun buildAdminProfilePatchArgs(profile: ServerAdminProfileInfo): List<String> = buildList {
add("update-admin-profile")
profile.vkHashes.trim().takeIf { it.isNotBlank() }?.let {
add("--vk-hashes")
add(it)
}
profile.secondaryVkHash.trim().takeIf { it.isNotBlank() }?.let {
add("--secondary-vk-hash")
add(it)
}
vpnProfileRestorableName(profile.profileName).takeIf { it.isNotBlank() }?.let {
add("--profile-name")
add(it)
}
profile.workersPerHash.coerceIn(1, 128).takeIf { it != 16 }?.let {
add("--workers")
add(it.toString())
}
profile.protocol.trim().lowercase().takeIf { it == "tcp" }?.let {
add("--protocol")
add(it)
}
profile.listenPort.coerceIn(1, 65535).takeIf { it != 9000 }?.let {
add("--listen-port")
add(it.toString())
}
profile.sni.trim().takeIf { it.isNotBlank() }?.let {
add("--sni")
add(it)
}
profile.ports.trim().takeIf { it.isNotBlank() && it != "56000,56001,9000" }?.let {
add("--ports")
add(it)
}
if (profile.noDns) add("--no-dns")
}
private class AdminSshClient(private val session: Session, private val sudoPassword: String) { private class AdminSshClient(private val session: Session, private val sudoPassword: String) {
fun exec(command: String, timeout: Long): String { fun exec(command: String, timeout: Long): String {
if (!session.isConnected) throw IllegalStateException("SSH-сессия разорвана") if (!session.isConnected) throw IllegalStateException("SSH-сессия разорвана")
@@ -543,7 +543,7 @@ class SettingsStore(context: Context) {
val deviceCompatibilityCheckComplete: Flow<Boolean> = dataStore.data.map { val deviceCompatibilityCheckComplete: Flow<Boolean> = dataStore.data.map {
it[DEVICE_COMPATIBILITY_CHECK_COMPLETE] ?: false it[DEVICE_COMPATIBILITY_CHECK_COMPLETE] ?: false
} }
val deployClientsSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: true } val deployClientsSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: false }
val deployOutboundSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_OUTBOUND_SECTION_EXPANDED] ?: false } val deployOutboundSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_OUTBOUND_SECTION_EXPANDED] ?: false }
val deployMigrationSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_MIGRATION_SECTION_EXPANDED] ?: false } val deployMigrationSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_MIGRATION_SECTION_EXPANDED] ?: false }
val interfaceRole: Flow<String> = dataStore.data.map { it[INTERFACE_ROLE] ?: "" } val interfaceRole: Flow<String> = dataStore.data.map { it[INTERFACE_ROLE] ?: "" }
@@ -1293,11 +1293,23 @@ class SettingsStore(context: Context) {
fun vpnProfileDefaultName(profile: Int): String = "VPN ${profile.coerceIn(0, 2) + 1}" fun vpnProfileDefaultName(profile: Int): String = "VPN ${profile.coerceIn(0, 2) + 1}"
fun normalizeVpnProfileName(name: String): String = fun sanitizeVpnProfileNameInput(name: String): String {
name val safe = buildString {
.replace(Regex("\\s+"), " ") name.forEach { character ->
.trim() when {
character.isWhitespace() -> append(' ')
!Character.isISOControl(character) -> append(character)
}
}
}
return safe
.replace(Regex(" +"), " ")
.trimStart()
.take(48) .take(48)
}
fun normalizeVpnProfileName(name: String): String =
sanitizeVpnProfileNameInput(name).trimEnd()
fun vpnProfileDisplayName(profile: Int, names: List<String>): String { fun vpnProfileDisplayName(profile: Int, names: List<String>): String {
val clean = normalizeVpnProfileName(names.getOrNull(profile).orEmpty()) val clean = normalizeVpnProfileName(names.getOrNull(profile).orEmpty())
+476 -99
View File
@@ -63,6 +63,7 @@ import com.wdtt.plus.ServerAdminTarget
import com.wdtt.plus.SettingsStore import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager import com.wdtt.plus.TunnelManager
import com.wdtt.plus.WDTTColors import com.wdtt.plus.WDTTColors
import com.wdtt.plus.hasMeaningfulAdminProfileFields
import com.wdtt.plus.vpnProfileRestorableName import com.wdtt.plus.vpnProfileRestorableName
import com.wdtt.plus.vpnProfileDisplayName import com.wdtt.plus.vpnProfileDisplayName
import com.wdtt.plus.vpnProfileTransferName import com.wdtt.plus.vpnProfileTransferName
@@ -118,6 +119,21 @@ private enum class OwnerProfileSource {
LocalOnly LocalOnly
} }
internal fun shouldAutoRefreshOutboundState(
expanded: Boolean,
outboundBusy: Boolean,
snapshotBusy: Boolean,
hostValid: Boolean,
hasSshPassword: Boolean,
targetKey: String,
checkedTargetKey: String
): Boolean = expanded &&
!outboundBusy &&
!snapshotBusy &&
hostValid &&
hasSshPassword &&
checkedTargetKey != targetKey
private enum class ProxyKind(val label: String, val protocol: String) { private enum class ProxyKind(val label: String, val protocol: String) {
Socks5("SOCKS5", "socks5"), Socks5("SOCKS5", "socks5"),
Http("HTTP", "http") Http("HTTP", "http")
@@ -289,6 +305,23 @@ private data class OutboundServerSnapshot(
} }
} }
private data class OutboundProcessSnapshot(
val snapshot: OutboundServerSnapshot?,
val lastCheckAttemptAt: Long,
val lastCheckError: String,
val attempted: Boolean
)
private object OutboundProcessCache {
private val values = java.util.concurrent.ConcurrentHashMap<String, OutboundProcessSnapshot>()
fun get(targetKey: String): OutboundProcessSnapshot? = values[targetKey]
fun put(targetKey: String, snapshot: OutboundProcessSnapshot) {
values[targetKey] = snapshot
}
}
private enum class OutboundModeVisualState { private enum class OutboundModeVisualState {
Unknown, Unknown,
Off, Off,
@@ -628,6 +661,9 @@ fun DeployTab(
var outboundStatusOwner by rememberSaveable { mutableStateOf<String?>(null) } var outboundStatusOwner by rememberSaveable { mutableStateOf<String?>(null) }
var outboundSnapshot by remember { mutableStateOf<OutboundServerSnapshot?>(null) } var outboundSnapshot by remember { mutableStateOf<OutboundServerSnapshot?>(null) }
var outboundSnapshotBusy by remember { mutableStateOf(false) } var outboundSnapshotBusy by remember { mutableStateOf(false) }
var outboundLastCheckAttemptAt by remember { mutableLongStateOf(0L) }
var outboundLastCheckError by remember { mutableStateOf("") }
var outboundAutoCheckedTargetKey by remember { mutableStateOf("") }
var importedWgConfigText by rememberSaveable { mutableStateOf("") } var importedWgConfigText by rememberSaveable { mutableStateOf("") }
val outboundPrefs = remember { context.getSharedPreferences("wdtt_outbound_forms", Context.MODE_PRIVATE) } val outboundPrefs = remember { context.getSharedPreferences("wdtt_outbound_forms", Context.MODE_PRIVATE) }
var localProxyPortInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("local_proxy_port", "1080") ?: "1080") } var localProxyPortInput by rememberSaveable { mutableStateOf(outboundPrefs.getString("local_proxy_port", "1080") ?: "1080") }
@@ -675,8 +711,23 @@ fun DeployTab(
LaunchedEffect(savedPassword) { password = savedPassword } LaunchedEffect(savedPassword) { password = savedPassword }
LaunchedEffect(savedDns1) { dns1 = savedDns1 } LaunchedEffect(savedDns1) { dns1 = savedDns1 }
LaunchedEffect(savedDns2) { dns2 = savedDns2 } LaunchedEffect(savedDns2) { dns2 = savedDns2 }
LaunchedEffect(ip.trim(), login.trim(), savedSshPort) { val outboundTargetKey = remember(ip, login, password, savedSshPort) {
outboundSnapshot = null listOf(
ip.trim(),
login.ifBlank { "root" },
savedSshPort.ifBlank { "22" },
password.hashCode().toString()
).joinToString("\u0000")
}
val currentOutboundTargetKey by rememberUpdatedState(outboundTargetKey)
LaunchedEffect(outboundTargetKey) {
val cached = OutboundProcessCache.get(outboundTargetKey)
outboundSnapshot = cached?.snapshot
outboundLastCheckAttemptAt = cached?.lastCheckAttemptAt ?: 0L
outboundLastCheckError = cached?.lastCheckError.orEmpty()
outboundAutoCheckedTargetKey = if (cached?.attempted == true) outboundTargetKey else ""
outboundStatus = ""
outboundStatusOwner = null
} }
LaunchedEffect( LaunchedEffect(
localProxyPortInput, localProxyPortInput,
@@ -741,7 +792,7 @@ fun DeployTab(
scope.launch { scope.launch {
try { try {
writeServerBackupToUri(context, uri, backup) writeServerBackupToUri(context, uri, backup)
migrationStatus = "Экспорт готов: паролей ${backup.passwordCount}, устройств ${backup.deviceCount}${if (backup.hasWgKeys) ", WG-ключи включены" else ""}" migrationStatus = "${if (backup.hasWgKeys) "Полный" else "Частичный"} экспорт готов: паролей ${backup.passwordCount}, устройств ${backup.deviceCount}."
} catch (e: Exception) { } catch (e: Exception) {
migrationStatus = "Ошибка экспорта: ${friendlyDeployError(e, "экспорт")}" migrationStatus = "Ошибка экспорта: ${friendlyDeployError(e, "экспорт")}"
DeployManager.writeError("Server export error: ${e.message}") DeployManager.writeError("Server export error: ${e.message}")
@@ -761,7 +812,7 @@ fun DeployTab(
val backup = loadServerBackupFromUri(context, uri) val backup = loadServerBackupFromUri(context, uri)
selectedImportBackup = backup selectedImportBackup = backup
selectedImportModeName = ServerImportMode.Replace.name selectedImportModeName = ServerImportMode.Replace.name
migrationStatus = "Импорт выбран: паролей ${backup.passwordCount}, устройств ${backup.deviceCount}${if (backup.hasWgKeys) ", полный перенос" else ", без WG-ключей"}" migrationStatus = "Выбран ${if (backup.hasWgKeys) "полный" else "частичный"} бэкап: паролей ${backup.passwordCount}, устройств ${backup.deviceCount}."
} catch (e: Exception) { } catch (e: Exception) {
selectedImportBackup = null selectedImportBackup = null
migrationStatus = "Ошибка файла импорта: ${friendlyDeployError(e, "файл импорта")}" migrationStatus = "Ошибка файла импорта: ${friendlyDeployError(e, "файл импорта")}"
@@ -826,8 +877,9 @@ fun DeployTab(
requestSshPort: Int, requestSshPort: Int,
requestMainPassword: String, requestMainPassword: String,
profile: ServerAdminProfileInfo profile: ServerAdminProfileInfo
): Result<Unit> = runCatching { ): Result<Boolean> = runCatching {
ServerAdminClient.updateAdminProfile( if (!hasMeaningfulAdminProfileFields(profile)) return@runCatching false
ServerAdminClient.updateAdminProfileFromTunnel(
ServerAdminTarget( ServerAdminTarget(
host = requestHost, host = requestHost,
user = requestUser.ifBlank { "root" }, user = requestUser.ifBlank { "root" },
@@ -837,7 +889,8 @@ fun DeployTab(
), ),
profile profile
) )
}.map { } true
}
suspend fun applyExistingConnection( suspend fun applyExistingConnection(
connection: ExistingServerConnection, connection: ExistingServerConnection,
@@ -912,7 +965,14 @@ fun DeployTab(
) )
if (success) { if (success) {
val ownerProfile = currentOwnerProfile() val ownerProfile = currentOwnerProfile()
DeployManager.updateProgress(0.97f, "Сохраняю профиль владельца на сервере...") DeployManager.updateProgress(
0.97f,
if (hasMeaningfulAdminProfileFields(ownerProfile)) {
"Сохраняю заданные поля профиля владельца на сервере..."
} else {
"Поля «Туннеля» стандартные — профиль владельца на сервере не изменяю..."
}
)
val ownerProfileSaved = syncOwnerProfileToServer( val ownerProfileSaved = syncOwnerProfileToServer(
requestHost = request.host, requestHost = request.host,
requestUser = request.user, requestUser = request.user,
@@ -943,8 +1003,10 @@ fun DeployTab(
DeployManager.updateProgress( DeployManager.updateProgress(
1f, 1f,
when { when {
ownerProfileSaved.isSuccess && outboundProfileSaved.isSuccess -> "Сервер обновлён, профили сохранены." ownerProfileSaved.getOrNull() == true && outboundProfileSaved.isSuccess -> "Сервер обновлён, заданные поля профиля владельца и профиль выходного IP сохранены."
ownerProfileSaved.isSuccess -> "Сервер обновлён, профиль владельца сохранён." ownerProfileSaved.getOrNull() == true -> "Сервер обновлён, заданные поля профиля владельца сохранены."
ownerProfileSaved.isSuccess && outboundProfileSaved.isSuccess -> "Сервер обновлён. Стандартные поля «Туннеля» не меняли профиль владельца на сервере."
ownerProfileSaved.isSuccess -> "Сервер обновлён. Профиль владельца на сервере не изменён."
outboundProfileSaved.isSuccess -> "Сервер обновлён, профиль выходного IP сохранён." outboundProfileSaved.isSuccess -> "Сервер обновлён, профиль выходного IP сохранён."
else -> "Сервер обновлён. Дополнительные профили не сохранились автоматически." else -> "Сервер обновлён. Дополнительные профили не сохранились автоматически."
} }
@@ -1026,9 +1088,57 @@ fun DeployTab(
) )
} }
fun acceptOutboundSnapshot(requestTargetKey: String, snapshot: OutboundServerSnapshot): Boolean {
if (currentOutboundTargetKey != requestTargetKey) return false
outboundSnapshot = snapshot
outboundLastCheckAttemptAt = snapshot.checkedAtMillis
outboundLastCheckError = ""
outboundAutoCheckedTargetKey = requestTargetKey
OutboundProcessCache.put(
requestTargetKey,
OutboundProcessSnapshot(
snapshot = snapshot,
lastCheckAttemptAt = snapshot.checkedAtMillis,
lastCheckError = "",
attempted = true
)
)
return true
}
fun recordOutboundCheckFailure(requestTargetKey: String, error: Throwable) {
if (currentOutboundTargetKey != requestTargetKey) return
outboundSnapshot = null
outboundLastCheckAttemptAt = System.currentTimeMillis()
outboundLastCheckError = friendlyDeployError(error, "выходной IP")
outboundAutoCheckedTargetKey = requestTargetKey
OutboundProcessCache.put(
requestTargetKey,
OutboundProcessSnapshot(
snapshot = null,
lastCheckAttemptAt = outboundLastCheckAttemptAt,
lastCheckError = outboundLastCheckError,
attempted = true
)
)
}
fun refreshOutboundSnapshot(showStatus: Boolean = true) { fun refreshOutboundSnapshot(showStatus: Boolean = true) {
if (outboundBusy || outboundSnapshotBusy) return
val target = currentOutboundTarget() ?: return val target = currentOutboundTarget() ?: return
val requestTargetKey = outboundTargetKey
outboundAutoCheckedTargetKey = requestTargetKey
OutboundProcessCache.put(
requestTargetKey,
OutboundProcessSnapshot(
snapshot = outboundSnapshot,
lastCheckAttemptAt = outboundLastCheckAttemptAt,
lastCheckError = "",
attempted = true
)
)
outboundSnapshotBusy = true outboundSnapshotBusy = true
outboundLastCheckError = ""
if (showStatus) { if (showStatus) {
outboundStatus = "Проверяю, какой выходной IP/прокси сейчас активен на сервере..." outboundStatus = "Проверяю, какой выходной IP/прокси сейчас активен на сервере..."
outboundStatusOwner = null outboundStatusOwner = null
@@ -1036,13 +1146,14 @@ fun DeployTab(
scope.launch { scope.launch {
try { try {
val snapshot = readOutboundServerSnapshot(context, target) val snapshot = readOutboundServerSnapshot(context, target)
outboundSnapshot = snapshot val accepted = acceptOutboundSnapshot(requestTargetKey, snapshot)
if (showStatus) { if (showStatus && accepted) {
outboundStatus = outboundServerStateSummary(snapshot) outboundStatus = outboundServerStateSummary(snapshot)
outboundStatusOwner = null outboundStatusOwner = null
} }
} catch (e: Exception) { } catch (e: Exception) {
if (showStatus) { recordOutboundCheckFailure(requestTargetKey, e)
if (showStatus && currentOutboundTargetKey == requestTargetKey) {
outboundStatus = "Не удалось прочитать состояние выходного IP: ${friendlyDeployError(e, "выходной IP")}" outboundStatus = "Не удалось прочитать состояние выходного IP: ${friendlyDeployError(e, "выходной IP")}"
outboundStatusOwner = null outboundStatusOwner = null
} }
@@ -1061,6 +1172,7 @@ fun DeployTab(
) { ) {
val owner = outboundDialog?.name val owner = outboundDialog?.name
val target = currentOutboundTarget() ?: return val target = currentOutboundTarget() ?: return
val requestTargetKey = outboundTargetKey
outboundBusy = true outboundBusy = true
outboundSnapshotBusy = true outboundSnapshotBusy = true
outboundProgressActive = true outboundProgressActive = true
@@ -1073,7 +1185,7 @@ fun DeployTab(
if (preflightRouteMode != null) { if (preflightRouteMode != null) {
DeployManager.updateProgress(0.04f, "Проверяю текущий выход перед переключением...") DeployManager.updateProgress(0.04f, "Проверяю текущий выход перед переключением...")
val before = readOutboundServerSnapshot(context, target) val before = readOutboundServerSnapshot(context, target)
outboundSnapshot = before if (!acceptOutboundSnapshot(requestTargetKey, before)) return@launch
before.routeConflictMessage?.let { conflict -> before.routeConflictMessage?.let { conflict ->
outboundStatus = "Установка остановлена. $conflict" outboundStatus = "Установка остановлена. $conflict"
outboundStatusOwner = owner outboundStatusOwner = owner
@@ -1085,7 +1197,9 @@ fun DeployTab(
val afterSnapshot = runCatching { val afterSnapshot = runCatching {
readOutboundServerSnapshot(context, target) readOutboundServerSnapshot(context, target)
}.onSuccess { }.onSuccess {
outboundSnapshot = it acceptOutboundSnapshot(requestTargetKey, it)
}.onFailure {
recordOutboundCheckFailure(requestTargetKey, it)
}.getOrNull() }.getOrNull()
val afterWarning = afterSnapshot?.routeConflictMessage val afterWarning = afterSnapshot?.routeConflictMessage
?: afterSnapshot?.outboundModeMismatchWarning() ?: afterSnapshot?.outboundModeMismatchWarning()
@@ -1141,6 +1255,7 @@ fun DeployTab(
fun restoreOutboundFromServer() { fun restoreOutboundFromServer() {
val target = currentOutboundTarget() ?: return val target = currentOutboundTarget() ?: return
val requestTargetKey = outboundTargetKey
outboundBusy = true outboundBusy = true
outboundSnapshotBusy = true outboundSnapshotBusy = true
outboundProgressActive = true outboundProgressActive = true
@@ -1151,10 +1266,11 @@ fun DeployTab(
scope.launch { scope.launch {
try { try {
val snapshot = readOutboundServerSnapshot(context, target) val snapshot = readOutboundServerSnapshot(context, target)
outboundSnapshot = snapshot if (!acceptOutboundSnapshot(requestTargetKey, snapshot)) return@launch
applyOutboundSnapshot(snapshot) applyOutboundSnapshot(snapshot)
outboundStatus = outboundRestoreSummary(snapshot) outboundStatus = outboundRestoreSummary(snapshot)
} catch (e: Exception) { } catch (e: Exception) {
recordOutboundCheckFailure(requestTargetKey, e)
outboundStatus = "Не удалось прочитать настройки выходного IP с сервера: ${friendlyDeployError(e, "выходной IP")}" outboundStatus = "Не удалось прочитать настройки выходного IP с сервера: ${friendlyDeployError(e, "выходной IP")}"
outboundStatusOwner = null outboundStatusOwner = null
DeployManager.writeError("Outbound profile restore failed: ${e.message}") DeployManager.writeError("Outbound profile restore failed: ${e.message}")
@@ -1177,36 +1293,26 @@ fun DeployTab(
fun dialogStatus(dialog: OutboundDialog): String = fun dialogStatus(dialog: OutboundDialog): String =
if (outboundStatusOwner == dialog.name) outboundStatus else "" if (outboundStatusOwner == dialog.name) outboundStatus else ""
LaunchedEffect(outboundSectionExpanded) { LaunchedEffect(
if ( outboundSectionExpanded,
outboundSectionExpanded == true && outboundTargetKey,
outboundSnapshot == null && outboundBusy,
!outboundBusy && outboundSnapshotBusy,
!outboundSnapshotBusy && isServerAddressValid,
isServerAddressValid && password,
password.isNotBlank() outboundAutoCheckedTargetKey
) { ) {
val target = OutboundSshTarget( if (shouldAutoRefreshOutboundState(
host = ip.trim(), expanded = outboundSectionExpanded == true,
user = login.ifBlank { "root" }, outboundBusy = outboundBusy,
pass = password, snapshotBusy = outboundSnapshotBusy,
port = savedSshPort.toIntOrNull() ?: 22 hostValid = isServerAddressValid,
hasSshPassword = password.isNotBlank(),
targetKey = outboundTargetKey,
checkedTargetKey = outboundAutoCheckedTargetKey
) )
outboundSnapshotBusy = true ) {
try { refreshOutboundSnapshot(showStatus = false)
runCatching {
readOutboundServerSnapshot(context, target)
}.onSuccess {
outboundSnapshot = it
}.onFailure {
outboundStatus = "Не удалось автоматически проверить выходной IP: ${friendlyDeployError(it, "выходной IP")}"
outboundStatusOwner = null
DeployManager.writeError("Outbound auto refresh failed: ${it.message}")
}
} finally {
outboundSnapshotBusy = false
DeployManager.updateProgress(0f, "")
}
} }
} }
@@ -1609,6 +1715,7 @@ fun DeployTab(
adminProfile = currentOwnerProfile(), adminProfile = currentOwnerProfile(),
sourceProfileName = vpnProfileTransferName(activeProfile, profileNames), sourceProfileName = vpnProfileTransferName(activeProfile, profileNames),
enabled = !isDeploying && !isCheckingExistingInstall && !migrationBusy && !outboundBusy && isServerAddressValid, enabled = !isDeploying && !isCheckingExistingInstall && !migrationBusy && !outboundBusy && isServerAddressValid,
hostValid = isServerAddressValid,
expanded = clientsExpanded, expanded = clientsExpanded,
modifier = Modifier.onGloballyPositioned { clientsSectionY = it.positionInParent().y }, modifier = Modifier.onGloballyPositioned { clientsSectionY = it.positionInParent().y },
onExpandedChange = { expanded -> onExpandedChange = { expanded ->
@@ -1628,6 +1735,8 @@ fun DeployTab(
busy = outboundBusy, busy = outboundBusy,
snapshot = outboundSnapshot, snapshot = outboundSnapshot,
snapshotBusy = outboundSnapshotBusy, snapshotBusy = outboundSnapshotBusy,
lastCheckAttemptAt = outboundLastCheckAttemptAt,
lastCheckError = outboundLastCheckError,
status = if (outboundDialog == null && outboundStatusOwner == null) outboundStatus else "", status = if (outboundDialog == null && outboundStatusOwner == null) outboundStatus else "",
actionTitle = outboundActionTitle, actionTitle = outboundActionTitle,
enabled = !isDeploying && !migrationBusy && !outboundBusy && !outboundSnapshotBusy, enabled = !isDeploying && !migrationBusy && !outboundBusy && !outboundSnapshotBusy,
@@ -2004,12 +2113,12 @@ fun DeployTab(
) { ) {
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f)) HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f))
Text( Text(
"Экспорт сохраняет пароли, Telegram-бота, привязки устройств и историю. Полный экспорт дополнительно сохраняет WireGuard-ключи сервера и клиентов.", "Экспорт сохраняет базу WDTT Plus: профиль владельца, Telegram-бота, клиентов, привязки устройств, статистику и историю. Полный экспорт дополнительно сохраняет WireGuard-ключи сервера.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
Text( Text(
"Старые ссылки пользователей останутся рабочими только если в них был домен и после переноса DNS этого домена указывает на новый сервер. Если ссылки выдавались с IP, после переноса сгенерируйте и отправьте пользователям новые ссылки; пароли и привязки при полном переносе сохранятся.", "Старые ссылки останутся рабочими, если в них был домен, DNS указывает на новый сервер и при импорте сохранены прежние порты. Для ссылок с IP или при смене портов создайте и отправьте новые. Пароли, привязки и история входят в оба вида экспорта; серверные WireGuard-ключи — только в полный.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
@@ -2026,30 +2135,32 @@ fun DeployTab(
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically verticalAlignment = Alignment.CenterVertically
) { ) {
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text( Text(
"Полный экспорт: сохранить WireGuard-ключи", if (exportIncludeWgKeys) "Полный экспорт" else "Частичный экспорт",
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurface, fontWeight = FontWeight.SemiBold,
modifier = Modifier.weight(1f) color = MaterialTheme.colorScheme.onSurface
) )
Text(
if (exportIncludeWgKeys) {
"База WDTT Plus и WireGuard-ключи сервера. Для полного переезда с сохранением серверной WG-идентичности."
} else {
"Только база WDTT Plus без серверных WG-ключей. На целевом сервере сохранятся его ключи, а при их отсутствии создадутся новые."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
Switch( Switch(
checked = exportIncludeWgKeys, checked = exportIncludeWgKeys,
enabled = !migrationBusy && !isDeploying, enabled = !migrationBusy && !isDeploying,
onCheckedChange = { exportIncludeWgKeys = it } onCheckedChange = { exportIncludeWgKeys = it }
) )
} }
Text(
if (exportIncludeWgKeys) {
"Полный перенос нужен для переезда своего сервера: сохраняет WireGuard-идентичность и снижает риск перепривязки устройств."
} else {
"Без WireGuard-ключей переносится только база доступа. Новый сервер создаст новые ключи, часть клиентов может потребовать повторное подключение."
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
@@ -2115,7 +2226,7 @@ fun DeployTab(
verticalArrangement = Arrangement.spacedBy(8.dp) verticalArrangement = Arrangement.spacedBy(8.dp)
) { ) {
Text( Text(
"Выбран импорт: ${backup.passwordCount} паролей, ${backup.deviceCount} устройств${if (backup.hasWgKeys) ", WG-ключи есть" else ", WG-ключей нет"}", "Выбран ${if (backup.hasWgKeys) "полный" else "частичный"} бэкап: ${backup.passwordCount} паролей, ${backup.deviceCount} устройств${if (backup.hasWgKeys) ", WG-ключи сервера включены" else ", без WG-ключей сервера"}.",
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface color = MaterialTheme.colorScheme.onSurface
) )
@@ -2452,6 +2563,8 @@ private fun OutboundRoutingSection(
busy: Boolean, busy: Boolean,
snapshot: OutboundServerSnapshot?, snapshot: OutboundServerSnapshot?,
snapshotBusy: Boolean, snapshotBusy: Boolean,
lastCheckAttemptAt: Long,
lastCheckError: String,
status: String, status: String,
actionTitle: String, actionTitle: String,
enabled: Boolean, enabled: Boolean,
@@ -2539,6 +2652,8 @@ private fun OutboundRoutingSection(
OutboundServerStateCard( OutboundServerStateCard(
snapshot = snapshot, snapshot = snapshot,
snapshotBusy = snapshotBusy, snapshotBusy = snapshotBusy,
lastCheckAttemptAt = lastCheckAttemptAt,
lastCheckError = lastCheckError,
enabled = enabled, enabled = enabled,
onRefreshState = onRefreshState onRefreshState = onRefreshState
) )
@@ -2678,10 +2793,13 @@ private fun BetaBadge() {
private fun OutboundServerStateCard( private fun OutboundServerStateCard(
snapshot: OutboundServerSnapshot?, snapshot: OutboundServerSnapshot?,
snapshotBusy: Boolean, snapshotBusy: Boolean,
lastCheckAttemptAt: Long,
lastCheckError: String,
enabled: Boolean, enabled: Boolean,
onRefreshState: () -> Unit onRefreshState: () -> Unit
) { ) {
val state = when { val state = when {
lastCheckError.isNotBlank() -> OutboundModeVisualState.Error
snapshot == null -> OutboundModeVisualState.Unknown snapshot == null -> OutboundModeVisualState.Unknown
snapshot.hasRouteConflict -> OutboundModeVisualState.Error snapshot.hasRouteConflict -> OutboundModeVisualState.Error
snapshot.outboundModeMismatchWarning() != null -> OutboundModeVisualState.Warning snapshot.outboundModeMismatchWarning() != null -> OutboundModeVisualState.Warning
@@ -2707,17 +2825,30 @@ private fun OutboundServerStateCard(
OutboundStateDot(state) OutboundStateDot(state)
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text( Text(
text = snapshot?.let { "На сервере: ${outboundServerShortState(it)}" } text = when {
?: "На сервере: состояние ещё не проверено", snapshotBusy -> "Проверяю состояние на сервере..."
lastCheckError.isNotBlank() -> "Не удалось проверить выходной IP"
snapshot != null -> "На сервере: ${outboundServerShortState(snapshot)}"
else -> "На сервере: состояние ещё не проверено"
},
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold, fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface color = MaterialTheme.colorScheme.onSurface
) )
Text( Text(
text = snapshot?.let { outboundServerStateHint(it) } text = when {
?: "Откройте блок или нажмите «Обновить состояние», чтобы увидеть, что реально запущено на сервере.", snapshotBusy -> "Читаю активный режим и проверяю конфликтующие маршруты."
lastCheckError.isNotBlank() -> buildString {
if (lastCheckAttemptAt > 0L) {
append("Последняя попытка: ${formatOutboundCheckTime(lastCheckAttemptAt)}. ")
}
append(lastCheckError)
}
snapshot != null -> outboundServerStateHint(snapshot)
else -> "Откройте блок или нажмите «Обновить состояние», чтобы увидеть, что реально запущено на сервере."
},
style = MaterialTheme.typography.bodySmall, style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant color = if (lastCheckError.isNotBlank()) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant
) )
} }
} }
@@ -5976,6 +6107,7 @@ private fun validateTrafficBucket(owner: String, index: Int, bucket: JSONObject)
private fun validatePasswordEntry(pass: String, entry: JSONObject) { private fun validatePasswordEntry(pass: String, entry: JSONObject) {
require(pass.isNotBlank()) { "пустой пароль в passwords" } require(pass.isNotBlank()) { "пустой пароль в passwords" }
require(pass.length <= 256) { "пароль в passwords слишком длинный" }
entry.optStringLength("device_id", 256, "пароля $pass") entry.optStringLength("device_id", 256, "пароля $pass")
entry.optStringLength("label", 120, "пароля $pass") entry.optStringLength("label", 120, "пароля $pass")
entry.optStringLength("vk_hash", 512, "пароля $pass") entry.optStringLength("vk_hash", 512, "пароля $pass")
@@ -6006,6 +6138,7 @@ private fun validatePasswordEntry(pass: String, entry: JSONObject) {
private fun validateDeviceEntry(deviceId: String, device: JSONObject) { private fun validateDeviceEntry(deviceId: String, device: JSONObject) {
require(deviceId.isNotBlank()) { "пустой ключ устройства в devices" } require(deviceId.isNotBlank()) { "пустой ключ устройства в devices" }
require(deviceId.length <= 256) { "ключ устройства слишком длинный" }
val storedId = device.optString("device_id", deviceId) val storedId = device.optString("device_id", deviceId)
require(storedId.isNotBlank()) { "device_id устройства $deviceId пустой" } require(storedId.isNotBlank()) { "device_id устройства $deviceId пустой" }
val ip = device.optString("ip") val ip = device.optString("ip")
@@ -6026,11 +6159,42 @@ private fun validateDeviceEntry(deviceId: String, device: JSONObject) {
require(device.optLong("last_seen_at", 0) >= 0) { "last_seen_at устройства $deviceId должен быть >= 0" } require(device.optLong("last_seen_at", 0) >= 0) { "last_seen_at устройства $deviceId должен быть >= 0" }
} }
private fun validatePasswordsDbStructure(db: JSONObject) { private fun validateAdminProfile(profile: JSONObject?) {
if (profile == null) return
profile.optStringLength("vk_hashes", 2048, "admin_profile")
profile.optStringLength("secondary_vk_hash", 512, "admin_profile")
profile.optStringLength("profile_name", 48, "admin_profile")
profile.optStringLength("sni", 253, "admin_profile")
if (profile.has("workers_per_hash")) {
require(profile.optInt("workers_per_hash", 0) in 1..128) { "workers_per_hash в admin_profile должен быть 1..128" }
}
if (profile.has("protocol")) {
require(profile.optString("protocol").lowercase() in setOf("udp", "tcp")) { "protocol в admin_profile должен быть udp или tcp" }
}
if (profile.has("listen_port")) {
require(profile.optInt("listen_port", 0) in 1..65535) { "listen_port в admin_profile некорректен" }
}
val ports = profile.optString("ports", "")
require(ports.isBlank() || ports.isValidPortsSpec()) { "ports в admin_profile некорректны" }
require(profile.optLong("updated_at", 0L) >= 0L) { "updated_at в admin_profile должен быть >= 0" }
profile.optJSONArray("device_ids")?.let { ids ->
require(ids.length() <= 500) { "слишком много device_ids в admin_profile" }
for (index in 0 until ids.length()) {
require(ids.optString(index).length <= 256) { "device_id в admin_profile слишком длинный" }
}
}
}
internal fun validatePasswordsDbStructure(db: JSONObject) {
require(db.has("main_password")) { "в базе нет main_password" } require(db.has("main_password")) { "в базе нет main_password" }
require(db.optString("main_password").isNotBlank()) { "main_password пустой" } require(db.optString("main_password").isNotBlank()) { "main_password пустой" }
require(db.optString("main_password").length <= 256) { "main_password слишком длинный" }
require(db.optString("admin_id", "").length <= 64) { "admin_id слишком длинный" }
require(db.optString("bot_token", "").length <= 256) { "bot_token слишком длинный" }
val passwords = db.optJSONObject("passwords") ?: throw IllegalArgumentException("passwords должен быть объектом") val passwords = db.optJSONObject("passwords") ?: throw IllegalArgumentException("passwords должен быть объектом")
val devices = db.optJSONObject("devices") ?: throw IllegalArgumentException("devices должен быть объектом") val devices = db.optJSONObject("devices") ?: throw IllegalArgumentException("devices должен быть объектом")
require(passwords.length() <= 500) { "в бэкапе больше 500 паролей" }
require(devices.length() <= 500) { "в бэкапе больше 500 устройств" }
val dns = db.optString("dns", "") val dns = db.optString("dns", "")
require(dns.isBlank() || dns.length <= 256) { "dns слишком длинный" } require(dns.isBlank() || dns.length <= 256) { "dns слишком длинный" }
val publicHost = db.optString("public_ip", "") val publicHost = db.optString("public_ip", "")
@@ -6052,9 +6216,13 @@ private fun validatePasswordsDbStructure(db: JSONObject) {
validateTrafficBucket("admin_traffic", i, bucket) validateTrafficBucket("admin_traffic", i, bucket)
} }
} }
validateAdminProfile(db.optJSONObject("admin_profile"))
passwords.keys().forEach { pass -> passwords.keys().forEach { pass ->
val entry = passwords.optJSONObject(pass) ?: throw IllegalArgumentException("passwords.$pass должен быть объектом") val entry = passwords.optJSONObject(pass) ?: throw IllegalArgumentException("passwords.$pass должен быть объектом")
validatePasswordEntry(pass, entry) validatePasswordEntry(pass, entry)
entry.optString("device_id", "").takeIf { it.isNotBlank() }?.let { deviceId ->
require(devices.has(deviceId)) { "у пароля $pass указано отсутствующее устройство $deviceId" }
}
} }
devices.keys().forEach { deviceId -> devices.keys().forEach { deviceId ->
val device = devices.optJSONObject(deviceId) ?: throw IllegalArgumentException("devices.$deviceId должен быть объектом") val device = devices.optJSONObject(deviceId) ?: throw IllegalArgumentException("devices.$deviceId должен быть объектом")
@@ -6160,6 +6328,9 @@ private suspend fun readServerBackup(
val dbB64 = markerValue(output, "WDTT_DB_B64") ?: throw IllegalStateException("сервер не отдал passwords.json") val dbB64 = markerValue(output, "WDTT_DB_B64") ?: throw IllegalStateException("сервер не отдал passwords.json")
val passwordsJson = decodeBase64Text(dbB64) val passwordsJson = decodeBase64Text(dbB64)
val wgKeys = markerValue(output, "WDTT_WG_KEYS_B64")?.takeIf { it.isNotBlank() }?.let { decodeBase64Text(it) } val wgKeys = markerValue(output, "WDTT_WG_KEYS_B64")?.takeIf { it.isNotBlank() }?.let { decodeBase64Text(it) }
if (includeWgKeys && wgKeys.isNullOrBlank()) {
throw IllegalStateException("полный экспорт невозможен: на сервере не найден корректный /etc/wdtt/wg-keys.dat. Выполните установку сервера или выберите частичный экспорт")
}
parseBackup( parseBackup(
passwordsJson = passwordsJson, passwordsJson = passwordsJson,
wgKeysDat = wgKeys, wgKeysDat = wgKeys,
@@ -6328,6 +6499,43 @@ private fun ownerProfileDiffLines(server: ServerAdminProfileInfo, local: ServerA
return lines.ifEmpty { listOf("Отличия есть только в служебных данных профиля.") } return lines.ifEmpty { listOf("Отличия есть только в служебных данных профиля.") }
} }
private fun ownerProfileInstallDiffLines(
server: ServerAdminProfileInfo,
local: ServerAdminProfileInfo
): List<String> {
val serverComparable = server.comparableOwnerProfile()
val localComparable = local.comparableOwnerProfile()
return buildList {
if (localComparable.vkHashes.isNotBlank() && serverComparable.vkHashes != localComparable.vkHashes) {
add("VK-хеши: сервер — ${secretPresenceLabel(serverComparable.vkHashes)}, приложение — ${secretPresenceLabel(localComparable.vkHashes)}")
}
if (localComparable.secondaryVkHash.isNotBlank() && serverComparable.secondaryVkHash != localComparable.secondaryVkHash) {
add("Резервный VK-хеш: сервер — ${secretPresenceLabel(serverComparable.secondaryVkHash)}, приложение — ${secretPresenceLabel(localComparable.secondaryVkHash)}")
}
if (localComparable.profileName.isNotBlank() && serverComparable.profileName != localComparable.profileName) {
add("Название профиля: сервер — ${serverComparable.profileName.ifBlank { "стандартное" }}, приложение — ${localComparable.profileName}")
}
if (localComparable.workersPerHash != 16 && serverComparable.workersPerHash != localComparable.workersPerHash) {
add("Потоки на хеш: сервер — ${serverComparable.workersPerHash}, приложение — ${localComparable.workersPerHash}")
}
if (localComparable.protocol != "udp" && serverComparable.protocol != localComparable.protocol) {
add("Протокол: сервер — ${serverComparable.protocol}, приложение — ${localComparable.protocol}")
}
if (localComparable.listenPort != 9000 && serverComparable.listenPort != localComparable.listenPort) {
add("Локальный порт: сервер — ${serverComparable.listenPort}, приложение — ${localComparable.listenPort}")
}
if (localComparable.ports != "56000,56001,9000" && serverComparable.ports != localComparable.ports) {
add("Порты ссылки: сервер — ${serverComparable.ports}, приложение — ${localComparable.ports}")
}
if (localComparable.sni.isNotBlank() && serverComparable.sni != localComparable.sni) {
add("SNI: сервер — ${serverComparable.sni.ifBlank { "не задан" }}, приложение — ${localComparable.sni}")
}
if (localComparable.noDns && !serverComparable.noDns) {
add("No DNS: сервер — выключено, приложение — включено")
}
}
}
private fun existingConnectionDiffLines( private fun existingConnectionDiffLines(
connection: ExistingServerConnection, connection: ExistingServerConnection,
localPeer: String, localPeer: String,
@@ -6447,11 +6655,14 @@ private suspend fun compareDeployWithServer(
val defaultPorts = db.optString("default_ports").ifBlank { "56000,56001,9000" } val defaultPorts = db.optString("default_ports").ifBlank { "56000,56001,9000" }
val serverProfile = parseOwnerProfileFromDb(db.optJSONObject("admin_profile"), defaultPorts) val serverProfile = parseOwnerProfileFromDb(db.optJSONObject("admin_profile"), defaultPorts)
if (serverProfile.hasSavedFields && ownerProfilesDiffer(serverProfile, localOwnerProfile)) { val ownerInstallDiff = ownerProfileInstallDiffLines(serverProfile, localOwnerProfile)
if (serverProfile.hasSavedFields && ownerInstallDiff.isNotEmpty()) {
overwriteLines += "Профиль владельца («Туннель» и порты)" overwriteLines += "Профиль владельца («Туннель» и порты)"
overwriteLines += ownerProfileDiffLines(serverProfile, localOwnerProfile).map { " $it" } overwriteLines += ownerInstallDiff.map { " $it" }
} else if (!serverProfile.hasSavedFields) { } else if (!serverProfile.hasSavedFields && hasMeaningfulAdminProfileFields(localOwnerProfile)) {
notes += "На сервере ещё нет профиля владельца; установка создаст его из текущих полей приложения." notes += "На сервере ещё нет профиля владельца; установка сохранит только заданные нестандартные поля «Туннеля»."
} else if (serverProfile.hasSavedFields && !hasMeaningfulAdminProfileFields(localOwnerProfile)) {
notes += "Поля «Туннеля» в приложении пустые или стандартные — сохранённый профиль владельца на сервере не изменится."
} }
} finally { } finally {
try { session?.disconnect() } catch (_: Exception) {} try { session?.disconnect() } catch (_: Exception) {}
@@ -6550,6 +6761,55 @@ private suspend fun readExistingServerConnection(
} }
} }
internal fun mergeServerDatabaseEntries(
source: JSONObject,
target: JSONObject,
portsSpec: String
) {
require(portsSpec.isValidPortsSpec()) { "некорректные порты целевого сервера" }
val sourcePasswords = source.optJSONObject("passwords") ?: JSONObject()
val sourceDevices = source.optJSONObject("devices") ?: JSONObject()
val targetPasswords = target.childObject("passwords")
val targetDevices = target.childObject("devices")
val devicesToImport = linkedSetOf<String>()
val usedDeviceIps = targetDevices.keys()
.asSequence()
.mapNotNull { targetDevices.optJSONObject(it)?.optString("ip")?.takeIf(String::isNotBlank) }
.toMutableSet()
sourcePasswords.keys().forEach { password ->
if (targetPasswords.has(password)) return@forEach
val entry = JSONObject(sourcePasswords.getJSONObject(password).toString())
entry.put("ports", portsSpec)
entry.optString("device_id", "").takeIf { it.isNotBlank() }?.let { deviceId ->
val sourceDevice = sourceDevices.optJSONObject(deviceId)
?: throw IllegalArgumentException("в бэкапе нет устройства $deviceId, привязанного к клиенту ${password.take(4)}…")
targetDevices.optJSONObject(deviceId)?.let { targetDevice ->
val sameKeys = sourceDevice.optString("priv_key") == targetDevice.optString("priv_key") &&
sourceDevice.optString("pub_key") == targetDevice.optString("pub_key")
require(sameKeys) {
"на целевом сервере уже есть другое устройство с ID $deviceId. Отвяжите конфликтующее устройство или используйте импорт с заменой"
}
} ?: devicesToImport.add(deviceId)
}
targetPasswords.put(password, entry)
}
devicesToImport.forEach { deviceId ->
val importedDevice = JSONObject(sourceDevices.getJSONObject(deviceId).toString())
val sourceIp = importedDevice.optString("ip")
val targetIp = sourceIp.takeIf { it.isNotBlank() && it !in usedDeviceIps }
?: (2..250)
.asSequence()
.map { "10.66.66.$it" }
.firstOrNull { it !in usedDeviceIps }
?: throw IllegalStateException("на целевом сервере нет свободных внутренних IP для импортируемых устройств")
importedDevice.put("ip", targetIp)
usedDeviceIps += targetIp
targetDevices.put(deviceId, importedDevice)
}
}
private fun normalizeDbForTarget( private fun normalizeDbForTarget(
backup: ServerBackup, backup: ServerBackup,
currentDbJson: String?, currentDbJson: String?,
@@ -6566,22 +6826,7 @@ private fun normalizeDbForTarget(
} }
if (mode == ServerImportMode.Merge) { if (mode == ServerImportMode.Merge) {
val sourcePasswords = source.optJSONObject("passwords") ?: JSONObject() mergeServerDatabaseEntries(source, target, portsSpec)
val targetPasswords = target.childObject("passwords")
sourcePasswords.keys().forEach { key ->
if (!targetPasswords.has(key)) {
val entry = JSONObject(sourcePasswords.getJSONObject(key).toString())
entry.put("ports", portsSpec)
targetPasswords.put(key, entry)
}
}
val sourceDevices = source.optJSONObject("devices") ?: JSONObject()
val targetDevices = target.childObject("devices")
sourceDevices.keys().forEach { key ->
if (!targetDevices.has(key)) {
targetDevices.put(key, JSONObject(sourceDevices.getJSONObject(key).toString()))
}
}
if (!target.has("main_password") || target.optString("main_password").isBlank()) { if (!target.has("main_password") || target.optString("main_password").isBlank()) {
target.put("main_password", backup.mainPassword) target.put("main_password", backup.mainPassword)
} }
@@ -6662,18 +6907,43 @@ private suspend fun performServerImportNow(
onProgress: (Float, String) -> Unit onProgress: (Float, String) -> Unit
): Boolean = withContext(Dispatchers.IO) { ): Boolean = withContext(Dispatchers.IO) {
var session: Session? = null var session: Session? = null
var sshClient: SSHClient? = null
var rollbackPrepared = false
try { try {
onProgress(0.05f, "Подключение...") onProgress(0.05f, "Подключение...")
session = createSSHSession(request.host, request.user, request.pass, request.sshPort) session = createSSHSession(request.host, request.user, request.pass, request.sshPort)
DeployManager.activeSession = session DeployManager.activeSession = session
val ssh = SSHClient(session, request.pass) val ssh = SSHClient(session, request.pass)
onProgress(0.30f, "Подготовка импорта...") sshClient = ssh
onProgress(0.15f, "Проверяю текущую базу и создаю страховочную копию...")
val beforeJson = readRemotePasswordsJson(ssh)?.also {
validatePasswordsDbStructure(JSONObject(it))
}
prepareServerUpdateRollback(ssh)
rollbackPrepared = true
onProgress(0.35f, "Подготовка импорта...")
applyServerImport(context, ssh, request, backup, mode, restartService = true) applyServerImport(context, ssh, request, backup, mode, restartService = true)
onProgress(0.85f, "Проверяю импортированные данные и службу...")
val afterJson = readRemotePasswordsJson(ssh)
?: throw IllegalStateException("после импорта не найдена база passwords.json")
validateImportedServerState(
sourceJson = backup.passwordsJson,
beforeJson = beforeJson,
afterJson = afterJson,
replace = mode == ServerImportMode.Replace
)
cleanupServerUpdateRollback(ssh)
rollbackPrepared = false
onProgress(1.0f, "Импорт завершён") onProgress(1.0f, "Импорт завершён")
DeployManager.stopDeploy("success") DeployManager.stopDeploy("success")
TunnelManager.addDeploySuccessLog("Импорт состояния WDTT Plus завершён.") TunnelManager.addDeploySuccessLog("Импорт состояния WDTT Plus завершён.")
true true
} catch (e: Exception) { } catch (e: Exception) {
if (rollbackPrepared) {
runCatching { sshClient?.let(::rollbackServerUpdate) }
.onFailure { rollbackError -> DeployManager.writeError("Import rollback failed: ${rollbackError.message}") }
rollbackPrepared = false
}
DeployManager.writeError("Server import critical: ${e.message}\n${e.stackTraceToString().take(500)}") DeployManager.writeError("Server import critical: ${e.message}\n${e.stackTraceToString().take(500)}")
DeployManager.stopDeploy("Ошибка импорта") DeployManager.stopDeploy("Ошибка импорта")
throw e throw e
@@ -6774,6 +7044,60 @@ private fun validatePreservedServerState(beforeJson: String, afterJson: String)
} }
} }
internal fun validateImportedServerState(
sourceJson: String,
beforeJson: String?,
afterJson: String,
replace: Boolean
) {
val source = JSONObject(sourceJson)
val after = JSONObject(afterJson)
validatePasswordsDbStructure(source)
validatePasswordsDbStructure(after)
if (!replace && beforeJson != null) {
validatePreservedServerState(beforeJson, afterJson)
}
val sourcePasswords = source.optJSONObject("passwords") ?: JSONObject()
val beforePasswords = beforeJson?.let { JSONObject(it).optJSONObject("passwords") } ?: JSONObject()
val afterPasswords = after.optJSONObject("passwords") ?: JSONObject()
val afterDevices = after.optJSONObject("devices") ?: JSONObject()
val safeExpiryCutoff = System.currentTimeMillis() / 1000L + 300L
sourcePasswords.keys().forEach { password ->
if (!replace && beforePasswords.has(password)) return@forEach
val expected = sourcePasswords.optJSONObject(password) ?: return@forEach
val expiresAt = expected.optLong("expires_at", 0L)
if (expiresAt != 0L && expiresAt <= safeExpiryCutoff) return@forEach
val actual = afterPasswords.optJSONObject(password)
?: throw IllegalStateException("после импорта не найден клиент ${password.take(4)}…")
listOf("device_id", "label", "vk_hash").forEach { field ->
require(expected.optString(field, "") == actual.optString(field, "")) {
"после импорта изменилось поле $field у клиента ${password.take(4)}…"
}
}
listOf("expires_at", "down_bytes", "up_bytes").forEach { field ->
require(expected.optLong(field, 0L) == actual.optLong(field, 0L)) {
"после импорта изменилось поле $field у клиента ${password.take(4)}…"
}
}
require(expected.optBoolean("is_deactivated", false) == actual.optBoolean("is_deactivated", false)) {
"после импорта изменился статус клиента ${password.take(4)}…"
}
listOf("bind_history", "traffic").forEach { field ->
require(expected.optJSONArray(field)?.toString().orEmpty() == actual.optJSONArray(field)?.toString().orEmpty()) {
"после импорта изменилась история $field у клиента ${password.take(4)}…"
}
}
val deviceId = expected.optString("device_id", "")
if (deviceId.isNotBlank()) {
require(afterDevices.has(deviceId)) {
"после импорта отсутствует привязанное устройство клиента ${password.take(4)}…"
}
}
}
}
private suspend fun performDeploy( private suspend fun performDeploy(
context: Context, context: Context,
host: String, user: String, pass: String, port: Int, host: String, user: String, pass: String, port: Int,
@@ -6787,6 +7111,7 @@ private suspend fun performDeploy(
var sshClient: SSHClient? = null var sshClient: SSHClient? = null
var rollbackPrepared = false var rollbackPrepared = false
var preservedDbJson: String? = null var preservedDbJson: String? = null
var preImportDbJson: String? = null
try { try {
onProgress(0.02f, "Подключение...") onProgress(0.02f, "Подключение...")
session = createSSHSession(host, user, pass, port) session = createSSHSession(host, user, pass, port)
@@ -6819,12 +7144,15 @@ private suspend fun performDeploy(
return@withContext false return@withContext false
} }
val expectedServerSha256 = sha256File(serverFile) val expectedServerSha256 = sha256File(serverFile)
if (mode == DeployMode.PreserveData) { if (mode == DeployMode.PreserveData || importPlan != null) {
onProgress(0.055f, "Проверка сохранённых данных...") onProgress(0.055f, "Проверка сохранённых данных...")
val currentDbJson = readRemotePasswordsJson(ssh)?.also { val currentDbJson = readRemotePasswordsJson(ssh)?.also {
validatePasswordsDbStructure(JSONObject(it)) validatePasswordsDbStructure(JSONObject(it))
} }
if (mode == DeployMode.PreserveData) {
if (importPlan == null) preservedDbJson = currentDbJson if (importPlan == null) preservedDbJson = currentDbJson
if (importPlan?.mode == ServerImportMode.Merge) preImportDbJson = currentDbJson
}
prepareServerUpdateRollback(ssh) prepareServerUpdateRollback(ssh)
rollbackPrepared = true rollbackPrepared = true
} }
@@ -6911,6 +7239,14 @@ private suspend fun performDeploy(
?: throw IllegalStateException("после обновления не найдена база passwords.json") ?: throw IllegalStateException("после обновления не найдена база passwords.json")
validatePasswordsDbStructure(JSONObject(updatedDbJson)) validatePasswordsDbStructure(JSONObject(updatedDbJson))
preservedDbJson?.let { validatePreservedServerState(it, updatedDbJson) } preservedDbJson?.let { validatePreservedServerState(it, updatedDbJson) }
importPlan?.let { plan ->
validateImportedServerState(
sourceJson = plan.backup.passwordsJson,
beforeJson = if (plan.mode == ServerImportMode.Merge) preImportDbJson else null,
afterJson = updatedDbJson,
replace = plan.mode == ServerImportMode.Replace
)
}
if (rollbackPrepared) { if (rollbackPrepared) {
cleanupServerUpdateRollback(ssh) cleanupServerUpdateRollback(ssh)
rollbackPrepared = false rollbackPrepared = false
@@ -7054,7 +7390,8 @@ private fun ServerImportConfirmDialog(
} }
val wgText = when { val wgText = when {
mode == ServerImportMode.Replace && backup.hasWgKeys -> "заменить WG-ключи из бэкапа" mode == ServerImportMode.Replace && backup.hasWgKeys -> "заменить WG-ключи из бэкапа"
mode == ServerImportMode.Replace -> "WG-ключей в бэкапе нет, сервер создаст новые" mode == ServerImportMode.Replace -> "не менять ключи целевого сервера; если их нет, сервер создаст новые"
backup.hasWgKeys -> "не трогать ключи целевого сервера; WG-ключи из бэкапа в режиме «Добавить» не применяются"
else -> "не трогать WG-ключи текущего сервера" else -> "не трогать WG-ключи текущего сервера"
} }
@@ -7586,16 +7923,9 @@ private fun TelegramBotHelpDialog(onDismiss: () -> Unit) {
style = MaterialTheme.typography.bodyMedium, style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
TelegramBotActionRow( TelegramBotFatherRows(
buttonText = "Мини-приложение BotFather", onOpenMiniApp = { openTelegramBot("BotFather", miniApp = true) },
handle = "@BotFather", onOpenChat = { openTelegramBot("BotFather") },
onOpen = { openTelegramBot("BotFather", miniApp = true) },
onCopy = { copyTelegramHandle("@BotFather") }
)
TelegramBotActionRow(
buttonText = "Обычный чат @BotFather",
handle = "@BotFather",
onOpen = { openTelegramBot("BotFather") },
onCopy = { copyTelegramHandle("@BotFather") } onCopy = { copyTelegramHandle("@BotFather") }
) )
@@ -7635,6 +7965,53 @@ private fun TelegramBotHelpDialog(onDismiss: () -> Unit) {
} }
} }
@Composable
private fun TelegramBotFatherRows(
onOpenMiniApp: () -> Unit,
onOpenChat: () -> Unit,
onCopy: () -> Unit
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(
modifier = Modifier.weight(1f),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedButton(
onClick = onOpenMiniApp,
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 48.dp),
shape = RoundedCornerShape(16.dp)
) {
Text("Мини-приложение BotFather", textAlign = TextAlign.Center)
}
OutlinedButton(
onClick = onOpenChat,
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 48.dp),
shape = RoundedCornerShape(16.dp)
) {
Text("Обычный чат @BotFather", textAlign = TextAlign.Center)
}
}
FilledTonalIconButton(
onClick = onCopy,
modifier = Modifier.size(48.dp)
) {
Icon(
Icons.Default.ContentCopy,
contentDescription = "Скопировать @BotFather",
modifier = Modifier.size(20.dp)
)
}
}
}
@Composable @Composable
private fun TelegramBotActionRow( private fun TelegramBotActionRow(
buttonText: String, buttonText: String,
@@ -1,17 +1,15 @@
package com.wdtt.plus.ui package com.wdtt.plus.ui
import android.content.pm.PackageManager import android.content.pm.PackageManager
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.background import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.* import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.items
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
@@ -21,9 +19,13 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
@@ -37,10 +39,9 @@ import com.wdtt.plus.SettingsStore
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job import kotlinx.coroutines.Job
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import kotlin.math.roundToInt
import androidx.compose.runtime.Stable import androidx.compose.runtime.Stable
@@ -212,43 +213,57 @@ fun ExceptionsTab(
firstVisibleItemIndex, firstVisibleItemIndex,
firstVisibleItemScrollOffset firstVisibleItemScrollOffset
) )
var topBlockVisible by rememberSaveable { mutableStateOf(true) } var topBlockHeightPx by remember { mutableFloatStateOf(0f) }
var topBlockOffsetPx by rememberSaveable { mutableStateOf(0f) }
var topBlockPositionInitialized by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(listState) { LaunchedEffect(topBlockHeightPx) {
var previousIndex = listState.firstVisibleItemIndex if (topBlockHeightPx <= 0f) return@LaunchedEffect
var previousOffset = listState.firstVisibleItemScrollOffset if (!topBlockPositionInitialized) {
if (listState.firstVisibleItemIndex > 0 || listState.firstVisibleItemScrollOffset > 0) {
snapshotFlow { topBlockOffsetPx = -topBlockHeightPx
Triple(
listState.firstVisibleItemIndex,
listState.firstVisibleItemScrollOffset,
listState.isScrollInProgress
)
} }
.distinctUntilChanged() topBlockPositionInitialized = true
.filter { it.third } } else {
.collect { (index, offset, _) -> topBlockOffsetPx = topBlockOffsetPx.coerceIn(-topBlockHeightPx, 0f)
val scrollingDown = index > previousIndex ||
(index == previousIndex && offset > previousOffset)
val scrollingUp = index < previousIndex ||
(index == previousIndex && offset < previousOffset)
if (scrollingDown) {
topBlockVisible = false
} else if (scrollingUp || (index == 0 && offset == 0)) {
topBlockVisible = true
}
previousIndex = index
previousOffset = offset
} }
} }
Column(modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp)) { val collapsingHeaderConnection = remember(topBlockHeightPx) {
AnimatedVisibility( object : NestedScrollConnection {
visible = topBlockVisible, override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
enter = slideInVertically(initialOffsetY = { -it }) + fadeIn(), if (topBlockHeightPx <= 0f) return Offset.Zero
exit = slideOutVertically(targetOffsetY = { -it }) + fadeOut() val delta = available.y
val canCollapse = delta < 0f && topBlockOffsetPx > -topBlockHeightPx
val canExpand = delta > 0f && topBlockOffsetPx < 0f
if (!canCollapse && !canExpand) return Offset.Zero
val previousOffset = topBlockOffsetPx
topBlockOffsetPx = (previousOffset + delta).coerceIn(-topBlockHeightPx, 0f)
topBlockPositionInitialized = true
return Offset(x = 0f, y = topBlockOffsetPx - previousOffset)
}
}
}
val collapseFraction = if (topBlockHeightPx > 0f) {
(-topBlockOffsetPx / topBlockHeightPx).coerceIn(0f, 1f)
} else {
0f
}
Column(
modifier = Modifier
.fillMaxSize()
.nestedScroll(collapsingHeaderConnection)
.padding(horizontal = 16.dp)
) {
CollapsingExceptionsHeader(
offsetPx = topBlockOffsetPx,
onHeightChanged = { measuredHeight ->
if (measuredHeight > 0 && topBlockHeightPx != measuredHeight.toFloat()) {
topBlockHeightPx = measuredHeight.toFloat()
}
}
) { ) {
Column { Column {
// Header // Header
@@ -393,7 +408,7 @@ fun ExceptionsTab(
placeholder = { Text("Поиск приложений...", fontSize = 14.sp) }, placeholder = { Text("Поиск приложений...", fontSize = 14.sp) },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(top = if (topBlockVisible) 0.dp else 16.dp, bottom = 12.dp) .padding(top = 16.dp * collapseFraction, bottom = 12.dp)
.height(52.dp), .height(52.dp),
shape = RoundedCornerShape(16.dp), shape = RoundedCornerShape(16.dp),
leadingIcon = { Icon(Icons.Default.Search, null, modifier = Modifier.size(20.dp)) }, leadingIcon = { Icon(Icons.Default.Search, null, modifier = Modifier.size(20.dp)) },
@@ -440,6 +455,35 @@ fun ExceptionsTab(
} }
} }
@Composable
private fun CollapsingExceptionsHeader(
offsetPx: Float,
onHeightChanged: (Int) -> Unit,
content: @Composable () -> Unit
) {
Layout(
modifier = Modifier
.fillMaxWidth()
.clipToBounds(),
content = {
Box(
modifier = Modifier
.fillMaxWidth()
.onSizeChanged { onHeightChanged(it.height) }
) {
content()
}
}
) { measurables, constraints ->
val placeable = measurables.single().measure(constraints.copy(minHeight = 0))
val safeOffset = offsetPx.roundToInt().coerceIn(-placeable.height, 0)
val visibleHeight = (placeable.height + safeOffset).coerceAtLeast(0)
layout(placeable.width, visibleHeight) {
placeable.placeRelative(0, safeOffset)
}
}
}
@Composable @Composable
private fun ModeChip(label: String, selected: Boolean, onClick: () -> Unit) { private fun ModeChip(label: String, selected: Boolean, onClick: () -> Unit) {
FilterChip( FilterChip(
@@ -37,7 +37,7 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.plus.SettingsStore import com.wdtt.plus.SettingsStore
import com.wdtt.plus.normalizeVpnProfileName import com.wdtt.plus.sanitizeVpnProfileNameInput
import com.wdtt.plus.vpnProfileDisplayName import com.wdtt.plus.vpnProfileDisplayName
import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
@@ -570,7 +570,7 @@ fun FloatingToolbar(
text = { text = {
OutlinedTextField( OutlinedTextField(
value = profileNameInput, value = profileNameInput,
onValueChange = { profileNameInput = normalizeVpnProfileName(it) }, onValueChange = { profileNameInput = sanitizeVpnProfileNameInput(it) },
label = { Text("Название") }, label = { Text("Название") },
singleLine = true, singleLine = true,
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
@@ -127,6 +127,7 @@ import com.wdtt.plus.ServerClientCreateRequest
import com.wdtt.plus.ServerClientInfo import com.wdtt.plus.ServerClientInfo
import com.wdtt.plus.ServerTrafficPeriod import com.wdtt.plus.ServerTrafficPeriod
import com.wdtt.plus.TransferFiles import com.wdtt.plus.TransferFiles
import com.wdtt.plus.WDTTColors
import com.wdtt.plus.connectionLink import com.wdtt.plus.connectionLink
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
@@ -159,6 +160,37 @@ private enum class ClientExpiryFilter { All, Valid, Expired, Unlimited }
private enum class ClientVkHashFilter { All, Present, Missing } private enum class ClientVkHashFilter { All, Present, Missing }
private enum class ClientsServerRefreshState { Unknown, Ready, Error }
internal fun serverClientsAccessIssue(
host: String,
hostValid: Boolean,
sshPassword: String,
sshPort: Int,
mainPassword: String
): String? = when {
host.isBlank() -> "Укажите IP-адрес или домен сервера в верхнем блоке «Деплой»."
!hostValid -> "Проверьте IP-адрес или домен сервера в верхнем блоке «Деплой»."
sshPassword.isBlank() -> "Укажите SSH-пароль сервера в верхнем блоке «Деплой»."
sshPort !in 1..65535 -> "Укажите корректный SSH-порт от 1 до 65535."
mainPassword.isBlank() -> "Откройте «Секреты» и укажите главный пароль администратора."
else -> null
}
internal fun shouldAutoRefreshServerClients(
expanded: Boolean,
targetReady: Boolean,
enabled: Boolean,
busy: Boolean,
automaticRefreshAttempted: Boolean,
lastRefreshAt: Long
): Boolean = expanded &&
targetReady &&
enabled &&
!busy &&
!automaticRefreshAttempted &&
lastRefreshAt == 0L
private data class PendingClientAction( private data class PendingClientAction(
val title: String, val title: String,
val message: String, val message: String,
@@ -168,6 +200,108 @@ private data class PendingClientAction(
val run: suspend () -> ServerAdminActionResult val run: suspend () -> ServerAdminActionResult
) )
@Composable
private fun ClientsServerStateCard(
state: ServerAdminState?,
refreshBusy: Boolean,
lastRefreshAt: Long,
lastRefreshAttemptAt: Long,
lastRefreshError: String,
accessIssue: String?,
enabled: Boolean,
onRefresh: () -> Unit
) {
val visualState = when {
lastRefreshError.isNotBlank() -> ClientsServerRefreshState.Error
lastRefreshAt > 0L && state != null -> ClientsServerRefreshState.Ready
else -> ClientsServerRefreshState.Unknown
}
val indicatorColor = when (visualState) {
ClientsServerRefreshState.Unknown -> MaterialTheme.colorScheme.outline
ClientsServerRefreshState.Ready -> WDTTColors.connected
ClientsServerRefreshState.Error -> MaterialTheme.colorScheme.error
}
val title = when {
refreshBusy -> "Обновляю клиентов и состояние сервера..."
accessIssue != null -> "Обновление пока недоступно"
lastRefreshError.isNotBlank() -> "Не удалось обновить данные"
lastRefreshAt > 0L && state != null -> "Клиенты и сервер обновлены"
else -> "Клиенты и сервер ещё не проверены"
}
val details = when {
refreshBusy -> "Проверяю SSH-доступ, главный пароль администратора и читаю актуальный список."
accessIssue != null -> accessIssue
lastRefreshError.isNotBlank() -> buildString {
if (lastRefreshAttemptAt > 0L) {
append("Последняя попытка: ${formatRefreshDateTime(lastRefreshAttemptAt)}. ")
}
append(lastRefreshError)
}
lastRefreshAt > 0L && state != null ->
"Обновлено: ${formatRefreshDateTime(lastRefreshAt)}.\nКлиентов: ${state.passwordCount}, устройств: ${state.deviceCount}."
else -> "При первом раскрытии за текущий запуск список обновится автоматически. Правильность главного пароля проверит сервер."
}
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.40f),
border = BorderStroke(1.dp, indicatorColor.copy(alpha = 0.42f))
) {
Column(
modifier = Modifier.padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
if (refreshBusy) {
CircularProgressIndicator(
modifier = Modifier.size(14.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.primary
)
} else {
Box(
modifier = Modifier
.size(12.dp)
.background(indicatorColor, CircleShape)
)
}
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
title,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold
)
Text(
details,
style = MaterialTheme.typography.bodySmall,
color = if (lastRefreshError.isNotBlank()) {
MaterialTheme.colorScheme.error
} else {
MaterialTheme.colorScheme.onSurfaceVariant
}
)
}
}
TextButton(
onClick = onRefresh,
enabled = enabled && accessIssue == null && !refreshBusy,
modifier = Modifier.align(Alignment.End)
) {
if (refreshBusy) {
CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)
Spacer(Modifier.width(6.dp))
}
Text(if (refreshBusy) "Обновляю..." else "Обновить")
}
}
}
}
@OptIn(ExperimentalLayoutApi::class) @OptIn(ExperimentalLayoutApi::class)
@Composable @Composable
fun ServerClientsSection( fun ServerClientsSection(
@@ -180,7 +314,8 @@ fun ServerClientsSection(
adminProfile: ServerAdminProfileInfo, adminProfile: ServerAdminProfileInfo,
sourceProfileName: String, sourceProfileName: String,
enabled: Boolean, enabled: Boolean,
expanded: Boolean = true, hostValid: Boolean,
expanded: Boolean = false,
modifier: Modifier = Modifier, modifier: Modifier = Modifier,
onExpandedChange: (Boolean) -> Unit = {}, onExpandedChange: (Boolean) -> Unit = {},
onExpanded: () -> Unit = {} onExpanded: () -> Unit = {}
@@ -190,6 +325,7 @@ fun ServerClientsSection(
val clientsViewModel: ServerClientsViewModel = viewModel() val clientsViewModel: ServerClientsViewModel = viewModel()
var state by clientsViewModel.serverState var state by clientsViewModel.serverState
var busy by remember { mutableStateOf(false) } var busy by remember { mutableStateOf(false) }
var refreshBusy by remember { mutableStateOf(false) }
var status by rememberSaveable { mutableStateOf("") } var status by rememberSaveable { mutableStateOf("") }
var showCreateWizard by rememberSaveable { mutableStateOf(false) } var showCreateWizard by rememberSaveable { mutableStateOf(false) }
var showImportMethods by rememberSaveable { mutableStateOf(false) } var showImportMethods by rememberSaveable { mutableStateOf(false) }
@@ -212,21 +348,43 @@ fun ServerClientsSection(
var clientSearchFocused by remember { mutableStateOf(false) } var clientSearchFocused by remember { mutableStateOf(false) }
var clientSearch by clientsViewModel.clientSearch var clientSearch by clientsViewModel.clientSearch
var selectedClientIndex by clientsViewModel.selectedClientIndex var selectedClientIndex by clientsViewModel.selectedClientIndex
var lastRefreshAt by clientsViewModel.lastRefreshAt
var lastRefreshAttemptAt by clientsViewModel.lastRefreshAttemptAt
var lastRefreshError by clientsViewModel.lastRefreshError
var automaticRefreshAttempted by clientsViewModel.automaticRefreshAttempted
val inboxTransfer by ClientTransferInbox.pending.collectAsStateWithLifecycle() val inboxTransfer by ClientTransferInbox.pending.collectAsStateWithLifecycle()
val arrowRotation by animateFloatAsState( val arrowRotation by animateFloatAsState(
targetValue = if (expanded) 180f else 0f, targetValue = if (expanded) 180f else 0f,
label = "server_clients_arrow_rotation" label = "server_clients_arrow_rotation"
) )
val targetReady = host.isNotBlank() && sshPassword.isNotBlank() && mainPassword.isNotBlank() val accessIssue = serverClientsAccessIssue(
val targetKey = remember(host, user, sshPort, mainPassword) { host = host,
listOf(host.trim(), user.ifBlank { "root" }, sshPort.toString(), mainPassword.hashCode().toString()).joinToString("\u0000") hostValid = hostValid,
sshPassword = sshPassword,
sshPort = sshPort,
mainPassword = mainPassword
)
val targetReady = accessIssue == null
val targetKey = remember(host, user, sshPassword, sshPort, mainPassword) {
listOf(
host.trim(),
user.ifBlank { "root" },
sshPort.toString(),
sshPassword.hashCode().toString(),
mainPassword.hashCode().toString()
).joinToString("\u0000")
} }
LaunchedEffect(targetKey, targetReady) { LaunchedEffect(targetKey) {
if (targetReady && clientsViewModel.targetKey != targetKey) { if (clientsViewModel.targetKey != targetKey) {
clientsViewModel.targetKey = targetKey clientsViewModel.targetKey = targetKey
state = null val cached = ServerClientsProcessCache.get(targetKey)
state = cached?.state
status = "" status = ""
lastRefreshAt = cached?.lastRefreshAt ?: 0L
lastRefreshAttemptAt = cached?.lastRefreshAttemptAt ?: 0L
lastRefreshError = cached?.lastRefreshError.orEmpty()
automaticRefreshAttempted = cached?.attempted == true
detailsClient = null detailsClient = null
showServerTools = false showServerTools = false
clientSearch = "" clientSearch = ""
@@ -284,20 +442,91 @@ fun ServerClientsSection(
} }
} }
fun applyFreshServerState(freshState: ServerAdminState) {
val refreshedAt = System.currentTimeMillis()
state = freshState
lastRefreshAt = refreshedAt
lastRefreshAttemptAt = refreshedAt
lastRefreshError = ""
automaticRefreshAttempted = true
ServerClientsProcessCache.put(
targetKey,
ServerClientsProcessSnapshot(
state = freshState,
lastRefreshAt = refreshedAt,
lastRefreshAttemptAt = refreshedAt,
lastRefreshError = "",
attempted = true
)
)
}
fun recordRefreshFailure(error: Throwable) {
lastRefreshAttemptAt = System.currentTimeMillis()
lastRefreshError = error.message ?: "не удалось прочитать клиентов и состояние сервера"
automaticRefreshAttempted = true
ServerClientsProcessCache.put(
targetKey,
ServerClientsProcessSnapshot(
state = state,
lastRefreshAt = lastRefreshAt,
lastRefreshAttemptAt = lastRefreshAttemptAt,
lastRefreshError = lastRefreshError,
attempted = true
)
)
}
fun refreshClients() { fun refreshClients() {
if (!targetReady || busy) return if (!targetReady || !enabled || busy) return
val requestedTargetKey = targetKey
busy = true busy = true
status = "Читаю клиентов на сервере..." refreshBusy = true
lastRefreshError = ""
automaticRefreshAttempted = true
ServerClientsProcessCache.put(
targetKey,
ServerClientsProcessSnapshot(
state = state,
lastRefreshAt = lastRefreshAt,
lastRefreshAttemptAt = lastRefreshAttemptAt,
lastRefreshError = "",
attempted = true
)
)
scope.launch { scope.launch {
try {
runCatching { ServerAdminClient.list(target) } runCatching { ServerAdminClient.list(target) }
.onSuccess { .onSuccess {
state = it if (clientsViewModel.targetKey == requestedTargetKey) {
status = "Готово: клиентов ${it.passwordCount}, устройств ${it.deviceCount}." applyFreshServerState(it)
} }
.onFailure { status = "Ошибка: ${it.message ?: "не удалось прочитать клиентов"}" } }
.onFailure {
if (clientsViewModel.targetKey == requestedTargetKey) {
recordRefreshFailure(it)
}
}
} finally {
refreshBusy = false
busy = false busy = false
} }
} }
}
LaunchedEffect(expanded, targetKey, targetReady, enabled, busy, automaticRefreshAttempted, lastRefreshAt) {
if (shouldAutoRefreshServerClients(
expanded = expanded,
targetReady = targetReady,
enabled = enabled,
busy = busy,
automaticRefreshAttempted = automaticRefreshAttempted,
lastRefreshAt = lastRefreshAt
)
) {
refreshClients()
}
}
fun runAction(action: PendingClientAction) { fun runAction(action: PendingClientAction) {
pendingAction = null pendingAction = null
@@ -311,7 +540,9 @@ fun ServerClientsSection(
append(result.message) append(result.message)
if (result.restarted) append(". Сервис перезапущен.") if (result.restarted) append(". Сервис перезапущен.")
} }
runCatching { ServerAdminClient.list(target) }.onSuccess { state = it } runCatching { ServerAdminClient.list(target) }
.onSuccess(::applyFreshServerState)
.onFailure(::recordRefreshFailure)
} }
.onFailure { status = "Ошибка: ${it.message ?: "операция не выполнена"}" } .onFailure { status = "Ошибка: ${it.message ?: "операция не выполнена"}" }
busy = false busy = false
@@ -325,7 +556,9 @@ fun ServerClientsSection(
runCatching { action() } runCatching { action() }
.onSuccess { result -> .onSuccess { result ->
status = result.message + if (result.restarted) ". Сервис перезапущен." else "" status = result.message + if (result.restarted) ". Сервис перезапущен." else ""
runCatching { ServerAdminClient.list(target) }.onSuccess { state = it } runCatching { ServerAdminClient.list(target) }
.onSuccess(::applyFreshServerState)
.onFailure(::recordRefreshFailure)
} }
.onFailure { status = "Ошибка: ${it.message ?: "операция не выполнена"}" } .onFailure { status = "Ошибка: ${it.message ?: "операция не выполнена"}" }
busy = false busy = false
@@ -389,23 +622,29 @@ fun ServerClientsSection(
color = MaterialTheme.colorScheme.onSurfaceVariant color = MaterialTheme.colorScheme.onSurfaceVariant
) )
if (!targetReady) { ClientsServerStateCard(
Text( state = state,
"Укажите IP/домен, SSH-пароль и главный пароль в «Секретах». После деплоя нажмите «Обновить».", refreshBusy = refreshBusy,
style = MaterialTheme.typography.bodySmall, lastRefreshAt = lastRefreshAt,
color = MaterialTheme.colorScheme.onSurfaceVariant lastRefreshAttemptAt = lastRefreshAttemptAt,
lastRefreshError = lastRefreshError,
accessIssue = accessIssue,
enabled = enabled && !busy,
onRefresh = { refreshClients() }
) )
}
ClientPanel {
Text(
"Действия для сервера",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
FlowRow( FlowRow(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
verticalArrangement = Arrangement.spacedBy(8.dp) verticalArrangement = Arrangement.spacedBy(8.dp)
) { ) {
OutlinedButton(onClick = { refreshClients() }, enabled = canUse) {
Icon(Icons.Default.Refresh, null, Modifier.size(18.dp))
Text(" Обновить")
}
Button(onClick = { showCreateWizard = true }, enabled = canUse) { Button(onClick = { showCreateWizard = true }, enabled = canUse) {
Icon(Icons.Default.Add, null, Modifier.size(18.dp)) Icon(Icons.Default.Add, null, Modifier.size(18.dp))
Text(" Создать") Text(" Создать")
@@ -417,6 +656,7 @@ fun ServerClientsSection(
Text("Сервер") Text("Сервер")
} }
} }
}
if (status.isNotBlank()) { if (status.isNotBlank()) {
ClientStatusBanner(status = status, busy = busy) ClientStatusBanner(status = status, busy = busy)
@@ -667,7 +907,9 @@ fun ServerClientsSection(
if (result.restarted) append(". Сервис перезапущен.") if (result.restarted) append(". Сервис перезапущен.")
} }
createdClient = result.createdClient createdClient = result.createdClient
runCatching { ServerAdminClient.list(target) }.onSuccess { state = it } runCatching { ServerAdminClient.list(target) }
.onSuccess(::applyFreshServerState)
.onFailure(::recordRefreshFailure)
} }
.onFailure { status = "Ошибка: ${it.message ?: "клиент не создан"}" } .onFailure { status = "Ошибка: ${it.message ?: "клиент не создан"}" }
busy = false busy = false
@@ -722,11 +964,13 @@ fun ServerClientsSection(
current?.defaultPorts ?: defaultPorts.ifBlank { "56000,56001,9000" } current?.defaultPorts ?: defaultPorts.ifBlank { "56000,56001,9000" }
) )
status = "Импорт: клиент записан, проверяю список на сервере..." status = "Импорт: клиент записан, проверяю список на сервере..."
val refreshed = ServerAdminClient.list(target) val refreshed = runCatching { ServerAdminClient.list(target) }
.onFailure(::recordRefreshFailure)
.getOrThrow()
val imported = refreshed.clients.firstOrNull { it.password == payload.password } val imported = refreshed.clients.firstOrNull { it.password == payload.password }
?: result.createdClient?.takeIf { created -> created.password == payload.password } ?: result.createdClient?.takeIf { created -> created.password == payload.password }
?: throw IllegalStateException("сервер принял импорт, но клиент не найден в свежем списке. Нажмите «Обновить» и проверьте, не достигнут ли лимит клиентов.") ?: throw IllegalStateException("сервер принял импорт, но клиент не найден в свежем списке. Нажмите «Обновить» и проверьте, не достигнут ли лимит клиентов.")
state = refreshed applyFreshServerState(refreshed)
clientSearch = "" clientSearch = ""
statusFilter = ClientStatusFilter.All statusFilter = ClientStatusFilter.All
bindingFilter = ClientBindingFilter.All bindingFilter = ClientBindingFilter.All
@@ -803,7 +1047,9 @@ fun ServerClientsSection(
.onSuccess { result -> .onSuccess { result ->
status = result.message status = result.message
changedPasswordClient = result.createdClient changedPasswordClient = result.createdClient
runCatching { ServerAdminClient.list(target) }.onSuccess { state = it } runCatching { ServerAdminClient.list(target) }
.onSuccess(::applyFreshServerState)
.onFailure(::recordRefreshFailure)
} }
.onFailure { status = "Ошибка: ${it.message ?: "пароль не изменён"}" } .onFailure { status = "Ошибка: ${it.message ?: "пароль не изменён"}" }
busy = false busy = false
@@ -2806,6 +3052,11 @@ private fun formatDateTime(ts: Long): String {
return SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault()).format(Date(ts * 1000L)) return SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.getDefault()).format(Date(ts * 1000L))
} }
private fun formatRefreshDateTime(timestampMillis: Long): String {
if (timestampMillis <= 0L) return "неизвестно"
return SimpleDateFormat("dd.MM.yyyy HH:mm", Locale("ru", "RU")).format(Date(timestampMillis))
}
private fun secretPresenceLabel(value: String): String { private fun secretPresenceLabel(value: String): String {
val count = value.split(',', ' ', '\n', '\t') val count = value.split(',', ' ', '\n', '\t')
.map { it.trim() } .map { it.trim() }
@@ -2,12 +2,36 @@ package com.wdtt.plus.ui
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import com.wdtt.plus.ServerAdminState import com.wdtt.plus.ServerAdminState
import java.util.concurrent.ConcurrentHashMap
data class ServerClientsProcessSnapshot(
val state: ServerAdminState?,
val lastRefreshAt: Long,
val lastRefreshAttemptAt: Long,
val lastRefreshError: String,
val attempted: Boolean
)
object ServerClientsProcessCache {
private val values = ConcurrentHashMap<String, ServerClientsProcessSnapshot>()
fun get(targetKey: String): ServerClientsProcessSnapshot? = values[targetKey]
fun put(targetKey: String, snapshot: ServerClientsProcessSnapshot) {
values[targetKey] = snapshot
}
}
class ServerClientsViewModel : ViewModel() { class ServerClientsViewModel : ViewModel() {
val serverState = mutableStateOf<ServerAdminState?>(null) val serverState = mutableStateOf<ServerAdminState?>(null)
val clientSearch = mutableStateOf("") val clientSearch = mutableStateOf("")
val selectedClientIndex = mutableIntStateOf(0) val selectedClientIndex = mutableIntStateOf(0)
val lastRefreshAt = mutableLongStateOf(0L)
val lastRefreshAttemptAt = mutableLongStateOf(0L)
val lastRefreshError = mutableStateOf("")
val automaticRefreshAttempted = mutableStateOf(false)
var targetKey: String = "" var targetKey: String = ""
} }
@@ -119,6 +119,38 @@ class TransferCodecTest {
assertEquals("Работа", vpnProfileTransferName(2, listOf("", "", "Работа"))) assertEquals("Работа", vpnProfileTransferName(2, listOf("", "", "Работа")))
} }
@Test
fun vpnProfileNameInput_allowsSpacesBetweenWords() {
assertEquals("Домашний ", sanitizeVpnProfileNameInput("Домашний "))
assertEquals("Домашний сервер", sanitizeVpnProfileNameInput(" Домашний сервер"))
assertEquals("Домашний сервер", normalizeVpnProfileName(" Домашний сервер "))
}
@Test
fun adminProfilePatch_omitsEmptyAndDefaultTunnelFields() {
val defaults = ServerAdminProfileInfo()
assertEquals(listOf("update-admin-profile"), buildAdminProfilePatchArgs(defaults))
assertFalse(hasMeaningfulAdminProfileFields(defaults))
val custom = defaults.copy(
vkHashes = "hash-value",
profileName = "Домашний сервер",
workersPerHash = 24,
noDns = true
)
assertEquals(
listOf(
"update-admin-profile",
"--vk-hashes", "hash-value",
"--profile-name", "Домашний сервер",
"--workers", "24",
"--no-dns"
),
buildAdminProfilePatchArgs(custom)
)
assertTrue(hasMeaningfulAdminProfileFields(custom))
}
@Test @Test
fun serverClientLink_carriesSourceVpnProfileName() { fun serverClientLink_carriesSourceVpnProfileName() {
val link = buildServerConnectionLink( val link = buildServerConnectionLink(
@@ -0,0 +1,55 @@
package com.wdtt.plus.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ServerClientsAccessTest {
@Test
fun accessRequiresDeployHostSshAndAdminPassword() {
assertEquals(
"Укажите IP-адрес или домен сервера в верхнем блоке «Деплой».",
serverClientsAccessIssue("", false, "", 22, "")
)
assertEquals(
"Проверьте IP-адрес или домен сервера в верхнем блоке «Деплой».",
serverClientsAccessIssue("https://bad host", false, "ssh", 22, "owner")
)
assertEquals(
"Укажите SSH-пароль сервера в верхнем блоке «Деплой».",
serverClientsAccessIssue("vpn.example.org", true, "", 22, "owner")
)
assertEquals(
"Укажите корректный SSH-порт от 1 до 65535.",
serverClientsAccessIssue("vpn.example.org", true, "ssh", 0, "owner")
)
assertEquals(
"Откройте «Секреты» и укажите главный пароль администратора.",
serverClientsAccessIssue("vpn.example.org", true, "ssh", 22, "")
)
assertNull(serverClientsAccessIssue("vpn.example.org", true, "ssh", 22, "owner"))
}
@Test
fun clientAutoRefreshRunsOnlyOnceForReadyTarget() {
assertTrue(shouldAutoRefreshServerClients(true, true, true, false, false, 0L))
assertFalse(shouldAutoRefreshServerClients(false, true, true, false, false, 0L))
assertFalse(shouldAutoRefreshServerClients(true, false, true, false, false, 0L))
assertFalse(shouldAutoRefreshServerClients(true, true, true, true, false, 0L))
assertFalse(shouldAutoRefreshServerClients(true, true, true, false, true, 0L))
assertFalse(shouldAutoRefreshServerClients(true, true, true, false, false, 1L))
}
@Test
fun outboundAutoRefreshRunsOncePerSshTarget() {
assertTrue(shouldAutoRefreshOutboundState(true, false, false, true, true, "new", ""))
assertFalse(shouldAutoRefreshOutboundState(true, false, false, true, true, "same", "same"))
assertFalse(shouldAutoRefreshOutboundState(false, false, false, true, true, "new", ""))
assertFalse(shouldAutoRefreshOutboundState(true, true, false, true, true, "new", ""))
assertFalse(shouldAutoRefreshOutboundState(true, false, true, true, true, "new", ""))
assertFalse(shouldAutoRefreshOutboundState(true, false, false, false, true, "new", ""))
assertFalse(shouldAutoRefreshOutboundState(true, false, false, true, false, "new", ""))
}
}
@@ -0,0 +1,126 @@
package com.wdtt.plus.ui
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertTrue
import org.junit.Test
class ServerMigrationTest {
@Test
fun backupValidation_acceptsCurrentOwnerAndClientFields() {
validatePasswordsDbStructure(database("client-a", "Телефон"))
}
@Test(expected = IllegalArgumentException::class)
fun backupValidation_rejectsInvalidOwnerProfile() {
val db = database("client-a", "Телефон")
db.getJSONObject("admin_profile").put("workers_per_hash", 500)
validatePasswordsDbStructure(db)
}
@Test
fun replaceImport_preservesClientDataAndHistory() {
val source = database("client-a", "Телефон")
val after = JSONObject(source.toString())
after.getJSONObject("passwords").getJSONObject("client-a").put("ports", "56010,56011,9010")
validateImportedServerState(source.toString(), null, after.toString(), replace = true)
}
@Test
fun mergeImport_preservesTargetAndAddsMissingClient() {
val before = database("target-client", "Существующий")
val source = database("source-client", "Перенесённый")
val after = JSONObject(before.toString())
after.getJSONObject("passwords").put(
"source-client",
JSONObject(source.getJSONObject("passwords").getJSONObject("source-client").toString())
)
validateImportedServerState(source.toString(), before.toString(), after.toString(), replace = false)
assertTrue(after.getJSONObject("passwords").has("target-client"))
assertTrue(after.getJSONObject("passwords").has("source-client"))
}
@Test(expected = IllegalStateException::class)
fun importValidation_detectsMissingTransferredClient() {
val source = database("client-a", "Телефон")
val after = database("another-client", "Другой")
validateImportedServerState(source.toString(), null, after.toString(), replace = true)
}
@Test(expected = IllegalArgumentException::class)
fun mergeRejectsDeviceIdWithDifferentKeys() {
val source = database("source-client", "Перенесённый")
val target = database("target-client", "Существующий")
bindDevice(source, "source-client", "same-device", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
bindDevice(target, "target-client", "same-device", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=")
mergeServerDatabaseEntries(source, target, "56000,56001,9000")
}
@Test
fun mergeCopiesOnlyDeviceOfAddedClient() {
val source = database("source-client", "Перенесённый")
val target = database("target-client", "Существующий")
bindDevice(source, "source-client", "used-device", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
bindDevice(target, "target-client", "target-device", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=")
source.getJSONObject("devices").put(
"orphan-device",
device("orphan-device", "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC=")
)
mergeServerDatabaseEntries(source, target, "56000,56001,9000")
assertTrue(target.getJSONObject("devices").has("used-device"))
assertTrue(!target.getJSONObject("devices").has("orphan-device"))
assertTrue(target.getJSONObject("devices").getJSONObject("used-device").getString("ip") == "10.66.66.3")
}
private fun database(password: String, label: String): JSONObject {
val entry = JSONObject()
.put("device_id", "")
.put("expires_at", 0L)
.put("down_bytes", 1024L)
.put("up_bytes", 2048L)
.put("label", label)
.put("vk_hash", "1234567890abcdef")
.put("ports", "56000,56001,9000")
.put("traffic", JSONArray().put(
JSONObject()
.put("date", "2026-07-05")
.put("down_bytes", 1024L)
.put("up_bytes", 2048L)
))
.put("bind_history", JSONArray())
return JSONObject()
.put("main_password", "owner-password")
.put("admin_id", "123456")
.put("bot_token", "123456:token")
.put("dns", "1.1.1.1,1.0.0.1")
.put("public_ip", "vpn.example.org")
.put("default_ports", "56000,56001,9000")
.put("max_passwords", 50)
.put("passwords", JSONObject().put(password, entry))
.put("devices", JSONObject())
.put("admin_profile", JSONObject()
.put("workers_per_hash", 16)
.put("protocol", "udp")
.put("listen_port", 9000)
.put("ports", "56000,56001,9000")
)
}
private fun bindDevice(db: JSONObject, password: String, deviceId: String, privateKey: String) {
db.getJSONObject("passwords").getJSONObject(password).put("device_id", deviceId)
db.getJSONObject("devices").put(deviceId, device(deviceId, privateKey))
}
private fun device(deviceId: String, privateKey: String): JSONObject = JSONObject()
.put("device_id", deviceId)
.put("ip", "10.66.66.2")
.put("priv_key", privateKey)
.put("pub_key", "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD=")
}