Выпуск WDTT Plus v3
This commit is contained in:
1 parent
ab1246525f
commit
cba54802d0
21 files changed
+1986
-164
No files matched your search
@@ -0,0 +1,114 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import org.json.JSONObject
|
||||
import java.security.SecureRandom
|
||||
|
||||
private const val CLIENT_TRANSFER_FORMAT = "wdtt-plus-client"
|
||||
private const val CLIENT_TRANSFER_VERSION = 1
|
||||
|
||||
data class ClientTransferPayload(
|
||||
val password: String,
|
||||
val label: String,
|
||||
val vkHash: String,
|
||||
val expiresAt: Long,
|
||||
val deactivated: Boolean,
|
||||
val createdAt: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
object ClientPasswordRules {
|
||||
const val LENGTH = 16
|
||||
const val ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789"
|
||||
private val random = SecureRandom()
|
||||
|
||||
fun generate(): String = buildString(LENGTH) {
|
||||
repeat(LENGTH) { append(ALPHABET[random.nextInt(ALPHABET.length)]) }
|
||||
}
|
||||
|
||||
fun validate(value: String): String? = when {
|
||||
value.length != LENGTH -> "Пароль должен содержать ровно $LENGTH символов."
|
||||
value.any { it !in ALPHABET } -> "Допустимы только безопасные латинские буквы и цифры без 0, 1, I, i, O, o и l."
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
object ClientTransferCodec {
|
||||
fun encode(payload: ClientTransferPayload): String {
|
||||
ClientPasswordRules.validate(payload.password)?.let { throw IllegalArgumentException(it) }
|
||||
require(payload.expiresAt >= 0) { "Некорректный срок клиента." }
|
||||
require(payload.label.length <= 40 && payload.label.none(Char::isISOControl)) { "Название клиента повреждено или слишком длинное." }
|
||||
val vkHash = normalizeVkHashes(payload.vkHash)
|
||||
return JSONObject()
|
||||
.put("format", CLIENT_TRANSFER_FORMAT)
|
||||
.put("version", CLIENT_TRANSFER_VERSION)
|
||||
.put("created_at", payload.createdAt)
|
||||
.put("password", payload.password)
|
||||
.put("label", payload.label.trim())
|
||||
.put("vk_hash", vkHash)
|
||||
.put("expires_at", payload.expiresAt)
|
||||
.put("deactivated", payload.deactivated)
|
||||
.toString()
|
||||
}
|
||||
|
||||
fun decode(value: String): ClientTransferPayload {
|
||||
val json = runCatching { JSONObject(value.trim()) }
|
||||
.getOrElse { throw IllegalArgumentException("Данные клиента повреждены или имеют неверный формат.") }
|
||||
require(json.optString("format") == CLIENT_TRANSFER_FORMAT) { "Это не файл переноса клиента WDTT Plus." }
|
||||
require(json.optInt("version", -1) == CLIENT_TRANSFER_VERSION) { "Версия файла клиента не поддерживается." }
|
||||
val password = json.optString("password")
|
||||
ClientPasswordRules.validate(password)?.let { throw IllegalArgumentException(it) }
|
||||
val label = json.optString("label").trim()
|
||||
require(label.length <= 40 && label.none(Char::isISOControl)) { "Название клиента повреждено или длиннее 40 символов." }
|
||||
val vkHash = normalizeVkHashes(json.optString("vk_hash"))
|
||||
val expiresAt = json.optLong("expires_at", -1)
|
||||
require(expiresAt >= 0) { "В файле указан некорректный срок клиента." }
|
||||
return ClientTransferPayload(
|
||||
password = password,
|
||||
label = label,
|
||||
vkHash = vkHash,
|
||||
expiresAt = expiresAt,
|
||||
deactivated = json.optBoolean("deactivated", false),
|
||||
createdAt = json.optLong("created_at", 0)
|
||||
)
|
||||
}
|
||||
|
||||
fun isClientTransfer(value: String): Boolean = runCatching {
|
||||
val json = JSONObject(value.trim())
|
||||
json.optString("format") == CLIENT_TRANSFER_FORMAT
|
||||
}.getOrDefault(false)
|
||||
|
||||
fun fromClient(client: ServerClientInfo): ClientTransferPayload = ClientTransferPayload(
|
||||
password = client.password,
|
||||
label = client.label,
|
||||
vkHash = client.vkHash,
|
||||
expiresAt = client.expiresAt,
|
||||
deactivated = client.status == "deactivated"
|
||||
)
|
||||
|
||||
private fun normalizeVkHashes(value: String): String {
|
||||
val clean = value.trim()
|
||||
if (clean.isBlank()) return ""
|
||||
require(clean.length <= 4096 && clean.none(Char::isISOControl)) { "Поле VK-хешей повреждено." }
|
||||
val hashes = clean.split(Regex("[,\\s]+"))
|
||||
.map { VkJoinLink.extractHash(it) }
|
||||
.filter { it.isNotBlank() }
|
||||
require(hashes.isNotEmpty() && hashes.all { it.length >= 16 } && hashes.none { it.contains('/') || it.contains('\\') }) {
|
||||
"VK-хеши в переносе имеют неверный формат."
|
||||
}
|
||||
return hashes.distinct().joinToString(",")
|
||||
}
|
||||
}
|
||||
|
||||
object ClientTransferInbox {
|
||||
private val mutablePending = MutableStateFlow<String?>(null)
|
||||
val pending = mutablePending.asStateFlow()
|
||||
|
||||
fun offer(value: String) {
|
||||
mutablePending.value = value.trim()
|
||||
}
|
||||
|
||||
fun clear(value: String) {
|
||||
if (mutablePending.value == value) mutablePending.value = null
|
||||
}
|
||||
}
|
||||
@@ -217,7 +217,9 @@ class MainActivity : ComponentActivity() {
|
||||
} ?: intent.clipData?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.uri
|
||||
val streamFirst = intent.type?.let { type ->
|
||||
type.startsWith("image/") || type == "application/json" ||
|
||||
type == "application/vnd.wdtt.plus.transfer" || type == "application/octet-stream"
|
||||
type == "application/vnd.wdtt.plus.transfer" ||
|
||||
type == "application/vnd.wdtt.plus.client" ||
|
||||
type == "application/octet-stream"
|
||||
} == true
|
||||
if (streamFirst && streamUri != null) {
|
||||
handleIncomingUri(streamUri, intent.type)
|
||||
@@ -252,6 +254,10 @@ class MainActivity : ComponentActivity() {
|
||||
private fun handleIncomingTransferText(value: String) {
|
||||
val link = WdttTransferCodec.extractWdttLink(value)
|
||||
when {
|
||||
ClientTransferCodec.isClientTransfer(value) -> {
|
||||
ClientTransferInbox.offer(value)
|
||||
wdttDeepLinkMessage = "Распознан перенос клиента. В режиме «Я — админ» откройте «Деплой» → «Клиенты и сервер»: перед импортом приложение покажет проверку данных и целевого сервера."
|
||||
}
|
||||
link != null -> handleIncomingWdttLink(link)
|
||||
WdttTransferCodec.isAdminTransfer(value) -> pendingAdminTransfer = value.trim()
|
||||
WdttTransferCodec.documentFormat(value) == "wdtt-server-backup" -> {
|
||||
@@ -292,7 +298,7 @@ class MainActivity : ComponentActivity() {
|
||||
wdttDeepLinkMessage = if (result == null) {
|
||||
WdttDeepLink.validate(plan.link).userMessage()
|
||||
} else {
|
||||
val profileLabel = "VPN ${result.targetProfile + 1}"
|
||||
val profileLabel = vpnProfileDisplayName(result.targetProfile, store.profileNames.first())
|
||||
val action = if (result.overwritten) "перезаписана" else "добавлена"
|
||||
val mode = if (result.storedAsLink) "сохранена в режиме ссылки" else "разобрана, поля подключения заполнены"
|
||||
"Ссылка wdtt:// $action в профиль $profileLabel: $mode."
|
||||
@@ -641,10 +647,12 @@ fun MainScreen(
|
||||
val focusManager = LocalFocusManager.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0)
|
||||
val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList())
|
||||
val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false)
|
||||
val interfaceRole by settingsStore.interfaceRole.collectAsStateWithLifecycle(initialValue = "")
|
||||
val permissionOnboardingComplete by settingsStore.permissionOnboardingComplete.collectAsStateWithLifecycle(initialValue = false)
|
||||
val migrationNoticeV2Shown by settingsStore.migrationNoticeV2Shown.collectAsStateWithLifecycle(initialValue = true)
|
||||
val migrationNoticeV3Shown by settingsStore.migrationNoticeV3Shown.collectAsStateWithLifecycle(initialValue = true)
|
||||
val isAdminInterface = interfaceRole == "admin"
|
||||
val isUpdatedInstall = remember(context) {
|
||||
runCatching {
|
||||
@@ -944,9 +952,13 @@ fun MainScreen(
|
||||
// Floating theme toolbar overlay
|
||||
FloatingToolbar(
|
||||
activeProfile = activeProfile,
|
||||
profileNames = profileNames,
|
||||
onActiveProfileChange = { profile ->
|
||||
scope.launch { settingsStore.saveActiveProfile(profile) }
|
||||
},
|
||||
onProfileNameChange = { profile, name ->
|
||||
scope.launch { settingsStore.saveProfileName(profile, name) }
|
||||
},
|
||||
interfaceRole = interfaceRole,
|
||||
onInterfaceRoleChange = { role ->
|
||||
scope.launch { settingsStore.saveInterfaceRole(role) }
|
||||
@@ -997,6 +1009,38 @@ fun MainScreen(
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
BuildConfig.VERSION_CODE == 3 &&
|
||||
isAdminInterface &&
|
||||
isUpdatedInstall &&
|
||||
!migrationNoticeV3Shown
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = {},
|
||||
properties = DialogProperties(
|
||||
dismissOnBackPress = false,
|
||||
dismissOnClickOutside = false
|
||||
),
|
||||
title = { Text("Требуется обновление сервера") },
|
||||
text = {
|
||||
Text(
|
||||
"Для корректной работы новых функций необходимо обновить установку серверной части во вкладке «Деплой».\n\n" +
|
||||
"Выберите установку с сохранением данных. Настройки, клиенты и выданные доступы сохранятся — будет обновлена только серверная часть.\n\n" +
|
||||
"Установку с нуля выполнять не нужно."
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
|
||||
Button(
|
||||
onClick = { scope.launch { settingsStore.saveMigrationNoticeV3Shown() } }
|
||||
) {
|
||||
Text("Хорошо")
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (showTransferCenter) {
|
||||
TransferCenterDialog(
|
||||
settingsStore = settingsStore,
|
||||
@@ -1126,7 +1170,7 @@ fun MainScreen(
|
||||
}
|
||||
|
||||
pendingWdttDeepLinkPlan?.let { plan ->
|
||||
val profileLabel = "VPN ${plan.targetProfile + 1}"
|
||||
val profileLabel = vpnProfileDisplayName(plan.targetProfile, profileNames)
|
||||
AlertDialog(
|
||||
onDismissRequest = onCancelWdttDeepLinkOverwrite,
|
||||
title = { Text("Профили VPN заполнены") },
|
||||
@@ -1138,7 +1182,7 @@ fun MainScreen(
|
||||
FilterChip(
|
||||
selected = plan.targetProfile == profile,
|
||||
onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) },
|
||||
label = { Text("VPN ${profile + 1}") }
|
||||
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class QuickToggleTileService : TileService() {
|
||||
@@ -27,8 +28,15 @@ class QuickToggleTileService : TileService() {
|
||||
stateJob?.cancel()
|
||||
stateJob = scope.launch {
|
||||
try {
|
||||
TunnelManager.running.collect { running ->
|
||||
updateTile(running)
|
||||
val settingsStore = SettingsStore(this@QuickToggleTileService)
|
||||
combine(
|
||||
TunnelManager.running,
|
||||
settingsStore.activeProfile,
|
||||
settingsStore.profileNames
|
||||
) { running, activeProfile, profileNames ->
|
||||
Triple(running, activeProfile, profileNames)
|
||||
}.collect { (running, activeProfile, profileNames) ->
|
||||
updateTile(running, activeProfile, profileNames)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("QuickToggleTile", "Error collecting running state", e)
|
||||
@@ -89,14 +97,22 @@ class QuickToggleTileService : TileService() {
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun updateTile(running: Boolean) {
|
||||
private fun updateTile(running: Boolean, activeProfile: Int, profileNames: List<String>) {
|
||||
runCatching {
|
||||
val profile = activeProfile.coerceIn(0, 2)
|
||||
val profileLabel = vpnProfileDisplayName(profile, profileNames)
|
||||
val defaultProfileLabel = vpnProfileDefaultName(profile)
|
||||
val profileIsDefault = profileLabel == defaultProfileLabel
|
||||
qsTile?.apply {
|
||||
label = "WDTT Plus"
|
||||
label = when {
|
||||
!running -> "WDTT Plus"
|
||||
profileIsDefault -> "WDTT Plus $profileLabel"
|
||||
else -> profileLabel
|
||||
}
|
||||
icon = Icon.createWithResource(this@QuickToggleTileService, R.drawable.ic_tile_logo)
|
||||
state = if (running) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
subtitle = if (running) "Подключено" else "Отключено"
|
||||
subtitle = if (running) "" else "Отключено"
|
||||
}
|
||||
updateTile()
|
||||
}
|
||||
|
||||
@@ -124,7 +124,10 @@ data class ServerClientCreateRequest(
|
||||
val days: Int,
|
||||
val label: String,
|
||||
val vkHash: String,
|
||||
val ports: String
|
||||
val ports: String,
|
||||
val password: String? = null,
|
||||
val expiresAt: Long? = null,
|
||||
val deactivated: Boolean = false
|
||||
)
|
||||
|
||||
data class ServerAdminActionResult(
|
||||
@@ -162,10 +165,30 @@ object ServerAdminClient {
|
||||
if (request.label.isNotBlank()) args += listOf("--label", request.label.trim())
|
||||
if (request.vkHash.isNotBlank()) args += listOf("--vk-hash", request.vkHash.trim())
|
||||
if (request.ports.isNotBlank()) args += listOf("--ports", request.ports.trim())
|
||||
request.password?.takeIf { it.isNotBlank() }?.let { args += listOf("--client-password", it) }
|
||||
request.expiresAt?.let { args += listOf("--expires-at", it.coerceAtLeast(0).toString()) }
|
||||
if (request.deactivated) args += "--deactivated"
|
||||
actionFromResponse(callAdmin(ssh, target, args))
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun importClient(
|
||||
target: ServerAdminTarget,
|
||||
payload: ClientTransferPayload,
|
||||
targetPorts: String
|
||||
): ServerAdminActionResult = create(
|
||||
target,
|
||||
ServerClientCreateRequest(
|
||||
days = 0,
|
||||
label = payload.label,
|
||||
vkHash = payload.vkHash,
|
||||
ports = targetPorts,
|
||||
password = payload.password,
|
||||
expiresAt = payload.expiresAt,
|
||||
deactivated = payload.deactivated
|
||||
)
|
||||
)
|
||||
|
||||
suspend fun delete(target: ServerAdminTarget, password: String): ServerAdminActionResult =
|
||||
runPasswordAction(target, "delete", password)
|
||||
|
||||
@@ -208,6 +231,9 @@ object ServerAdminClient {
|
||||
suspend fun setPorts(target: ServerAdminTarget, password: String, ports: String): ServerAdminActionResult =
|
||||
runArgsAction(target, listOf("set-ports", "--password", password, "--ports", ports))
|
||||
|
||||
suspend fun setPassword(target: ServerAdminTarget, password: String, newPassword: String): ServerAdminActionResult =
|
||||
runArgsAction(target, listOf("set-password", "--password", password, "--new-password", newPassword))
|
||||
|
||||
suspend fun updateClient(target: ServerAdminTarget, password: String, label: String, hash: String, ports: String): ServerAdminActionResult =
|
||||
withContext(Dispatchers.IO) {
|
||||
withSession(target) { ssh ->
|
||||
@@ -509,6 +535,8 @@ object ServerAdminClient {
|
||||
"на сервере не найдена база WDTT Plus. Сначала выполните деплой."
|
||||
"admin_socket_unavailable" in lower ->
|
||||
"сервер ещё не поддерживает управление без перезапуска. Переустановите сервер из этой версии WDTT Plus."
|
||||
"неизвестная admin-команда" in lower || "flag provided but not defined" in lower ->
|
||||
"сервер ещё не поддерживает перенос или смену пароля клиента. Выполните установку сервера с сохранением данных из этой версии WDTT Plus."
|
||||
"главный пароль" in lower ->
|
||||
"главный пароль администратора не совпадает с сервером."
|
||||
"no such file" in lower || "not found" in lower && "wdtt-server" in lower ->
|
||||
|
||||
@@ -218,6 +218,7 @@ class SettingsStore(context: Context) {
|
||||
companion object {
|
||||
private val Context.dataStore by preferencesDataStore("settings")
|
||||
private val ACTIVE_PROFILE = intPreferencesKey("active_profile")
|
||||
private val PROFILE_NAME = stringPreferencesKey("profile_name")
|
||||
private val SHOW_SYSTEM_APPS = booleanPreferencesKey("show_system_apps")
|
||||
private val LOGGING_ENABLED = booleanPreferencesKey("logging_enabled")
|
||||
private val WDTT_LINK = stringPreferencesKey("wdtt_link")
|
||||
@@ -297,6 +298,7 @@ class SettingsStore(context: Context) {
|
||||
private val UPDATE_DIALOG_LAST_ACTION = stringPreferencesKey("update_dialog_last_action")
|
||||
private val UPDATE_DIALOG_LAST_ACTION_AT = longPreferencesKey("update_dialog_last_action_at")
|
||||
private val MIGRATION_NOTICE_V2_SHOWN = booleanPreferencesKey("migration_notice_v2_shown")
|
||||
private val MIGRATION_NOTICE_V3_SHOWN = booleanPreferencesKey("migration_notice_v3_shown")
|
||||
private val DEPLOY_CLIENTS_SECTION_EXPANDED = booleanPreferencesKey("deploy_clients_section_expanded")
|
||||
private val DEPLOY_OUTBOUND_SECTION_EXPANDED = booleanPreferencesKey("deploy_outbound_section_expanded")
|
||||
private val DEPLOY_MIGRATION_SECTION_EXPANDED = booleanPreferencesKey("deploy_migration_section_expanded")
|
||||
@@ -311,7 +313,7 @@ class SettingsStore(context: Context) {
|
||||
val newName = "${baseKey.name}_$profile"
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
return when (baseKey) {
|
||||
PEER, VK_HASHES, SECONDARY_VK_HASH, PROTOCOL, SNI, USER_AGENT, DEPLOY_IP, DEPLOY_LOGIN, DEPLOY_PASSWORD, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_SSH_PORT, DEPLOY_DNS1, DEPLOY_DNS2, EXCLUDED_APPS, BLACKLIST_APPS, WHITELIST_APPS, CONNECTION_PASSWORD, CONNECTION_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_ADMIN_ID, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_BOT_TOKEN, DEPLOY_BOT_TOKEN_ENCRYPTED, PROXY_MODE, PROXY_HOST, CAPTCHA_MODE, CAPTCHA_SOLVE_METHOD, CAPTCHA_WBV_SOLVE_METHOD, WDTT_LINK, SELECTED_FINGERPRINT, ACTIVE_CLIENT_IDS -> stringPreferencesKey(newName) as Preferences.Key<T>
|
||||
PROFILE_NAME, PEER, VK_HASHES, SECONDARY_VK_HASH, PROTOCOL, SNI, USER_AGENT, DEPLOY_IP, DEPLOY_LOGIN, DEPLOY_PASSWORD, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_SSH_PORT, DEPLOY_DNS1, DEPLOY_DNS2, EXCLUDED_APPS, BLACKLIST_APPS, WHITELIST_APPS, CONNECTION_PASSWORD, CONNECTION_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_ADMIN_ID, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_BOT_TOKEN, DEPLOY_BOT_TOKEN_ENCRYPTED, PROXY_MODE, PROXY_HOST, CAPTCHA_MODE, CAPTCHA_SOLVE_METHOD, CAPTCHA_WBV_SOLVE_METHOD, WDTT_LINK, SELECTED_FINGERPRINT, ACTIVE_CLIENT_IDS -> stringPreferencesKey(newName) as Preferences.Key<T>
|
||||
WORKERS_PER_HASH, VK_HASH_NEXT_SLOT, LISTEN_PORT, SERVER_DTLS_PORT, SERVER_WG_PORT, PROXY_PORT -> intPreferencesKey(newName) as Preferences.Key<T>
|
||||
MANUAL_PORTS_ENABLED, NO_DTLS, NO_DNS, IS_WHITELIST, WDTT_LINK_MODE, VKCALLS_PREFLIGHT, DETAILED_LOGS -> booleanPreferencesKey(newName) as Preferences.Key<T>
|
||||
else -> throw IllegalArgumentException("Unsupported key type: ${baseKey.name}")
|
||||
@@ -330,6 +332,11 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
|
||||
val activeProfile: Flow<Int> = dataStore.data.map { it[ACTIVE_PROFILE] ?: 0 }
|
||||
val profileNames: Flow<List<String>> = dataStore.data.map { prefs ->
|
||||
(0 until VPN_PROFILE_COUNT).map { profile ->
|
||||
prefs[getProfileKey(PROFILE_NAME, profile)].orEmpty()
|
||||
}
|
||||
}
|
||||
val showSystemApps: Flow<Boolean> = dataStore.data.map { it[SHOW_SYSTEM_APPS] ?: false }
|
||||
val loggingEnabled: Flow<Boolean> = dataStore.data.map { it[LOGGING_ENABLED] ?: true }
|
||||
val wdttLink: Flow<String> = dataStore.data.map { prefs ->
|
||||
@@ -515,6 +522,7 @@ class SettingsStore(context: Context) {
|
||||
val updateDialogLastAction: Flow<String> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION] ?: "" }
|
||||
val updateDialogLastActionAt: Flow<Long> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_AT] ?: 0L }
|
||||
val migrationNoticeV2Shown: Flow<Boolean> = dataStore.data.map { it[MIGRATION_NOTICE_V2_SHOWN] ?: false }
|
||||
val migrationNoticeV3Shown: Flow<Boolean> = dataStore.data.map { it[MIGRATION_NOTICE_V3_SHOWN] ?: false }
|
||||
val deployClientsSectionExpanded: Flow<Boolean> = dataStore.data.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: true }
|
||||
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 }
|
||||
@@ -621,6 +629,12 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveMigrationNoticeV3Shown() {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[MIGRATION_NOTICE_V3_SHOWN] = true
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveDeployClientsSectionExpanded(expanded: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[DEPLOY_CLIENTS_SECTION_EXPANDED] = expanded
|
||||
@@ -645,6 +659,19 @@ class SettingsStore(context: Context) {
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveProfileName(profile: Int, name: String) {
|
||||
dataStore.edit { prefs ->
|
||||
val index = profile.coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
val clean = normalizeVpnProfileName(name)
|
||||
val key = getProfileKey(PROFILE_NAME, index)
|
||||
if (clean.isBlank() || clean == vpnProfileDefaultName(index)) {
|
||||
prefs.remove(key)
|
||||
} else {
|
||||
prefs[key] = clean
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveShowSystemApps(enabled: Boolean) {
|
||||
dataStore.edit { prefs ->
|
||||
prefs[SHOW_SYSTEM_APPS] = enabled
|
||||
@@ -696,8 +723,12 @@ class SettingsStore(context: Context) {
|
||||
)
|
||||
val link = WdttTransferCodec.buildConnectionLink(parts)
|
||||
val validation = WdttDeepLink.validate(link)
|
||||
val profileLabel = vpnProfileDisplayName(
|
||||
profile,
|
||||
(0 until VPN_PROFILE_COUNT).map { index -> prefs[getProfileKey(PROFILE_NAME, index)].orEmpty() }
|
||||
)
|
||||
require(validation.canStartVpn) {
|
||||
"Профиль VPN ${profile + 1} заполнен не полностью. Проверьте адрес, порты, пароль и VK-хеши."
|
||||
"Профиль «$profileLabel» заполнен не полностью. Проверьте адрес, порты, пароль и VK-хеши."
|
||||
}
|
||||
link
|
||||
}.first()
|
||||
@@ -745,6 +776,7 @@ class SettingsStore(context: Context) {
|
||||
put("detailedLogs", prefs[getProfileKey(DETAILED_LOGS, profile)] ?: false)
|
||||
put("selectedFingerprint", prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox")
|
||||
put("activeClientIds", prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] ?: "6287487,8202606")
|
||||
put("profileName", prefs[getProfileKey(PROFILE_NAME, profile)].orEmpty())
|
||||
})
|
||||
}
|
||||
JSONObject().apply {
|
||||
@@ -815,6 +847,13 @@ class SettingsStore(context: Context) {
|
||||
prefs[getProfileKey(DETAILED_LOGS, profile)] = item.optBoolean("detailedLogs")
|
||||
prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] = item.optString("selectedFingerprint", "firefox")
|
||||
prefs[getProfileKey(ACTIVE_CLIENT_IDS, profile)] = item.optString("activeClientIds", "6287487,8202606")
|
||||
val importedName = normalizeVpnProfileName(item.optString("profileName"))
|
||||
val profileNameKey = getProfileKey(PROFILE_NAME, profile)
|
||||
if (importedName.isBlank() || importedName == vpnProfileDefaultName(profile)) {
|
||||
prefs.remove(profileNameKey)
|
||||
} else {
|
||||
prefs[profileNameKey] = importedName
|
||||
}
|
||||
}
|
||||
prefs[ACTIVE_PROFILE] = root.optInt("activeProfile", 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
|
||||
prefs[THEME_MODE] = root.optString("themeMode", "system")
|
||||
@@ -1207,3 +1246,16 @@ class SettingsStore(context: Context) {
|
||||
private fun JSONObject.safePort(name: String, fallback: Int): Int =
|
||||
optInt(name, fallback).takeIf { it in 1..65535 } ?: fallback
|
||||
}
|
||||
|
||||
fun vpnProfileDefaultName(profile: Int): String = "VPN ${profile.coerceIn(0, 2) + 1}"
|
||||
|
||||
fun normalizeVpnProfileName(name: String): String =
|
||||
name
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
.take(48)
|
||||
|
||||
fun vpnProfileDisplayName(profile: Int, names: List<String>): String {
|
||||
val clean = normalizeVpnProfileName(names.getOrNull(profile).orEmpty())
|
||||
return clean.ifBlank { vpnProfileDefaultName(profile) }
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.combine
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@@ -44,8 +45,11 @@ class TunnelService : Service() {
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
private var wifiLock: WifiManager.WifiLock? = null
|
||||
private var updateJob: Job? = null
|
||||
private var profileNameJob: Job? = null
|
||||
private var networkChangeJob: Job? = null
|
||||
private var lastNotificationTitle: String? = null
|
||||
private var lastNotificationText: String? = null
|
||||
private var notificationProfileTitle: String = "WDTT Plus"
|
||||
|
||||
// Network Monitoring
|
||||
private var connectivityManager: ConnectivityManager? = null
|
||||
@@ -153,13 +157,16 @@ class TunnelService : Service() {
|
||||
CaptchaWebViewManager.onTunnelStart(applicationContext)
|
||||
|
||||
TunnelManager.start(this, params)
|
||||
startNotificationProfileWatcher()
|
||||
startStatsUpdater()
|
||||
}
|
||||
|
||||
private fun stopTunnel() {
|
||||
updateJob?.cancel()
|
||||
profileNameJob?.cancel()
|
||||
networkChangeJob?.cancel()
|
||||
wakeRescueJob?.cancel()
|
||||
profileNameJob = null
|
||||
networkChangeJob = null
|
||||
wakeRescueJob = null
|
||||
|
||||
@@ -177,6 +184,26 @@ class TunnelService : Service() {
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private fun startNotificationProfileWatcher() {
|
||||
profileNameJob?.cancel()
|
||||
val settingsStore = SettingsStore(applicationContext)
|
||||
profileNameJob = TunnelManager.scope.launch(Dispatchers.Main) {
|
||||
combine(
|
||||
settingsStore.activeProfile,
|
||||
settingsStore.profileNames
|
||||
) { activeProfile, profileNames ->
|
||||
val profile = activeProfile.coerceIn(0, 2)
|
||||
val profileLabel = vpnProfileDisplayName(profile, profileNames)
|
||||
"WDTT Plus · $profileLabel"
|
||||
}.collect { prefix ->
|
||||
notificationProfileTitle = prefix
|
||||
if (TunnelManager.running.value && !isTunnelPaused) {
|
||||
updateNotification(buildTunnelNotificationText())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun registerScreenStateReceiver() {
|
||||
if (screenStateReceiver != null) return
|
||||
screenStateReceiver = object : BroadcastReceiver() {
|
||||
@@ -647,7 +674,7 @@ class TunnelService : Service() {
|
||||
)
|
||||
|
||||
return NotificationCompat.Builder(this, TUNNEL_NOTIFICATION_CHANNEL_ID)
|
||||
.setContentTitle("WDTT Plus")
|
||||
.setContentTitle(notificationProfileTitle)
|
||||
.setContentText(text)
|
||||
.setSmallIcon(R.drawable.ic_notification_icon)
|
||||
.setOngoing(true)
|
||||
@@ -677,7 +704,9 @@ class TunnelService : Service() {
|
||||
}
|
||||
|
||||
private fun updateNotification(text: String) {
|
||||
if (lastNotificationText == text) return
|
||||
val title = notificationProfileTitle
|
||||
if (lastNotificationTitle == title && lastNotificationText == text) return
|
||||
lastNotificationTitle = title
|
||||
lastNotificationText = text
|
||||
val notification = createNotification(text)
|
||||
getSystemService(NotificationManager::class.java).notify(TUNNEL_NOTIFICATION_ID, notification)
|
||||
|
||||
@@ -57,6 +57,7 @@ import com.wdtt.plus.ServerAdminTarget
|
||||
import com.wdtt.plus.SettingsStore
|
||||
import com.wdtt.plus.TunnelManager
|
||||
import com.wdtt.plus.WDTTColors
|
||||
import com.wdtt.plus.vpnProfileDisplayName
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -265,6 +266,8 @@ fun DeployTab(
|
||||
LaunchedEffect(Unit) { DeployManager.init(context) }
|
||||
|
||||
val savedIp by settingsStore.deployIp.collectAsStateWithLifecycle(initialValue = "")
|
||||
val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0)
|
||||
val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList())
|
||||
val savedLogin by settingsStore.deployLogin.collectAsStateWithLifecycle(initialValue = "")
|
||||
val savedPassword by settingsStore.deployPassword.collectAsStateWithLifecycle(initialValue = "")
|
||||
val savedPeer by settingsStore.peer.collectAsStateWithLifecycle(initialValue = "")
|
||||
@@ -812,11 +815,18 @@ fun DeployTab(
|
||||
.verticalScroll(deployScrollState),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Text(
|
||||
"Настройки сервера",
|
||||
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
"Настройки сервера",
|
||||
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Text(
|
||||
"(${vpnProfileDisplayName(activeProfile, profileNames)})",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
val importCanProvideMainPassword = selectedImportMode == ServerImportMode.Replace &&
|
||||
selectedImportBackup?.mainPassword?.isNotBlank() == true
|
||||
|
||||
@@ -11,9 +11,11 @@ import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.scaleIn
|
||||
import androidx.compose.animation.scaleOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.foundation.ExperimentalFoundationApi
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.combinedClickable
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
@@ -35,8 +37,11 @@ import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.wdtt.plus.SettingsStore
|
||||
import com.wdtt.plus.normalizeVpnProfileName
|
||||
import com.wdtt.plus.vpnProfileDisplayName
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
@@ -52,11 +57,13 @@ import androidx.compose.material.icons.filled.Share
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
|
||||
@Composable
|
||||
fun FloatingToolbar(
|
||||
activeProfile: Int,
|
||||
profileNames: List<String>,
|
||||
onActiveProfileChange: (Int) -> Unit,
|
||||
onProfileNameChange: (Int, String) -> Unit,
|
||||
interfaceRole: String,
|
||||
onInterfaceRoleChange: (String) -> Unit,
|
||||
currentTheme: String,
|
||||
@@ -89,6 +96,8 @@ fun FloatingToolbar(
|
||||
var isExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var tabHeightPx by remember { mutableFloatStateOf(0f) }
|
||||
var panelHeightPx by remember { mutableFloatStateOf(0f) }
|
||||
var renamingProfile by remember { mutableStateOf<Int?>(null) }
|
||||
var profileNameInput by rememberSaveable { mutableStateOf("") }
|
||||
|
||||
val tabWidthDp = 42.dp
|
||||
val tabHeightDp = 52.dp
|
||||
@@ -219,20 +228,29 @@ fun FloatingToolbar(
|
||||
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
listOf(0, 1, 2).forEach { profile ->
|
||||
val selected = profile == activeProfile
|
||||
val profileLabel = "VPN ${profile + 1}"
|
||||
val profileLabel = vpnProfileDisplayName(profile, profileNames)
|
||||
val profileShape = RoundedCornerShape(12.dp)
|
||||
Surface(
|
||||
onClick = { onActiveProfileChange(profile) },
|
||||
shape = RoundedCornerShape(12.dp),
|
||||
shape = profileShape,
|
||||
color = if (selected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
|
||||
modifier = Modifier.weight(1f).widthIn(min = 62.dp)
|
||||
modifier = Modifier
|
||||
.widthIn(min = 72.dp, max = 180.dp)
|
||||
.clip(profileShape)
|
||||
.combinedClickable(
|
||||
onClick = { onActiveProfileChange(profile) },
|
||||
onLongClick = {
|
||||
renamingProfile = profile
|
||||
profileNameInput = profileLabel
|
||||
}
|
||||
)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.padding(vertical = 8.dp),
|
||||
modifier = Modifier.padding(horizontal = 6.dp, vertical = 8.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Text(
|
||||
@@ -240,7 +258,8 @@ fun FloatingToolbar(
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
|
||||
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
|
||||
fontSize = 12.sp
|
||||
fontSize = 12.sp,
|
||||
textAlign = TextAlign.Center
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -532,6 +551,43 @@ fun FloatingToolbar(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
renamingProfile?.let { profile ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { renamingProfile = null },
|
||||
title = {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text("Название профиля")
|
||||
IconButton(onClick = { renamingProfile = null }) {
|
||||
Icon(Icons.Filled.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
},
|
||||
text = {
|
||||
OutlinedTextField(
|
||||
value = profileNameInput,
|
||||
onValueChange = { profileNameInput = normalizeVpnProfileName(it) },
|
||||
label = { Text("Название") },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
onClick = {
|
||||
onProfileNameChange(profile, profileNameInput)
|
||||
renamingProfile = null
|
||||
}
|
||||
) {
|
||||
Text("Сохранить")
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
|
||||
import androidx.compose.material.icons.filled.Add
|
||||
import androidx.compose.material.icons.filled.CameraAlt
|
||||
import androidx.compose.material.icons.filled.CheckCircle
|
||||
import androidx.compose.material.icons.filled.ChevronLeft
|
||||
import androidx.compose.material.icons.filled.ChevronRight
|
||||
@@ -57,6 +58,9 @@ import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.ExpandLess
|
||||
import androidx.compose.material.icons.filled.ExpandMore
|
||||
import androidx.compose.material.icons.filled.FilterList
|
||||
import androidx.compose.material.icons.filled.FileOpen
|
||||
import androidx.compose.material.icons.filled.Image
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material.icons.filled.Link
|
||||
import androidx.compose.material.icons.filled.LockOpen
|
||||
import androidx.compose.material.icons.filled.PauseCircle
|
||||
@@ -106,6 +110,14 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.viewmodel.compose.viewModel
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.journeyapps.barcodescanner.ScanContract
|
||||
import com.journeyapps.barcodescanner.ScanOptions
|
||||
import com.wdtt.plus.ClientPasswordRules
|
||||
import com.wdtt.plus.ClientTransferCodec
|
||||
import com.wdtt.plus.ClientTransferInbox
|
||||
import com.wdtt.plus.ClientTransferPayload
|
||||
import com.wdtt.plus.QrCaptureActivity
|
||||
import com.wdtt.plus.ServerAdminActionResult
|
||||
import com.wdtt.plus.ServerAdminClient
|
||||
import com.wdtt.plus.ServerAdminProfileInfo
|
||||
@@ -129,6 +141,7 @@ private enum class ClientWizardStep {
|
||||
Label,
|
||||
Hash,
|
||||
Ports,
|
||||
Password,
|
||||
Confirm
|
||||
}
|
||||
|
||||
@@ -178,12 +191,18 @@ fun ServerClientsSection(
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var status by rememberSaveable { mutableStateOf("") }
|
||||
var showCreateWizard by rememberSaveable { mutableStateOf(false) }
|
||||
var showImportMethods by rememberSaveable { mutableStateOf(false) }
|
||||
var pendingImport by remember { mutableStateOf<ClientTransferPayload?>(null) }
|
||||
var exportClient by remember { mutableStateOf<ServerClientInfo?>(null) }
|
||||
var passwordClient by remember { mutableStateOf<ServerClientInfo?>(null) }
|
||||
var changedPasswordClient by remember { mutableStateOf<ServerClientInfo?>(null) }
|
||||
var pendingAction by remember { mutableStateOf<PendingClientAction?>(null) }
|
||||
var expiryClient by remember { mutableStateOf<ServerClientInfo?>(null) }
|
||||
var qrData by remember { mutableStateOf<Pair<String, Bitmap>?>(null) }
|
||||
var detailsClient by remember { mutableStateOf<ServerClientInfo?>(null) }
|
||||
var showServerTools by rememberSaveable { mutableStateOf(false) }
|
||||
var createdClient by remember { mutableStateOf<ServerClientInfo?>(null) }
|
||||
var importedClient by remember { mutableStateOf<ServerClientInfo?>(null) }
|
||||
var filtersExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var statusFilter by rememberSaveable { mutableStateOf(ClientStatusFilter.All) }
|
||||
var bindingFilter by rememberSaveable { mutableStateOf(ClientBindingFilter.All) }
|
||||
@@ -192,6 +211,7 @@ fun ServerClientsSection(
|
||||
var clientSearchFocused by remember { mutableStateOf(false) }
|
||||
var clientSearch by clientsViewModel.clientSearch
|
||||
var selectedClientIndex by clientsViewModel.selectedClientIndex
|
||||
val inboxTransfer by ClientTransferInbox.pending.collectAsStateWithLifecycle()
|
||||
val arrowRotation by animateFloatAsState(
|
||||
targetValue = if (expanded) 180f else 0f,
|
||||
label = "server_clients_arrow_rotation"
|
||||
@@ -229,6 +249,40 @@ fun ServerClientsSection(
|
||||
mainPassword = mainPassword
|
||||
)
|
||||
|
||||
fun acceptClientTransfer(raw: String) {
|
||||
runCatching { ClientTransferCodec.decode(raw) }
|
||||
.onSuccess {
|
||||
pendingImport = it
|
||||
showImportMethods = false
|
||||
}
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "данные клиента не распознаны"}" }
|
||||
}
|
||||
|
||||
val importCameraLauncher = rememberLauncherForActivityResult(ScanContract()) { result ->
|
||||
result.contents?.takeIf { it.isNotBlank() }?.let(::acceptClientTransfer)
|
||||
}
|
||||
val importGalleryLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||
if (uri != null) scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { TransferFiles.decodeQrImage(context, uri) } }
|
||||
.onSuccess(::acceptClientTransfer)
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не прочитан"}" }
|
||||
}
|
||||
}
|
||||
val importFileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
|
||||
if (uri != null) scope.launch {
|
||||
runCatching { withContext(Dispatchers.IO) { TransferFiles.readText(context, uri) } }
|
||||
.onSuccess(::acceptClientTransfer)
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "файл клиента не прочитан"}" }
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(inboxTransfer) {
|
||||
inboxTransfer?.let { raw ->
|
||||
acceptClientTransfer(raw)
|
||||
ClientTransferInbox.clear(raw)
|
||||
}
|
||||
}
|
||||
|
||||
fun refreshClients() {
|
||||
if (!targetReady || busy) return
|
||||
busy = true
|
||||
@@ -355,12 +409,15 @@ fun ServerClientsSection(
|
||||
Icon(Icons.Default.Add, null, Modifier.size(18.dp))
|
||||
Text(" Создать")
|
||||
}
|
||||
OutlinedButton(onClick = { showImportMethods = true }, enabled = canUse && state != null) {
|
||||
Text("Импорт")
|
||||
}
|
||||
OutlinedButton(onClick = { showServerTools = true }, enabled = canUse && state != null) {
|
||||
Text("Сервер")
|
||||
}
|
||||
}
|
||||
|
||||
if (status.isNotBlank() && state == null) {
|
||||
if (status.isNotBlank()) {
|
||||
ClientStatusBanner(status = status, busy = busy)
|
||||
}
|
||||
|
||||
@@ -507,6 +564,7 @@ fun ServerClientsSection(
|
||||
}
|
||||
},
|
||||
onExtend = { expiryClient = selectedClient },
|
||||
onExport = { exportClient = selectedClient },
|
||||
onDetails = {
|
||||
busy = true
|
||||
status = "Читаю данные клиента..."
|
||||
@@ -529,6 +587,7 @@ fun ServerClientsSection(
|
||||
run = { ServerAdminClient.unbind(target, selectedClient.password) }
|
||||
)
|
||||
},
|
||||
onChangePassword = { passwordClient = selectedClient },
|
||||
onToggle = {
|
||||
pendingAction = if (selectedClient.status == "deactivated") {
|
||||
PendingClientAction(
|
||||
@@ -559,9 +618,6 @@ fun ServerClientsSection(
|
||||
}
|
||||
)
|
||||
}
|
||||
if (status.isNotBlank()) {
|
||||
ClientStatusBanner(status = status, busy = busy)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -593,6 +649,8 @@ fun ServerClientsSection(
|
||||
if (showCreateWizard) {
|
||||
CreateClientWizardDialog(
|
||||
defaultPorts = state?.defaultPorts ?: defaultPorts.ifBlank { "56000,56001,9000" },
|
||||
existingPasswords = state?.clients?.map { it.password }.orEmpty().toSet(),
|
||||
mainPassword = mainPassword,
|
||||
busy = busy,
|
||||
onDismiss = { if (!busy) showCreateWizard = false },
|
||||
onCreate = { request ->
|
||||
@@ -616,6 +674,142 @@ fun ServerClientsSection(
|
||||
)
|
||||
}
|
||||
|
||||
if (showImportMethods) {
|
||||
ClientImportMethodsDialog(
|
||||
onDismiss = { showImportMethods = false },
|
||||
onCamera = {
|
||||
importCameraLauncher.launch(
|
||||
ScanOptions()
|
||||
.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||
.setPrompt("Наведите камеру на QR переноса клиента")
|
||||
.setBeepEnabled(false)
|
||||
.setCaptureActivity(QrCaptureActivity::class.java)
|
||||
.setOrientationLocked(false)
|
||||
)
|
||||
},
|
||||
onGallery = { importGalleryLauncher.launch("image/*") },
|
||||
onFile = { importFileLauncher.launch("*/*") },
|
||||
onPaste = {
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
val value = clipboard.primaryClip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(context)?.toString()
|
||||
if (value.isNullOrBlank()) status = "Ошибка: в буфере обмена нет данных клиента"
|
||||
else acceptClientTransfer(value)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
pendingImport?.let { payload ->
|
||||
val current = state
|
||||
ClientImportConfirmDialog(
|
||||
payload = payload,
|
||||
targetHost = current?.let { it.publicHost.ifBlank { it.effectivePublicHost.ifBlank { host } } }.orEmpty(),
|
||||
targetPorts = current?.defaultPorts ?: defaultPorts,
|
||||
passwordConflict = current?.clients?.any { it.password == payload.password } == true,
|
||||
mainPasswordConflict = payload.password == mainPassword,
|
||||
limitReached = current != null && current.passwordCount >= current.maxPasswords && current.expiredCount == 0,
|
||||
onDismiss = { pendingImport = null },
|
||||
onConfirm = {
|
||||
pendingImport = null
|
||||
busy = true
|
||||
status = "Импорт: отправляю данные клиента на сервер..."
|
||||
scope.launch {
|
||||
try {
|
||||
val result = ServerAdminClient.importClient(
|
||||
target,
|
||||
payload,
|
||||
current?.defaultPorts ?: defaultPorts.ifBlank { "56000,56001,9000" }
|
||||
)
|
||||
status = "Импорт: клиент записан, проверяю список на сервере..."
|
||||
val refreshed = ServerAdminClient.list(target)
|
||||
val imported = refreshed.clients.firstOrNull { it.password == payload.password }
|
||||
?: result.createdClient?.takeIf { created -> created.password == payload.password }
|
||||
?: throw IllegalStateException("сервер принял импорт, но клиент не найден в свежем списке. Нажмите «Обновить» и проверьте, не достигнут ли лимит клиентов.")
|
||||
state = refreshed
|
||||
clientSearch = ""
|
||||
statusFilter = ClientStatusFilter.All
|
||||
bindingFilter = ClientBindingFilter.All
|
||||
expiryFilter = ClientExpiryFilter.All
|
||||
vkHashFilter = ClientVkHashFilter.All
|
||||
selectedClientIndex = refreshed.clients.indexOfFirst { it.password == payload.password }
|
||||
.coerceAtLeast(0)
|
||||
importedClient = imported
|
||||
status = "Клиент импортирован и найден в списке без перезапуска сервера."
|
||||
} catch (error: Throwable) {
|
||||
status = "Ошибка: ${error.message ?: "клиент не импортирован"}"
|
||||
}
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
exportClient?.let { client ->
|
||||
val transferResult = remember(client) { runCatching { ClientTransferCodec.encode(ClientTransferCodec.fromClient(client)) } }
|
||||
val transfer = transferResult.getOrNull()
|
||||
if (transfer == null) {
|
||||
AlertDialog(
|
||||
onDismissRequest = { exportClient = null },
|
||||
title = { DialogTitle("Экспорт невозможен", { exportClient = null }) },
|
||||
text = {
|
||||
Text(
|
||||
transferResult.exceptionOrNull()?.message ?: "Проверьте пароль и VK-хеши клиента.",
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
},
|
||||
confirmButton = { Button(onClick = { exportClient = null }) { Text("Хорошо") } }
|
||||
)
|
||||
} else {
|
||||
ClientTransferExportDialog(
|
||||
client = client,
|
||||
onDismiss = { exportClient = null },
|
||||
onCopy = { copyText(context, "Перенос клиента WDTT Plus", transfer) },
|
||||
onShare = { shareText(context, transfer, "Передать клиента WDTT Plus") },
|
||||
onQr = {
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, transfer) } }
|
||||
.onSuccess { qrData = "Перенос: ${client.displayName()}" to it }
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
|
||||
}
|
||||
},
|
||||
onFile = {
|
||||
scope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) {
|
||||
TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt-client", transfer)
|
||||
}
|
||||
}.onSuccess {
|
||||
shareUri(context, it, "application/vnd.wdtt.plus.client", "Передать клиента WDTT Plus")
|
||||
}.onFailure { status = "Ошибка: ${it.message ?: "файл клиента не создан"}" }
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
passwordClient?.let { client ->
|
||||
ChangeClientPasswordDialog(
|
||||
client = client,
|
||||
existingPasswords = state?.clients?.map { it.password }.orEmpty().toSet(),
|
||||
mainPassword = mainPassword,
|
||||
onDismiss = { passwordClient = null },
|
||||
onConfirm = { newPassword ->
|
||||
passwordClient = null
|
||||
busy = true
|
||||
status = "Изменяю пароль клиента..."
|
||||
scope.launch {
|
||||
runCatching { ServerAdminClient.setPassword(target, client.password, newPassword) }
|
||||
.onSuccess { result ->
|
||||
status = result.message
|
||||
changedPasswordClient = result.createdClient
|
||||
runCatching { ServerAdminClient.list(target) }.onSuccess { state = it }
|
||||
}
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "пароль не изменён"}" }
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
pendingAction?.let { action ->
|
||||
ConfirmClientActionDialog(
|
||||
action = action,
|
||||
@@ -654,7 +848,6 @@ fun ServerClientsSection(
|
||||
onShare = { link?.let { shareText(context, it) } },
|
||||
onQr = {
|
||||
link?.let { value ->
|
||||
createdClient = null
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
|
||||
.onSuccess { qrData = client.displayName() to it }
|
||||
@@ -675,6 +868,73 @@ fun ServerClientsSection(
|
||||
)
|
||||
}
|
||||
|
||||
importedClient?.let { client ->
|
||||
val link = client.connectionLink(host, state?.publicHost?.ifBlank { state?.effectivePublicHost.orEmpty() }.orEmpty())
|
||||
AccessResultDialog(
|
||||
title = "Импорт готов",
|
||||
statusText = "Клиент импортирован и найден в списке.",
|
||||
password = client.password,
|
||||
link = link,
|
||||
noLinkText = "VK-хеш не задан. Клиент добавлен; хеш можно указать в «Подробнее».",
|
||||
onDismiss = { importedClient = null },
|
||||
onCopyPassword = { copyText(context, "Пароль импортированного клиента", client.password) },
|
||||
onCopyLink = { link?.let { copyText(context, "Ссылка WDTT", it) } },
|
||||
onShare = { link?.let { shareText(context, it) } },
|
||||
onQr = {
|
||||
link?.let { value ->
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
|
||||
.onSuccess { qrData = client.displayName() to it }
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
|
||||
}
|
||||
}
|
||||
},
|
||||
onFile = {
|
||||
link?.let { value ->
|
||||
scope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) }
|
||||
}.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus") }
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
changedPasswordClient?.let { client ->
|
||||
val link = client.connectionLink(host, state?.publicHost?.ifBlank { state?.effectivePublicHost.orEmpty() }.orEmpty())
|
||||
AccessResultDialog(
|
||||
title = "Пароль изменён",
|
||||
password = client.password,
|
||||
link = link,
|
||||
noLinkText = "VK-хеш не задан. Новый пароль уже работает; добавьте хеш в «Подробнее», чтобы сформировать ссылку.",
|
||||
onDismiss = { changedPasswordClient = null },
|
||||
onCopyPassword = { copyText(context, "Новый пароль WDTT", client.password) },
|
||||
onCopyLink = { link?.let { copyText(context, "Новая ссылка WDTT", it) } },
|
||||
onShare = { link?.let { shareText(context, it) } },
|
||||
onQr = {
|
||||
link?.let { value ->
|
||||
scope.launch {
|
||||
runCatching { withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, value) } }
|
||||
.onSuccess { qrData = client.displayName() to it }
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "QR-код не создан"}" }
|
||||
}
|
||||
}
|
||||
},
|
||||
onFile = {
|
||||
link?.let { value ->
|
||||
scope.launch {
|
||||
runCatching {
|
||||
withContext(Dispatchers.IO) { TransferFiles.writeTransferText(context, "WDTT-Plus-${client.safeFileName()}.wdtt", value) }
|
||||
}.onSuccess { shareUri(context, it, "application/vnd.wdtt.plus.transfer", "Передать новое подключение WDTT Plus") }
|
||||
.onFailure { status = "Ошибка: ${it.message ?: "файл не создан"}" }
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
detailsClient?.let { client ->
|
||||
ClientDetailsDialog(
|
||||
client = client,
|
||||
@@ -991,8 +1251,10 @@ private fun ServerClientActions(
|
||||
onFile: (String) -> Unit,
|
||||
onQr: (String) -> Unit,
|
||||
onExtend: () -> Unit,
|
||||
onExport: () -> Unit,
|
||||
onDetails: () -> Unit,
|
||||
onUnbind: () -> Unit,
|
||||
onChangePassword: () -> Unit,
|
||||
onToggle: () -> Unit,
|
||||
onDelete: () -> Unit
|
||||
) {
|
||||
@@ -1031,6 +1293,7 @@ private fun ServerClientActions(
|
||||
) {
|
||||
OutlinedButton(onClick = onExtend, enabled = !busy) { Text("Продлить") }
|
||||
OutlinedButton(onClick = onDetails, enabled = !busy) { Text("Подробнее") }
|
||||
OutlinedButton(onClick = onExport, enabled = !busy) { Text("Экспорт") }
|
||||
}
|
||||
|
||||
ClientActionCategoryBlock(
|
||||
@@ -1041,6 +1304,10 @@ private fun ServerClientActions(
|
||||
category = ClientActionCategory.Access.takeUnless { category == it }
|
||||
}
|
||||
) {
|
||||
OutlinedButton(onClick = onChangePassword, enabled = !busy) {
|
||||
Icon(Icons.Default.Key, null, Modifier.size(16.dp))
|
||||
Text(" Сменить пароль")
|
||||
}
|
||||
OutlinedButton(onClick = onUnbind, enabled = !busy && client.isBound) {
|
||||
Icon(Icons.Default.Smartphone, null, Modifier.size(16.dp))
|
||||
Text(" Отвязать")
|
||||
@@ -1124,6 +1391,7 @@ private fun ClientActionCategoryBlock(
|
||||
@Composable
|
||||
private fun AccessResultDialog(
|
||||
title: String,
|
||||
statusText: String? = null,
|
||||
password: String,
|
||||
link: String?,
|
||||
noLinkText: String,
|
||||
@@ -1139,6 +1407,14 @@ private fun AccessResultDialog(
|
||||
title = { DialogTitle(title, onDismiss) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
statusText?.let {
|
||||
Text(
|
||||
it,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
Card(
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f))
|
||||
@@ -1741,10 +2017,231 @@ private fun DialogTitle(
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun ClientImportMethodsDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onCamera: () -> Unit,
|
||||
onGallery: () -> Unit,
|
||||
onFile: () -> Unit,
|
||||
onPaste: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Импорт клиента", onDismiss) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("Выберите данные переноса клиента. Обычная ссылка подключения сюда не импортируется.")
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
OutlinedButton(onClick = onCamera) {
|
||||
Icon(Icons.Default.CameraAlt, null, Modifier.size(18.dp))
|
||||
Text(" Камера")
|
||||
}
|
||||
OutlinedButton(onClick = onGallery) {
|
||||
Icon(Icons.Default.Image, null, Modifier.size(18.dp))
|
||||
Text(" Галерея")
|
||||
}
|
||||
OutlinedButton(onClick = onFile) {
|
||||
Icon(Icons.Default.FileOpen, null, Modifier.size(18.dp))
|
||||
Text(" Файл")
|
||||
}
|
||||
OutlinedButton(onClick = onPaste) { Text("Вставить") }
|
||||
}
|
||||
Text(
|
||||
"Файл, изображение или код содержит пароль клиента. После чтения приложение покажет проверку перед записью на сервер.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {}
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun ClientTransferExportDialog(
|
||||
client: ServerClientInfo,
|
||||
onDismiss: () -> Unit,
|
||||
onCopy: () -> Unit,
|
||||
onShare: () -> Unit,
|
||||
onQr: () -> Unit,
|
||||
onFile: () -> Unit
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Экспорт клиента", onDismiss) },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
Text("Клиент: ${client.displayName()}", fontWeight = FontWeight.Bold)
|
||||
Text("Переносятся пароль, название, VK-хеши, срок и состояние доступа.")
|
||||
Text(
|
||||
"Не переносятся устройство, WireGuard-ключи, адрес, порты, трафик и история. На новом сервере используются его настройки, а устройство привяжется при первом подключении.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
OutlinedButton(onClick = onQr) {
|
||||
Icon(Icons.Default.QrCode2, null, Modifier.size(18.dp))
|
||||
Text(" QR")
|
||||
}
|
||||
OutlinedButton(onClick = onFile) {
|
||||
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, null, Modifier.size(18.dp))
|
||||
Text(" Файл")
|
||||
}
|
||||
OutlinedButton(onClick = onShare) {
|
||||
Icon(Icons.Default.Share, null, Modifier.size(18.dp))
|
||||
Text(" Поделиться")
|
||||
}
|
||||
OutlinedButton(onClick = onCopy) { Text("Копировать") }
|
||||
}
|
||||
Text(
|
||||
"Передача содержит рабочий пароль клиента. Отправляйте её только себе или доверенному администратору.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
}
|
||||
},
|
||||
confirmButton = {}
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ClientImportConfirmDialog(
|
||||
payload: ClientTransferPayload,
|
||||
targetHost: String,
|
||||
targetPorts: String,
|
||||
passwordConflict: Boolean,
|
||||
mainPasswordConflict: Boolean,
|
||||
limitReached: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit
|
||||
) {
|
||||
val expired = payload.expiresAt > 0 && payload.expiresAt <= System.currentTimeMillis() / 1000L
|
||||
val errors = buildList {
|
||||
if (passwordConflict) add("На новом сервере уже есть клиент с таким паролем.")
|
||||
if (mainPasswordConflict) add("Пароль клиента совпадает с главным паролем нового сервера.")
|
||||
if (expired) add("Срок этого клиента уже истёк.")
|
||||
if (limitReached) add("На новом сервере достигнут лимит клиентов.")
|
||||
if (targetHost.isBlank()) add("Не определён адрес нового сервера.")
|
||||
if (!targetPorts.isPortsSpec()) add("На новом сервере указаны некорректные порты.")
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Проверка импорта", onDismiss) },
|
||||
text = {
|
||||
Column(
|
||||
modifier = Modifier.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
InfoLine("Клиент", payload.label.ifBlank { "Без имени" })
|
||||
InfoLine("Пароль", "${payload.password.take(3)}••••${payload.password.takeLast(3)}")
|
||||
InfoLine("Срок", formatExpiry(payload.expiresAt))
|
||||
InfoLine("Состояние", if (payload.deactivated) "Отключён" else "Активен")
|
||||
InfoLine("VK-хеши", if (payload.vkHash.isBlank()) "не заданы" else "заданы")
|
||||
HorizontalDivider()
|
||||
InfoLine("Новый сервер", targetHost.ifBlank { "не определён" })
|
||||
InfoLine("Порты нового сервера", targetPorts.ifBlank { "не заданы" })
|
||||
Text(
|
||||
"Клиент будет скопирован без устройства, ключей, статистики и истории. Старый сервер не изменится. Импорт применяется наживую без перезапуска.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
errors.forEach { Text("• $it", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||
}
|
||||
},
|
||||
confirmButton = { Button(onClick = onConfirm, enabled = errors.isEmpty()) { Text("Импортировать") } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Отмена") } }
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun ChangeClientPasswordDialog(
|
||||
client: ServerClientInfo,
|
||||
existingPasswords: Set<String>,
|
||||
mainPassword: String,
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: (String) -> Unit
|
||||
) {
|
||||
var automatic by rememberSaveable(client.password) { mutableStateOf(true) }
|
||||
var generated by remember(client.password) { mutableStateOf(ClientPasswordRules.generate()) }
|
||||
var manual by rememberSaveable(client.password) { mutableStateOf("") }
|
||||
val value = if (automatic) generated else manual.trim()
|
||||
val error = when {
|
||||
ClientPasswordRules.validate(value) != null -> ClientPasswordRules.validate(value)
|
||||
value == client.password -> "Новый пароль совпадает с текущим."
|
||||
value == mainPassword -> "Пароль клиента не должен совпадать с главным паролем."
|
||||
value in existingPasswords -> "Клиент с таким паролем уже существует."
|
||||
else -> null
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { DialogTitle("Сменить пароль", onDismiss) },
|
||||
text = {
|
||||
Column(
|
||||
modifier = Modifier.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Text("Клиент: ${client.displayName()}", fontWeight = FontWeight.Bold)
|
||||
InfoLine("Текущий пароль", client.maskedPassword().removePrefix("Пароль: "))
|
||||
val deviceLabel = listOf(
|
||||
client.deviceName,
|
||||
client.device?.name.orEmpty(),
|
||||
client.device?.model.orEmpty(),
|
||||
client.deviceId
|
||||
).firstOrNull { it.isNotBlank() }
|
||||
InfoLine("Устройство", deviceLabel ?: "не привязано")
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
SelectButton("Автоматически", automatic) { automatic = true }
|
||||
SelectButton("Вручную", !automatic) { automatic = false }
|
||||
}
|
||||
if (automatic) {
|
||||
OutlinedTextField(value = generated, onValueChange = {}, readOnly = true, label = { Text("Новый пароль") }, modifier = Modifier.fillMaxWidth())
|
||||
error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) }
|
||||
OutlinedButton(onClick = { generated = ClientPasswordRules.generate() }) { Text("Другой пароль") }
|
||||
} else {
|
||||
OutlinedTextField(
|
||||
value = manual,
|
||||
onValueChange = { manual = it.trim().take(32) },
|
||||
label = { Text("Новый пароль, 16 символов") },
|
||||
supportingText = { error?.let { Text(it) } },
|
||||
isError = error != null,
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
}
|
||||
Text(
|
||||
"Старые ссылки перестанут работать, активное соединение этого клиента завершится. Название, срок, VK-хеши и привязка устройства сохранятся; остальные клиенты не затрагиваются.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
Text("Изменение применяется наживую без перезапуска сервера.", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
},
|
||||
confirmButton = { Button(onClick = { onConfirm(value) }, enabled = error == null) { Text("Изменить") } },
|
||||
dismissButton = { TextButton(onClick = onDismiss) { Text("Отмена") } }
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun CreateClientWizardDialog(
|
||||
defaultPorts: String,
|
||||
existingPasswords: Set<String>,
|
||||
mainPassword: String,
|
||||
busy: Boolean,
|
||||
onDismiss: () -> Unit,
|
||||
onCreate: (ServerClientCreateRequest) -> Unit
|
||||
@@ -1755,8 +2252,17 @@ private fun CreateClientWizardDialog(
|
||||
var vkHash by rememberSaveable { mutableStateOf("") }
|
||||
var useDefaultPorts by rememberSaveable { mutableStateOf(true) }
|
||||
var customPorts by rememberSaveable { mutableStateOf(defaultPorts) }
|
||||
var useAutoPassword by rememberSaveable { mutableStateOf(true) }
|
||||
var customPassword by rememberSaveable { mutableStateOf("") }
|
||||
val effectivePorts = if (useDefaultPorts) defaultPorts else customPorts
|
||||
val portsValid = effectivePorts.isPortsSpec()
|
||||
val passwordError = if (useAutoPassword || customPassword.isEmpty()) null else when {
|
||||
ClientPasswordRules.validate(customPassword) != null -> ClientPasswordRules.validate(customPassword)
|
||||
customPassword == mainPassword -> "Пароль клиента не должен совпадать с главным паролем."
|
||||
customPassword in existingPasswords -> "Клиент с таким паролем уже существует."
|
||||
else -> null
|
||||
}
|
||||
val passwordValid = useAutoPassword || (customPassword.isNotEmpty() && passwordError == null)
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
@@ -1845,12 +2351,44 @@ private fun CreateClientWizardDialog(
|
||||
)
|
||||
if (!portsValid) Text("Формат: 56000,56001,9000", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
ClientWizardStep.Password -> {
|
||||
Text("Пароль клиента", fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Автоматический пароль безопаснее. Ручной режим нужен, например, для переноса существующего клиента с другого сервера.",
|
||||
style = MaterialTheme.typography.bodySmall
|
||||
)
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
SelectButton("Автоматически", useAutoPassword) { useAutoPassword = true }
|
||||
SelectButton("Вручную", !useAutoPassword) { useAutoPassword = false }
|
||||
}
|
||||
if (!useAutoPassword) {
|
||||
OutlinedTextField(
|
||||
value = customPassword,
|
||||
onValueChange = { customPassword = it.trim().take(32) },
|
||||
label = { Text("16 символов") },
|
||||
supportingText = {
|
||||
Text(passwordError ?: "Допустимы безопасные латинские буквы и цифры.")
|
||||
},
|
||||
isError = customPassword.isNotEmpty() && passwordError != null,
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
)
|
||||
OutlinedButton(onClick = { customPassword = ClientPasswordRules.generate() }) {
|
||||
Text("Сгенерировать")
|
||||
}
|
||||
}
|
||||
}
|
||||
ClientWizardStep.Confirm -> {
|
||||
Text("Проверка", fontWeight = FontWeight.Bold)
|
||||
Text("Срок: ${if (days == 0) "бессрочно" else "$days дн."}")
|
||||
Text("Название: ${label.ifBlank { "без имени" }}")
|
||||
Text("VK-хеш: ${if (vkHash.isBlank()) "не задан" else "задан"}")
|
||||
Text("Порты: $effectivePorts")
|
||||
Text("Пароль: ${if (useAutoPassword) "будет создан автоматически" else customPassword}")
|
||||
Text(
|
||||
"Новый доступ начнёт работать сразу, текущие подключения не прервутся.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -1864,7 +2402,9 @@ private fun CreateClientWizardDialog(
|
||||
},
|
||||
confirmButton = {
|
||||
Button(
|
||||
enabled = !busy && (step != ClientWizardStep.Ports || portsValid),
|
||||
enabled = !busy &&
|
||||
(step != ClientWizardStep.Ports || portsValid) &&
|
||||
(step != ClientWizardStep.Password || passwordValid),
|
||||
onClick = {
|
||||
if (step == ClientWizardStep.Confirm) {
|
||||
onCreate(
|
||||
@@ -1872,7 +2412,8 @@ private fun CreateClientWizardDialog(
|
||||
days = days.coerceIn(0, 365),
|
||||
label = label,
|
||||
vkHash = vkHash,
|
||||
ports = effectivePorts
|
||||
ports = effectivePorts,
|
||||
password = customPassword.takeUnless { useAutoPassword }
|
||||
)
|
||||
)
|
||||
} else {
|
||||
@@ -2256,12 +2797,12 @@ private fun String.isPortsSpec(): Boolean {
|
||||
return parts.size == 3 && parts.all { it != null && it in 1..65535 }
|
||||
}
|
||||
|
||||
private fun shareText(context: Context, text: String) {
|
||||
private fun shareText(context: Context, text: String, title: String = "Передать подключение WDTT Plus") {
|
||||
val intent = Intent(Intent.ACTION_SEND).apply {
|
||||
type = "text/plain"
|
||||
putExtra(Intent.EXTRA_TEXT, text)
|
||||
}
|
||||
context.startActivity(Intent.createChooser(intent, "Передать подключение WDTT Plus"))
|
||||
context.startActivity(Intent.createChooser(intent, title))
|
||||
}
|
||||
|
||||
private fun copyText(context: Context, label: String, text: String) {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import androidx.compose.animation.animateContentSize
|
||||
import androidx.compose.animation.core.Spring
|
||||
import androidx.compose.animation.core.spring
|
||||
@@ -19,6 +21,7 @@ import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.HelpOutline
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material.icons.filled.PowerSettingsNew
|
||||
import androidx.compose.material.icons.filled.Stop
|
||||
@@ -54,6 +57,7 @@ import com.wdtt.plus.TunnelService
|
||||
import com.wdtt.plus.VkJoinLink
|
||||
import com.wdtt.plus.WDTTColors
|
||||
import com.wdtt.plus.WdttDeepLink
|
||||
import com.wdtt.plus.vpnProfileDisplayName
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
@@ -120,6 +124,7 @@ fun SettingsTabContent(
|
||||
val savedListenPort by settingsStore.listenPort.collectAsStateWithLifecycle(initialValue = 9000)
|
||||
|
||||
val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0)
|
||||
val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList())
|
||||
val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false)
|
||||
val wdttLink by settingsStore.wdttLink.collectAsStateWithLifecycle(initialValue = "")
|
||||
val savedVkHashes by settingsStore.vkHashes.collectAsStateWithLifecycle(initialValue = "")
|
||||
@@ -439,11 +444,18 @@ fun SettingsTabContent(
|
||||
if (!wdttLinkMode) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
// ═══ Заголовок раздела ═══
|
||||
Text(
|
||||
"Настройки туннеля",
|
||||
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
"Настройки туннеля",
|
||||
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
Text(
|
||||
"(${vpnProfileDisplayName(activeProfile, profileNames)})",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
|
||||
// ═══ Настройки туннеля ═══
|
||||
AppSectionCard(
|
||||
@@ -1171,17 +1183,29 @@ fun ImportantInfoDialog(onDismiss: () -> Unit) {
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
InfoSection("Капча VK",
|
||||
"Авто-режим старается пройти капчу сам, но иногда VK всё равно показывает проверку. Если появилось окно капчи, чаще всего достаточно поставить галочку в квадрате."
|
||||
InfoSection(
|
||||
"Профили VPN",
|
||||
"В боковых настройках доступны VPN 1, VPN 2 и VPN 3. Короткое нажатие переключает профиль, долгое нажатие позволяет переименовать его."
|
||||
)
|
||||
InfoSection("Сетевое окружение",
|
||||
"Перед подключением выключите другие VPN, системные прокси и «Приватный DNS», чтобы они не перехватывали трафик WDTT Plus."
|
||||
InfoSection(
|
||||
"VK-хеши",
|
||||
"VK-хеш нужен для работы туннеля. В настройке VK-хешей можно проверить каждый слот, скопировать отдельный хеш или все заполненные хеши сразу."
|
||||
)
|
||||
InfoSection("VK-хеши и мощность",
|
||||
"VK-хеш нужен для работы туннеля. Несколько хешей позволяют распределять нагрузку, а мощность лучше держать в умеренном диапазоне 12-36 потоков."
|
||||
InfoSection(
|
||||
"Клиенты и сервер",
|
||||
"В режиме «Я — админ» блок «Деплой» → «Клиенты и сервер» управляет клиентами без Telegram-бота: создание, продление, отключение, смена пароля, экспорт и импорт отдельного клиента."
|
||||
)
|
||||
InfoSection("Связь потоков и капч",
|
||||
"Чем выше мощность, тем больше нагрузка, расход батареи и шанс чаще видеть капчу. Повышайте её только если сеть нестабильная и сервер справляется."
|
||||
InfoSection(
|
||||
"Передача подключения",
|
||||
"Обычное подключение передаётся через «Настройки» → «Передать или получить». Перенос отдельного клиента выполняется именно в блоке «Клиенты и сервер»."
|
||||
)
|
||||
InfoSection(
|
||||
"После новых серверных функций",
|
||||
"Если приложение пишет, что сервер не поддерживает действие, выполните во вкладке «Деплой» установку сервера с сохранением данных."
|
||||
)
|
||||
InfoSection(
|
||||
"Капча и мощность",
|
||||
"Авто-режим старается пройти капчу сам. Несколько VK-хешей распределяют нагрузку, а мощность лучше держать умеренной: чем она выше, тем больше расход батареи и шанс чаще видеть капчу."
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
@@ -1246,6 +1270,13 @@ private fun encodeVkHashSlots(vararg hashes: String): String {
|
||||
return slots.joinToString(",")
|
||||
}
|
||||
|
||||
private fun copyVkHashesToClipboard(context: android.content.Context, label: String, value: String) {
|
||||
if (value.isBlank()) return
|
||||
val clipboard = context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText(label, value))
|
||||
Toast.makeText(context, "Скопировано", Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
// ═══ Модальное окно хешей ═══
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
@@ -1276,6 +1307,11 @@ fun HashesDialog(
|
||||
val currentHashes = remember(h1, h2, h3, h4) {
|
||||
listOf(h1, h2, h3, h4).map { stripVkUrlStatic(it) }
|
||||
}
|
||||
val copiedHashesText = remember(currentHashes) {
|
||||
currentHashes
|
||||
.filter { it.isNotBlank() }
|
||||
.joinToString(",")
|
||||
}
|
||||
val checkableHashes = remember(currentHashes) {
|
||||
currentHashes.mapIndexedNotNull { index, hash ->
|
||||
if (hash.length >= 16) index + 1 to hash else null
|
||||
@@ -1395,6 +1431,7 @@ fun HashesDialog(
|
||||
Triple("VK Хеш 4", h4) { v: String -> h4 = v }
|
||||
).forEachIndexed { idx, (label, value, onChange) ->
|
||||
val slot = idx + 1
|
||||
val cleanedValue = stripVkUrlStatic(value)
|
||||
HashInputField(
|
||||
slot = slot,
|
||||
label = label,
|
||||
@@ -1404,10 +1441,24 @@ fun HashesDialog(
|
||||
onChange(stripVkUrlStatic(cleaned))
|
||||
},
|
||||
result = checkResults[slot],
|
||||
onInfoClick = { detailSlot = slot }
|
||||
onInfoClick = { detailSlot = slot },
|
||||
canCopy = cleanedValue.isNotBlank(),
|
||||
onCopyClick = { copyVkHashesToClipboard(context, "VK Хеш $slot", cleanedValue) }
|
||||
)
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = { copyVkHashesToClipboard(context, "VK Хеши WDTT Plus", copiedHashesText) },
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
enabled = copiedHashesText.isNotBlank(),
|
||||
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp)
|
||||
) {
|
||||
Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
FlexibleButtonText("Скопировать все хеши", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
checkJob?.cancel(CancellationException("Restarting hash check"))
|
||||
@@ -1506,7 +1557,9 @@ private fun HashInputField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
result: HashCheckResult?,
|
||||
onInfoClick: () -> Unit
|
||||
onInfoClick: () -> Unit,
|
||||
canCopy: Boolean,
|
||||
onCopyClick: () -> Unit
|
||||
) {
|
||||
val isShort = value.isNotBlank() && value.length < 16
|
||||
val visibleResult = result?.takeIf { it.status != "pending" }
|
||||
@@ -1536,30 +1589,47 @@ private fun HashInputField(
|
||||
}
|
||||
else -> null
|
||||
},
|
||||
trailingIcon = if (visibleResult != null) {
|
||||
{
|
||||
trailingIcon = {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(2.dp)
|
||||
) {
|
||||
IconButton(
|
||||
onClick = onInfoClick,
|
||||
onClick = onCopyClick,
|
||||
enabled = canCopy,
|
||||
modifier = Modifier.size(34.dp)
|
||||
) {
|
||||
Surface(
|
||||
shape = CircleShape,
|
||||
color = borderColor.copy(alpha = 0.14f),
|
||||
border = BorderStroke(1.dp, borderColor.copy(alpha = 0.7f)),
|
||||
modifier = Modifier.size(22.dp)
|
||||
Icon(
|
||||
Icons.Default.ContentCopy,
|
||||
contentDescription = "Скопировать VK Хеш $slot",
|
||||
modifier = Modifier.size(18.dp),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = if (canCopy) 1f else 0.38f)
|
||||
)
|
||||
}
|
||||
if (visibleResult != null) {
|
||||
IconButton(
|
||||
onClick = onInfoClick,
|
||||
modifier = Modifier.size(34.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"?",
|
||||
color = borderColor,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
Surface(
|
||||
shape = CircleShape,
|
||||
color = borderColor.copy(alpha = 0.14f),
|
||||
border = BorderStroke(1.dp, borderColor.copy(alpha = 0.7f)),
|
||||
modifier = Modifier.size(22.dp)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Text(
|
||||
"?",
|
||||
color = borderColor,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else null,
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
colors = OutlinedTextFieldDefaults.colors(
|
||||
|
||||
@@ -58,12 +58,14 @@ import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.journeyapps.barcodescanner.ScanContract
|
||||
import com.journeyapps.barcodescanner.ScanOptions
|
||||
import com.wdtt.plus.SettingsStore
|
||||
import com.wdtt.plus.TransferFiles
|
||||
import com.wdtt.plus.WdttTransferCodec
|
||||
import com.wdtt.plus.QrCaptureActivity
|
||||
import com.wdtt.plus.vpnProfileDisplayName
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
@@ -88,6 +90,8 @@ fun TransferCenterDialog(
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
var qrData by remember { mutableStateOf<Pair<String, Bitmap>?>(null) }
|
||||
var adminAction by remember { mutableStateOf<AdminExportAction?>(null) }
|
||||
val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList())
|
||||
val activeProfileLabel = vpnProfileDisplayName(activeProfile, profileNames)
|
||||
|
||||
fun runCatchingUi(block: suspend () -> Unit) {
|
||||
busy = true
|
||||
@@ -154,7 +158,7 @@ fun TransferCenterDialog(
|
||||
}
|
||||
|
||||
HorizontalDivider()
|
||||
Text("Передача VPN ${activeProfile + 1}", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text("Передача $activeProfileLabel", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Ссылка содержит пароль подключения и VK-хеши. Передавайте её только тому, кому доверяете.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
@@ -169,7 +173,7 @@ fun TransferCenterDialog(
|
||||
runCatchingUi {
|
||||
val link = settingsStore.connectionLinkForProfile(activeProfile)
|
||||
val bitmap = withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) }
|
||||
qrData = "VPN ${activeProfile + 1}" to bitmap
|
||||
qrData = activeProfileLabel to bitmap
|
||||
}
|
||||
}
|
||||
TransferButton("Ссылка", Icons.Default.Share, busy) {
|
||||
@@ -181,7 +185,7 @@ fun TransferCenterDialog(
|
||||
runCatchingUi {
|
||||
val link = settingsStore.connectionLinkForProfile(activeProfile)
|
||||
val uri = withContext(Dispatchers.IO) {
|
||||
TransferFiles.writeTransferText(context, "WDTT-Plus-VPN-${activeProfile + 1}.wdtt", link)
|
||||
TransferFiles.writeTransferText(context, "WDTT-Plus-${activeProfileLabel.safeTransferFileName()}.wdtt", link)
|
||||
}
|
||||
shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus")
|
||||
}
|
||||
@@ -495,6 +499,14 @@ private fun String.safeQrFileName(): String =
|
||||
.trim('_', '.', '-')
|
||||
.ifBlank { "qr" }
|
||||
|
||||
private fun String.safeTransferFileName(): String =
|
||||
replace(Regex("[^\\p{L}\\p{N}._-]+"), "-")
|
||||
.replace(Regex("-+"), "-")
|
||||
.trim('_', '.', '-')
|
||||
.take(48)
|
||||
.trim('_', '.', '-')
|
||||
.ifBlank { "VPN" }
|
||||
|
||||
private fun shareUri(context: Context, uri: Uri, mimeType: String, title: String) {
|
||||
val intent = Intent(Intent.ACTION_SEND).apply {
|
||||
type = mimeType
|
||||
|
||||
Reference in new issue
Block a user