Выпуск WDTT Plus v2

This commit is contained in:
Ivan4537 committed 2026-07-03 16:59:27 +03:00
1 parent a8dce499eb
commit d30934ef4f
28 files changed
+8182 -355

No files matched your search

+213 -24
View File
@@ -59,13 +59,17 @@ import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.dp
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
@@ -77,6 +81,8 @@ import com.wdtt.plus.ui.SettingsTab
import com.wdtt.plus.ui.DeployTab
import com.wdtt.plus.ui.ExceptionsTab
import com.wdtt.plus.ui.InfoTab
import com.wdtt.plus.ui.AdminImportDialog
import com.wdtt.plus.ui.TransferCenterDialog
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.first
@@ -91,6 +97,7 @@ class MainActivity : ComponentActivity() {
private var sharedVkHashError by mutableStateOf<String?>(null)
private var wdttDeepLinkMessage by mutableStateOf<String?>(null)
private var pendingWdttDeepLinkPlan by mutableStateOf<WdttDeepLinkApplyPlan?>(null)
private var pendingAdminTransfer by mutableStateOf<String?>(null)
companion object {
var activeActivities = 0
@@ -138,6 +145,16 @@ class MainActivity : ComponentActivity() {
wdttDeepLinkMessage = wdttDeepLinkMessage,
onWdttDeepLinkMessageShown = { wdttDeepLinkMessage = null },
pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan,
pendingAdminTransfer = pendingAdminTransfer,
onIncomingTransferContent = ::handleIncomingTransferText,
onAdminTransferDismissed = { pendingAdminTransfer = null },
onAdminTransferFinished = { message ->
pendingAdminTransfer = null
wdttDeepLinkMessage = message
},
onSelectWdttDeepLinkOverwriteProfile = { profile ->
pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan?.copy(targetProfile = profile)
},
onConfirmWdttDeepLinkOverwrite = { plan ->
pendingWdttDeepLinkPlan = null
applyWdttDeepLinkPlan(plan)
@@ -171,21 +188,82 @@ class MainActivity : ComponentActivity() {
)
}
}
handleIncomingShareIntent(intent)
handleIncomingWdttDeepLink(intent)
handleIncomingIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIncomingShareIntent(intent)
handleIncomingWdttDeepLink(intent)
handleIncomingIntent(intent)
}
private fun handleIncomingWdttDeepLink(intent: Intent?) {
if (intent?.action != Intent.ACTION_VIEW) return
val link = intent.dataString?.trim().orEmpty()
if (!link.startsWith("wdtt://", ignoreCase = true)) return
private fun handleIncomingIntent(intent: Intent?) {
when (intent?.action) {
Intent.ACTION_VIEW -> {
val data = intent.data ?: return
if (data.scheme.equals("wdtt", ignoreCase = true)) {
handleIncomingTransferText(data.toString())
} else {
handleIncomingUri(data, intent.type)
}
}
Intent.ACTION_SEND -> {
val streamUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri
} ?: 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"
} == true
if (streamFirst && streamUri != null) {
handleIncomingUri(streamUri, intent.type)
return
}
val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT)
?: intent.clipData?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text?.toString()
if (!sharedText.isNullOrBlank()) {
handleIncomingTransferText(sharedText)
return
}
if (streamUri != null) handleIncomingUri(streamUri, intent.type)
}
}
}
private fun handleIncomingUri(uri: Uri, mimeType: String?) {
lifecycleScope.launch {
runCatching {
kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
if (mimeType?.startsWith("image/") == true) {
TransferFiles.decodeQrImage(this@MainActivity, uri)
} else {
TransferFiles.readText(this@MainActivity, uri)
}
}
}.onSuccess(::handleIncomingTransferText)
.onFailure { wdttDeepLinkMessage = it.message ?: "Не удалось прочитать переданные данные." }
}
}
private fun handleIncomingTransferText(value: String) {
val link = WdttTransferCodec.extractWdttLink(value)
when {
link != null -> handleIncomingWdttLink(link)
WdttTransferCodec.isAdminTransfer(value) -> pendingAdminTransfer = value.trim()
WdttTransferCodec.documentFormat(value) == "wdtt-server-backup" -> {
wdttDeepLinkMessage = "Распознана резервная копия сервера. Она применяется к выбранному серверу во вкладке «Деплой» → «Перенос сервера» → «Импорт»."
}
WdttTransferCodec.documentFormat(value) == "wdtt-plus-admin-settings" -> {
wdttDeepLinkMessage = "Распознаны незашифрованные настройки администратора. В целях безопасности импортируется только защищённый файл, созданный через раздел «Передача»."
}
else -> handleIncomingVkShare(value)
}
}
private fun handleIncomingWdttLink(link: String) {
lifecycleScope.launch {
val store = SettingsStore(this@MainActivity)
runCatching {
@@ -224,11 +302,14 @@ class MainActivity : ComponentActivity() {
}
}
private fun handleIncomingShareIntent(intent: Intent?) {
if (intent?.action != Intent.ACTION_SEND) return
val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT)
?: intent.clipData?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.coerceToText(this)?.toString()
?: return
private fun handleIncomingVkShare(sharedText: String) {
val trimmed = sharedText.trim().trim('<', '>', '"', '\'')
val looksLikeJoinLink = trimmed.contains("/call/join/", ignoreCase = true)
val looksLikeRawHash = Regex("^[A-Za-z0-9_-]{16,512}$").matches(trimmed)
if (!looksLikeJoinLink && !looksLikeRawHash) {
sharedVkHashError = "Данные не распознаны. Поддерживаются ссылка подключения wdtt://, файл или QR WDTT Plus и ссылка VK-звонка."
return
}
val hash = VkJoinLink.extractHash(sharedText)
if (hash.length < 16) {
sharedVkHashError = "В переданной ссылке не найден VK-хеш звонка."
@@ -533,6 +614,11 @@ fun MainScreen(
wdttDeepLinkMessage: String? = null,
onWdttDeepLinkMessageShown: () -> Unit = {},
pendingWdttDeepLinkPlan: WdttDeepLinkApplyPlan? = null,
pendingAdminTransfer: String? = null,
onIncomingTransferContent: (String) -> Unit = {},
onAdminTransferDismissed: () -> Unit = {},
onAdminTransferFinished: (String) -> Unit = {},
onSelectWdttDeepLinkOverwriteProfile: (Int) -> Unit = {},
onConfirmWdttDeepLinkOverwrite: (WdttDeepLinkApplyPlan) -> Unit = {},
onCancelWdttDeepLinkOverwrite: () -> Unit = {},
themeMode: String = "system",
@@ -551,13 +637,29 @@ fun MainScreen(
val view = LocalView.current
val context = LocalContext.current
val density = LocalDensity.current
val focusManager = LocalFocusManager.current
val scope = rememberCoroutineScope()
val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0)
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 isAdminInterface = interfaceRole == "admin"
val isUpdatedInstall = remember(context) {
runCatching {
context.packageManager.getPackageInfo(context.packageName, 0).let { info ->
info.lastUpdateTime > info.firstInstallTime
}
}.getOrDefault(false)
}
var selectedTab by rememberSaveable { mutableIntStateOf(0) }
val tunnelScrollPosition = rememberSaveable { mutableIntStateOf(0) }
val deployScrollPosition = rememberSaveable { mutableIntStateOf(0) }
val exceptionsFirstVisibleItemIndex = rememberSaveable { mutableIntStateOf(0) }
val exceptionsFirstVisibleItemScrollOffset = rememberSaveable { mutableIntStateOf(0) }
val logsFirstVisibleItemIndex = rememberSaveable { mutableIntStateOf(0) }
val logsFirstVisibleItemScrollOffset = rememberSaveable { mutableIntStateOf(0) }
val infoScrollPosition = rememberSaveable { mutableIntStateOf(0) }
var dragTargetIndex by remember { mutableIntStateOf(-1) }
var dragProgress by remember { mutableFloatStateOf(0f) }
val updateCheckIntervalHours by settingsStore.updateCheckIntervalHours.collectAsStateWithLifecycle(
@@ -567,6 +669,7 @@ fun MainScreen(
val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" }
val safeBottomInset = with(density) { WindowInsets.safeDrawing.getBottom(density).toDp() }
val navOverlayReserve = safeBottomInset + 96.dp
var showTransferCenter by rememberSaveable { mutableStateOf(false) }
if (interfaceRole.isBlank()) {
RoleSelectionScreen(
@@ -688,6 +791,16 @@ fun MainScreen(
.fillMaxSize()
.padding(padding)
.consumeWindowInsets(padding)
.pointerInput(focusManager) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent(PointerEventPass.Initial)
if (event.type == PointerEventType.Press) {
focusManager.clearFocus()
}
}
}
}
.pointerInput(selectedTab, wdttLinkMode) {
var totalDrag = 0f
detectHorizontalDragGestures(
@@ -709,6 +822,7 @@ fun MainScreen(
dragProgress = 0f
}
) { change, dragAmount ->
if (change.isConsumed) return@detectHorizontalDragGestures
change.consume()
totalDrag += dragAmount
if (abs(totalDrag) < 12f) {
@@ -741,11 +855,21 @@ fun MainScreen(
label = "tab_content"
) { tab ->
when (tab) {
0 -> SettingsTab()
1 -> if (!wdttLinkMode) DeployTab() else Spacer(modifier = Modifier.fillMaxSize())
2 -> ExceptionsTab()
3 -> LogsTab()
4 -> InfoTab(actionsExpandedState = actionsExpanded, projectExpandedState = projectExpanded)
0 -> SettingsTab(scrollPosition = tunnelScrollPosition)
1 -> if (!wdttLinkMode) DeployTab(scrollPosition = deployScrollPosition) else Spacer(modifier = Modifier.fillMaxSize())
2 -> ExceptionsTab(
firstVisibleItemIndex = exceptionsFirstVisibleItemIndex,
firstVisibleItemScrollOffset = exceptionsFirstVisibleItemScrollOffset
)
3 -> LogsTab(
firstVisibleItemIndex = logsFirstVisibleItemIndex,
firstVisibleItemScrollOffset = logsFirstVisibleItemScrollOffset
)
4 -> InfoTab(
actionsExpandedState = actionsExpanded,
projectExpandedState = projectExpanded,
scrollPosition = infoScrollPosition
)
}
}
@@ -789,7 +913,62 @@ fun MainScreen(
activeFingerprint = activeFingerprint,
onFingerprintChange = onFingerprintChange,
activeClientIds = activeClientIds,
onClientIdsChange = onClientIdsChange
onClientIdsChange = onClientIdsChange,
onTransferRequested = { showTransferCenter = true }
)
}
if (
BuildConfig.VERSION_CODE == 2 &&
isAdminInterface &&
isUpdatedInstall &&
!migrationNoticeV2Shown
) {
AlertDialog(
onDismissRequest = {},
properties = DialogProperties(
dismissOnBackPress = false,
dismissOnClickOutside = false
),
title = { Text("Требуется обновление сервера") },
text = {
Text(
"Это крупное обновление WDTT Plus. Для корректной работы новых функций необходимо выполнить установку сервера во вкладке «Деплой».\n\n" +
"Выберите установку с сохранением данных. Настройки, клиенты и выданные доступы сохранятся — будет обновлена только серверная часть.\n\n" +
"Установку с нуля выполнять не нужно."
)
},
confirmButton = {
Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
Button(
onClick = { scope.launch { settingsStore.saveMigrationNoticeV2Shown() } }
) {
Text("Хорошо")
}
}
}
)
}
if (showTransferCenter) {
TransferCenterDialog(
settingsStore = settingsStore,
activeProfile = activeProfile,
isAdmin = isAdminInterface,
onIncomingContent = {
showTransferCenter = false
onIncomingTransferContent(it)
},
onDismiss = { showTransferCenter = false }
)
}
pendingAdminTransfer?.let { document ->
AdminImportDialog(
settingsStore = settingsStore,
encryptedDocument = document,
onFinished = onAdminTransferFinished,
onDismiss = onAdminTransferDismissed
)
}
@@ -836,7 +1015,7 @@ fun MainScreen(
sharedVkHashError?.let { error ->
AlertDialog(
onDismissRequest = onSharedVkHashMessageShown,
title = { Text("VK-хеш не добавлен") },
title = { Text("Данные не импортированы") },
text = { Text(error) },
confirmButton = {
TextButton(onClick = onSharedVkHashMessageShown) {
@@ -849,7 +1028,7 @@ fun MainScreen(
wdttDeepLinkMessage?.let { message ->
AlertDialog(
onDismissRequest = onWdttDeepLinkMessageShown,
title = { Text("Ссылка WDTT") },
title = { Text("Передача WDTT") },
text = { Text(message) },
confirmButton = {
TextButton(onClick = onWdttDeepLinkMessageShown) {
@@ -865,9 +1044,19 @@ fun MainScreen(
onDismissRequest = onCancelWdttDeepLinkOverwrite,
title = { Text("Профили VPN заполнены") },
text = {
Text(
"Свободных профилей VPN нет. Ссылка перезапишет профиль $profileLabel. Выполнить действие?"
)
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Свободных профилей VPN нет. Выберите профиль, который можно перезаписать:")
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
repeat(3) { profile ->
FilterChip(
selected = plan.targetProfile == profile,
onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) },
label = { Text("VPN ${profile + 1}") }
)
}
}
Text("Будет полностью заменено подключение в профиле $profileLabel.")
}
},
confirmButton = {
TextButton(onClick = { onConfirmWdttDeepLinkOverwrite(plan) }) {
@@ -0,0 +1,33 @@
package com.wdtt.plus
import android.os.Bundle
import android.view.View
import com.journeyapps.barcodescanner.CaptureActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.google.zxing.client.android.R as ZxingR
class QrCaptureActivity : CaptureActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val statusView = findViewById<View>(ZxingR.id.zxing_status_view) ?: return
val originalLeft = statusView.paddingLeft
val originalTop = statusView.paddingTop
val originalRight = statusView.paddingRight
val originalBottom = statusView.paddingBottom
val extraBottom = (24 * resources.displayMetrics.density).toInt()
ViewCompat.setOnApplyWindowInsetsListener(statusView) { view, insets ->
val systemBottom = insets.getInsets(
WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout()
).bottom
view.setPadding(
originalLeft,
originalTop,
originalRight,
originalBottom + systemBottom + extraBottom
)
insets
}
ViewCompat.requestApplyInsets(statusView)
}
}
@@ -0,0 +1,614 @@
package com.wdtt.plus
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.util.Properties
data class ServerAdminTarget(
val host: String,
val user: String,
val sshPassword: String,
val sshPort: Int,
val mainPassword: String
)
data class ServerAdminProfileInfo(
val vkHashes: String = "",
val secondaryVkHash: String = "",
val workersPerHash: Int = 16,
val protocol: String = "udp",
val listenPort: Int = 9000,
val sni: String = "",
val noDns: Boolean = false,
val ports: String = "56000,56001,9000",
val deviceIds: List<String> = emptyList(),
val updatedAt: Long = 0
) {
val hasSavedFields: Boolean
get() = updatedAt > 0L || vkHashes.isNotBlank() || secondaryVkHash.isNotBlank()
}
data class ServerAdminState(
val publicHost: String,
val effectivePublicHost: String,
val dns: String,
val defaultPorts: String,
val maxPasswords: Int,
val passwordCount: Int,
val deviceCount: Int,
val expiredCount: Int,
val orphanDeviceCount: Int,
val orphanDevices: List<ServerDeviceInfo>,
val traffic: ServerTrafficPeriod,
val adminTraffic: ServerTrafficPeriod,
val adminProfile: ServerAdminProfileInfo,
val clients: List<ServerClientInfo>
) {
val linkHost: String
get() = publicHost.ifBlank { "" }
}
data class ServerTrafficValue(val down: Long = 0, val up: Long = 0)
data class ServerTrafficPeriod(
val today: ServerTrafficValue = ServerTrafficValue(),
val week: ServerTrafficValue = ServerTrafficValue(),
val month: ServerTrafficValue = ServerTrafficValue(),
val all: ServerTrafficValue = ServerTrafficValue()
)
data class ServerDeviceInfo(
val deviceId: String,
val ip: String,
val name: String,
val manufacturer: String,
val brand: String,
val model: String,
val androidVersion: String,
val sdk: Int,
val abi: String,
val appVersion: String,
val locale: String,
val country: String,
val timeZone: String,
val remoteIp: String,
val lastSeenAt: Long
)
data class ServerBindEvent(
val deviceId: String,
val deviceName: String,
val deviceIp: String,
val remoteIp: String,
val country: String,
val boundAt: Long,
val unboundAt: Long,
val eventAt: Long,
val status: String,
val note: String
)
data class ServerClientInfo(
val password: String,
val label: String,
val vkHash: String,
val ports: String,
val status: String,
val expiresAt: Long,
val downBytes: Long,
val upBytes: Long,
val deviceId: String,
val deviceName: String,
val deviceIp: String,
val deviceLastSeen: Long,
val bindEventsCount: Int,
val traffic: ServerTrafficPeriod,
val device: ServerDeviceInfo?,
val bindHistory: List<ServerBindEvent>
) {
val title: String
get() = label.ifBlank { "Без имени" }
val isActive: Boolean
get() = status == "active"
val isBound: Boolean
get() = deviceId.isNotBlank()
}
data class ServerClientCreateRequest(
val days: Int,
val label: String,
val vkHash: String,
val ports: String
)
data class ServerAdminActionResult(
val message: String,
val restartRequired: Boolean,
val restarted: Boolean,
val createdClient: ServerClientInfo?
)
object ServerAdminClient {
private const val ADMIN_TIMEOUT = 45_000L
private const val RESTART_TIMEOUT = 70_000L
suspend fun list(target: ServerAdminTarget): ServerAdminState = withContext(Dispatchers.IO) {
withSession(target) { ssh ->
parseState(callAdmin(ssh, target, listOf("list")))
}
}
suspend fun details(target: ServerAdminTarget, password: String): ServerClientInfo = withContext(Dispatchers.IO) {
withSession(target) { ssh ->
val json = callAdmin(ssh, target, listOf("details", "--password", password))
json.optJSONObject("password")?.let(::parseClient)
?: throw IllegalStateException("сервер не вернул данные клиента")
}
}
suspend fun create(target: ServerAdminTarget, request: ServerClientCreateRequest): ServerAdminActionResult =
withContext(Dispatchers.IO) {
withSession(target) { ssh ->
val args = mutableListOf(
"create",
"--days", request.days.coerceIn(0, 365).toString()
)
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())
actionFromResponse(callAdmin(ssh, target, args))
}
}
suspend fun delete(target: ServerAdminTarget, password: String): ServerAdminActionResult =
runPasswordAction(target, "delete", password)
suspend fun unbind(target: ServerAdminTarget, password: String): ServerAdminActionResult =
runPasswordAction(target, "unbind", password)
suspend fun deactivate(target: ServerAdminTarget, password: String): ServerAdminActionResult =
runPasswordAction(target, "deactivate", password)
suspend fun activate(target: ServerAdminTarget, password: String): ServerAdminActionResult =
runPasswordAction(target, "activate", password)
suspend fun setExpiry(target: ServerAdminTarget, password: String, days: Int): ServerAdminActionResult =
withContext(Dispatchers.IO) {
withSession(target) { ssh ->
actionFromResponse(
callAdmin(ssh, target, listOf("set-expiry", "--password", password, "--days", days.coerceIn(0, 365).toString()))
)
}
}
suspend fun setLabel(target: ServerAdminTarget, password: String, label: String): ServerAdminActionResult =
withContext(Dispatchers.IO) {
withSession(target) { ssh ->
actionFromResponse(
callAdmin(ssh, target, listOf("set-label", "--password", password, "--label", label))
)
}
}
suspend fun setHash(target: ServerAdminTarget, password: String, hash: String): ServerAdminActionResult =
withContext(Dispatchers.IO) {
withSession(target) { ssh ->
actionFromResponse(
callAdmin(ssh, target, listOf("set-hash", "--password", password, "--vk-hash", hash))
)
}
}
suspend fun setPorts(target: ServerAdminTarget, password: String, ports: String): ServerAdminActionResult =
runArgsAction(target, listOf("set-ports", "--password", password, "--ports", ports))
suspend fun updateClient(target: ServerAdminTarget, password: String, label: String, hash: String, ports: String): ServerAdminActionResult =
withContext(Dispatchers.IO) {
withSession(target) { ssh ->
val requestedLabel = label.trim()
val updated = actionFromResponse(callAdmin(ssh, target, listOf(
"update-client", "--password", password,
"--label", requestedLabel, "--vk-hash", hash, "--ports", ports
)))
val relabeled = actionFromResponse(
callAdmin(ssh, target, listOf("set-label", "--password", password, "--label", requestedLabel))
)
val savedClient = relabeled.createdClient ?: updated.createdClient
if (requestedLabel.isNotBlank() && savedClient?.label.isNullOrBlank()) {
throw IllegalStateException("Название не сохранилось на сервере. Попробуйте обновить сервер WDTT Plus и повторить.")
}
relabeled.copy(
message = updated.message,
restartRequired = updated.restartRequired || relabeled.restartRequired,
restarted = updated.restarted || relabeled.restarted,
createdClient = savedClient
)
}
}
suspend fun setDns(target: ServerAdminTarget, value: String): ServerAdminActionResult =
runArgsAction(target, listOf("set-dns", "--value", value))
suspend fun setLimit(target: ServerAdminTarget, value: Int): ServerAdminActionResult =
runArgsAction(target, listOf("set-limit", "--value", value.coerceIn(1, 500).toString()))
suspend fun setDefaultPorts(target: ServerAdminTarget, value: String): ServerAdminActionResult =
runArgsAction(target, listOf("set-default-ports", "--value", value))
suspend fun setPublicHost(target: ServerAdminTarget, value: String): ServerAdminActionResult =
runArgsAction(target, listOf("set-public-ip", "--value", value.ifBlank { "auto" }))
suspend fun updateSettings(
target: ServerAdminTarget,
dns: String,
limit: Int,
defaultPorts: String,
publicHost: String
): ServerAdminActionResult = runArgsAction(target, listOf(
"update-settings", "--dns", dns,
"--limit", limit.coerceIn(1, 500).toString(),
"--ports", defaultPorts,
"--public-ip", publicHost.ifBlank { "auto" }
))
suspend fun updateAdminProfile(target: ServerAdminTarget, profile: ServerAdminProfileInfo): ServerAdminActionResult {
val args = mutableListOf(
"update-admin-profile",
"--vk-hashes", profile.vkHashes.trim(),
"--secondary-vk-hash", profile.secondaryVkHash.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 =
runArgsAction(target, listOf("refresh-public-ip"))
suspend fun cleanupExpired(target: ServerAdminTarget): ServerAdminActionResult =
runArgsAction(target, listOf("cleanup-expired"))
suspend fun cleanupOrphans(target: ServerAdminTarget): ServerAdminActionResult =
runArgsAction(target, listOf("cleanup-orphans"))
suspend fun resetTraffic(target: ServerAdminTarget): ServerAdminActionResult =
runArgsAction(target, listOf("reset-traffic"))
suspend fun restart(target: ServerAdminTarget): ServerAdminActionResult =
withContext(Dispatchers.IO) {
withSession(target) { ssh ->
ssh.exec(rootCommand("systemctl restart wdtt"), RESTART_TIMEOUT)
ServerAdminActionResult(
message = "Готово",
restartRequired = false,
restarted = true,
createdClient = null
)
}
}
private suspend fun runPasswordAction(target: ServerAdminTarget, command: String, password: String): ServerAdminActionResult =
withContext(Dispatchers.IO) {
withSession(target) { ssh ->
actionFromResponse(callAdmin(ssh, target, listOf(command, "--password", password)))
}
}
private suspend fun runArgsAction(target: ServerAdminTarget, args: List<String>): ServerAdminActionResult =
withContext(Dispatchers.IO) {
withSession(target) { ssh -> actionFromResponse(callAdmin(ssh, target, args)) }
}
private fun <T> withSession(target: ServerAdminTarget, block: (AdminSshClient) -> T): T {
var session: Session? = null
try {
session = createSession(target)
return block(AdminSshClient(session, target.sshPassword))
} finally {
try { session?.disconnect() } catch (_: Exception) {}
}
}
private fun callAdmin(ssh: AdminSshClient, target: ServerAdminTarget, args: List<String>): JSONObject {
val command = buildString {
append("/usr/local/bin/wdtt-server admin")
append(" --config-dir /etc/wdtt")
append(" --main-password ")
append(shellQuote(target.mainPassword))
args.forEach {
append(' ')
append(shellQuote(it))
}
}
val output = ssh.exec(rootCommand(command), ADMIN_TIMEOUT)
val json = extractJson(output)
if (!json.optBoolean("ok", false)) {
throw IllegalStateException(friendlyAdminError(json.optString("message", output)))
}
return json
}
private fun actionFromResponse(json: JSONObject): ServerAdminActionResult {
val restartRequired = json.optBoolean("restart_required", false)
if (restartRequired) {
throw IllegalStateException(
"Сервер вернул старый режим сохранения через перезапуск. " +
"Переустановите сервер из этой версии WDTT Plus, чтобы изменения применялись на живую."
)
}
val createdClient = json.optJSONObject("password")?.let(::parseClient)
return ServerAdminActionResult(
message = json.optString("message", "Готово"),
restartRequired = restartRequired,
restarted = false,
createdClient = createdClient
)
}
private fun parseState(json: JSONObject): ServerAdminState {
val server = json.optJSONObject("server") ?: JSONObject()
val clientsJson = json.optJSONArray("passwords")
val clients = buildList {
if (clientsJson != null) {
for (i in 0 until clientsJson.length()) {
val item = clientsJson.optJSONObject(i) ?: continue
add(parseClient(item))
}
}
}
val defaultPorts = server.optString("default_ports", "56000,56001,9000")
return ServerAdminState(
publicHost = server.optString("public_ip", ""),
effectivePublicHost = server.optString("effective_public_ip", ""),
dns = server.optString("dns", ""),
defaultPorts = defaultPorts,
maxPasswords = server.optInt("max_passwords", 50),
passwordCount = server.optInt("password_count", clients.size),
deviceCount = server.optInt("device_count", 0),
expiredCount = server.optInt("expired_count", 0),
orphanDeviceCount = server.optInt("orphan_device_count", 0),
orphanDevices = buildList {
val devices = server.optJSONArray("orphan_devices") ?: return@buildList
for (i in 0 until devices.length()) {
devices.optJSONObject(i)?.let { add(parseDevice(it)) }
}
},
traffic = parseTrafficPeriod(server.optJSONObject("traffic")),
adminTraffic = parseTrafficPeriod(server.optJSONObject("admin_traffic")),
adminProfile = parseAdminProfile(server.optJSONObject("admin_profile"), defaultPorts),
clients = clients
)
}
private fun parseAdminProfile(json: JSONObject?, defaultPorts: String): ServerAdminProfileInfo {
val ports = json?.optString("ports", defaultPorts).orEmpty().ifBlank { defaultPorts }
val listenPort = json?.optInt("listen_port", 0)
?.takeIf { it in 1..65535 }
?: ports.thirdPortOrDefault(9000)
val deviceIds = buildList {
val raw = json?.optJSONArray("device_ids") ?: return@buildList
for (i in 0 until raw.length()) {
raw.optString(i).trim().takeIf { it.isNotBlank() }?.let(::add)
}
}
return ServerAdminProfileInfo(
vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(),
secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(),
workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128),
protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp",
listenPort = listenPort,
sni = json?.optString("sni", "").orEmpty().trim(),
noDns = json?.optBoolean("no_dns", false) ?: false,
ports = ports,
deviceIds = deviceIds,
updatedAt = json?.optLong("updated_at", 0L) ?: 0L
)
}
private fun parseClient(json: JSONObject): ServerClientInfo =
ServerClientInfo(
password = json.optString("password"),
label = json.optString("label", "").trim(),
vkHash = json.optString("vk_hash"),
ports = json.optString("ports", "56000,56001,9000"),
status = json.optString("status", "active"),
expiresAt = json.optLong("expires_at", 0),
downBytes = json.optLong("down_bytes", 0),
upBytes = json.optLong("up_bytes", 0),
deviceId = json.optString("device_id"),
deviceName = json.optString("device_name"),
deviceIp = json.optString("device_ip"),
deviceLastSeen = json.optLong("device_last_seen", 0),
bindEventsCount = json.optInt("bind_events_count", 0),
traffic = parseTrafficPeriod(json.optJSONObject("traffic")),
device = json.optJSONObject("device")?.let(::parseDevice),
bindHistory = buildList {
val history = json.optJSONArray("bind_history") ?: return@buildList
for (i in 0 until history.length()) {
history.optJSONObject(i)?.let { add(parseBindEvent(it)) }
}
}
)
private fun parseTrafficPeriod(json: JSONObject?): ServerTrafficPeriod = ServerTrafficPeriod(
today = parseTrafficValue(json?.optJSONObject("today")),
week = parseTrafficValue(json?.optJSONObject("week")),
month = parseTrafficValue(json?.optJSONObject("month")),
all = parseTrafficValue(json?.optJSONObject("all"))
)
private fun parseTrafficValue(json: JSONObject?): ServerTrafficValue = ServerTrafficValue(
down = json?.optLong("down", 0) ?: 0,
up = json?.optLong("up", 0) ?: 0
)
private fun parseDevice(json: JSONObject): ServerDeviceInfo = ServerDeviceInfo(
deviceId = json.optString("device_id"), ip = json.optString("ip"), name = json.optString("name"),
manufacturer = json.optString("manufacturer"), brand = json.optString("brand"), model = json.optString("model"),
androidVersion = json.optString("android_version"), sdk = json.optInt("sdk", 0), abi = json.optString("abi"),
appVersion = json.optString("app_version"), locale = json.optString("locale"), country = json.optString("country"),
timeZone = json.optString("time_zone"), remoteIp = json.optString("remote_ip"), lastSeenAt = json.optLong("last_seen_at", 0)
)
private fun parseBindEvent(json: JSONObject): ServerBindEvent = ServerBindEvent(
deviceId = json.optString("device_id"), deviceName = json.optString("device_name"),
deviceIp = json.optString("device_ip"), remoteIp = json.optString("remote_ip"), country = json.optString("country"),
boundAt = json.optLong("bound_at", 0), unboundAt = json.optLong("unbound_at", 0), eventAt = json.optLong("event_at", 0),
status = json.optString("status"), note = json.optString("note")
)
private fun createSession(target: ServerAdminTarget): Session {
val session = JSch().getSession(target.user.ifBlank { "root" }, target.host, target.sshPort)
session.setPassword(target.sshPassword)
session.setConfig(Properties().apply {
put("StrictHostKeyChecking", "no")
put("ServerAliveInterval", "10")
put("ServerAliveCountMax", "6")
put("ConnectTimeout", "15000")
put("PreferredAuthentications", "password,keyboard-interactive")
})
session.connect(20_000)
return session
}
private fun shellQuote(value: String): String =
"'" + value.replace("'", "'\"'\"'") + "'"
private fun rootCommand(command: String): String {
val quoted = shellQuote(command)
return "if command -v sudo >/dev/null 2>&1; then sudo -S bash -c $quoted; " +
"elif [ \"\$(id -u)\" = \"0\" ]; then bash -c $quoted; " +
"else echo 'error: root privileges required and sudo not found'; exit 1; fi"
}
private fun extractJson(output: String): JSONObject {
val candidate = output
.lineSequence()
.map { it.trim() }
.filter { it.startsWith("{") && it.endsWith("}") }
.lastOrNull()
?: throw IllegalStateException(friendlyAdminError(output.ifBlank { "сервер не вернул JSON" }))
return JSONObject(candidate)
}
private fun friendlyAdminError(raw: String): String {
val text = raw.trim()
val lower = text.lowercase()
return when {
"no_passwords_json" in lower ->
"на сервере не найдена база WDTT Plus. Сначала выполните деплой."
"admin_socket_unavailable" in lower ->
"сервер ещё не поддерживает управление без перезапуска. Переустановите сервер из этой версии WDTT Plus."
"главный пароль" in lower ->
"главный пароль администратора не совпадает с сервером."
"no such file" in lower || "not found" in lower && "wdtt-server" in lower ->
"на сервере старый wdtt-server без admin-команд. Переустановите сервер из этой версии WDTT Plus."
"permission denied" in lower || "authentication failed" in lower || "auth fail" in lower ->
"не удалось войти по SSH. Проверьте логин, пароль и порт."
"root privileges required" in lower || "sudo not found" in lower ->
"для управления нужны root-права или sudo на сервере."
"connection refused" in lower ->
"сервер отклонил SSH-подключение. Проверьте SSH-порт."
"timeout" in lower || "timed out" in lower ->
"сервер не ответил вовремя."
text.isBlank() -> "операция не выполнена"
else -> text.take(220)
}
}
}
private class AdminSshClient(private val session: Session, private val sudoPassword: String) {
fun exec(command: String, timeout: Long): String {
if (!session.isConnected) throw IllegalStateException("SSH-сессия разорвана")
var channel: ChannelExec? = null
val result = StringBuilder()
try {
channel = session.openChannel("exec") as ChannelExec
channel.setCommand(command)
val outStream = channel.outputStream
val input = channel.inputStream
val err = channel.errStream
channel.connect(15_000)
if (command.contains("sudo -S")) {
outStream.write("$sudoPassword\n".toByteArray())
outStream.flush()
}
val reader = input.bufferedReader()
val errReader = err.bufferedReader()
val started = System.currentTimeMillis()
while (!channel.isClosed || reader.ready() || errReader.ready()) {
if (System.currentTimeMillis() - started > timeout) {
try { channel.disconnect() } catch (_: Exception) {}
throw IllegalStateException("timeout")
}
if (reader.ready()) {
reader.readLine()?.let { result.appendLine(cleanShellLine(it)) }
}
if (errReader.ready()) {
errReader.readLine()
?.takeIf { !it.contains("password for", ignoreCase = true) }
?.let { result.appendLine(cleanShellLine(it)) }
}
if (!reader.ready() && !errReader.ready()) Thread.sleep(80)
}
val output = result.toString().trim()
if (channel.exitStatus != 0) {
if (output.startsWith("{") && output.endsWith("}")) return output
throw IllegalStateException(output.ifBlank { "команда завершилась с кодом ${channel.exitStatus}" })
}
if (output.startsWith("error:", ignoreCase = true)) {
throw IllegalStateException(output)
}
return output
} finally {
try { channel?.disconnect() } catch (_: Exception) {}
}
}
private fun cleanShellLine(line: String): String =
line.replace(Regex("\u001B\\[[;\\d]*m"), "")
}
private fun String.thirdPortOrDefault(default: Int): Int =
split(",").map { it.trim().toIntOrNull() }.getOrNull(2)?.takeIf { it in 1..65535 } ?: default
fun ServerClientInfo.connectionLink(fallbackHost: String, publicHost: String): String? {
return buildServerConnectionLink(password, vkHash, ports, fallbackHost, publicHost)
}
fun buildServerConnectionLink(
password: String,
hashes: String,
ports: String,
fallbackHost: String,
publicHost: String
): String? {
if (hashes.isBlank() || password.isBlank()) return null
val parts = ports.split(",").map { it.trim().toIntOrNull() }
if (parts.size != 3) return null
val dtls = parts[0]?.takeIf { it in 1..65535 } ?: return null
val wg = parts[1]?.takeIf { it in 1..65535 } ?: return null
val local = parts[2]?.takeIf { it in 1..65535 } ?: return null
val host = publicHost.ifBlank { fallbackHost }.trim()
if (host.isBlank()) return null
return WdttTransferCodec.buildConnectionLink(
WdttLinkParts(
host = host,
dtlsPort = dtls,
wgPort = wg,
localPort = local,
password = password,
hashes = hashes
)
)
}
+249 -16
View File
@@ -16,6 +16,8 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject
import android.os.Build
@@ -81,7 +83,7 @@ object WdttDeepLink {
}
fun validate(value: String): WdttDeepLinkValidation {
val clean = value.trim()
val clean = WdttTransferCodec.extractWdttLink(value) ?: value.trim()
val errors = mutableListOf<String>()
val warnings = mutableListOf<String>()
@@ -99,8 +101,18 @@ object WdttDeepLink {
)
}
val parts = clean.substringAfter("://").split(":")
if (parts.size != 6) {
val modernParts = if (clean.startsWith("wdtt://connect?", ignoreCase = true)) {
WdttTransferCodec.parseConnectionLink(clean)
} else null
if (clean.startsWith("wdtt://connect?", ignoreCase = true) && modernParts == null) {
return WdttDeepLinkValidation(
parts = null,
errors = listOf("Новая ссылка повреждена, содержит неподдерживаемую версию или не все поля.")
)
}
val parts = if (modernParts == null) clean.substringAfter("://").split(":") else emptyList()
if (modernParts == null && parts.size != 6) {
val found = parts.size
val detail = when {
found < 6 -> "не хватает ${6 - found} ${fieldWord(6 - found)}"
@@ -112,21 +124,21 @@ object WdttDeepLink {
)
}
val host = parts[0].trim()
val host = modernParts?.host?.trim() ?: parts[0].trim()
if (!isValidTunnelHost(host)) {
errors += "Адрес сервера пустой или неверный. Нужен домен или IPv4 без https://, порта и пути."
}
val dtlsPort = validatePort(parts[1], "DTLS-порт", errors)
val wgPort = validatePort(parts[2], "WG-порт", errors)
val localPort = validatePort(parts[3], "локальный порт", errors)
val dtlsPort = validatePort((modernParts?.dtlsPort ?: parts[1]).toString(), "DTLS-порт", errors)
val wgPort = validatePort((modernParts?.wgPort ?: parts[2]).toString(), "WG-порт", errors)
val localPort = validatePort((modernParts?.localPort ?: parts[3]).toString(), "локальный порт", errors)
val password = parts[4].trim()
val password = modernParts?.password?.trim() ?: parts[4].trim()
if (password.isBlank()) {
errors += "Не указан пароль туннеля."
}
val rawHashes = parts[5].split(",")
val rawHashes = (modernParts?.hashes ?: parts[5]).split(",")
val hashes = rawHashes
.map { VkJoinLink.extractHash(it) }
.filter { it.isNotBlank() && it.length >= 16 }
@@ -284,6 +296,10 @@ class SettingsStore(context: Context) {
private val UPDATE_DIALOG_LAST_ACTION_VERSION = stringPreferencesKey("update_dialog_last_action_version")
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 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")
private val CLIENT_ID_CHECK_RESULTS = stringPreferencesKey("client_id_check_results")
private val INTERFACE_ROLE = stringPreferencesKey("interface_role")
@@ -297,7 +313,7 @@ class SettingsStore(context: Context) {
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>
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 -> booleanPreferencesKey(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}")
}
}
@@ -408,7 +424,10 @@ class SettingsStore(context: Context) {
prefs[getProfileKey(baseKey, profile)] ?: ""
}
val detailedLogs: Flow<Boolean> = dataStore.data.map { it[DETAILED_LOGS] ?: false }
val detailedLogs: Flow<Boolean> = dataStore.data.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DETAILED_LOGS, profile)] ?: false
}
// ═══ Пароли и Управление ═══
val connectionPassword: Flow<String> = dataStore.data.map { prefs ->
@@ -495,6 +514,10 @@ class SettingsStore(context: Context) {
val updateDialogLastActionVersion: Flow<String> = dataStore.data.map { it[UPDATE_DIALOG_LAST_ACTION_VERSION] ?: "" }
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 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 }
val interfaceRole: Flow<String> = dataStore.data.map { it[INTERFACE_ROLE] ?: "" }
val permissionOnboardingComplete: Flow<Boolean> = dataStore.data.map { prefs ->
prefs[PERMISSION_ONBOARDING_COMPLETE] ?: !prefs[INTERFACE_ROLE].isNullOrBlank()
@@ -592,6 +615,30 @@ class SettingsStore(context: Context) {
}
}
suspend fun saveMigrationNoticeV2Shown() {
dataStore.edit { prefs ->
prefs[MIGRATION_NOTICE_V2_SHOWN] = true
}
}
suspend fun saveDeployClientsSectionExpanded(expanded: Boolean) {
dataStore.edit { prefs ->
prefs[DEPLOY_CLIENTS_SECTION_EXPANDED] = expanded
}
}
suspend fun saveDeployOutboundSectionExpanded(expanded: Boolean) {
dataStore.edit { prefs ->
prefs[DEPLOY_OUTBOUND_SECTION_EXPANDED] = expanded
}
}
suspend fun saveDeployMigrationSectionExpanded(expanded: Boolean) {
dataStore.edit { prefs ->
prefs[DEPLOY_MIGRATION_SECTION_EXPANDED] = expanded
}
}
suspend fun saveActiveProfile(profile: Int) {
dataStore.edit { prefs ->
prefs[ACTIVE_PROFILE] = profile
@@ -629,11 +676,158 @@ class SettingsStore(context: Context) {
link = cleanLink,
targetProfile = freeProfile ?: activeProfile,
requiresConfirmation = freeProfile == null,
storeAsLink = prefs[getProfileKey(WDTT_LINK_MODE, activeProfile)] == true
storeAsLink = false
)
}.first()
}
suspend fun connectionLinkForProfile(profileIndex: Int): String {
val profile = profileIndex.coerceIn(0, VPN_PROFILE_COUNT - 1)
return dataStore.data.map { prefs ->
val storedLink = prefs[getProfileKey(WDTT_LINK, profile)].orEmpty()
val storedParts = WdttDeepLink.parse(storedLink)
val parts = storedParts ?: WdttLinkParts(
host = prefs[getProfileKey(PEER, profile)].orEmpty().trim(),
dtlsPort = prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000,
wgPort = prefs[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001,
localPort = prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000,
password = readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile),
hashes = prefs[getProfileKey(VK_HASHES, profile)].orEmpty()
)
val link = WdttTransferCodec.buildConnectionLink(parts)
val validation = WdttDeepLink.validate(link)
require(validation.canStartVpn) {
"Профиль VPN ${profile + 1} заполнен не полностью. Проверьте адрес, порты, пароль и VK-хеши."
}
link
}.first()
}
suspend fun exportAdminSettings(): String = dataStore.data.map { prefs ->
val profiles = JSONArray()
repeat(VPN_PROFILE_COUNT) { profile ->
profiles.put(JSONObject().apply {
put("wdttLink", prefs[getProfileKey(WDTT_LINK, profile)].orEmpty())
put("wdttLinkMode", prefs[getProfileKey(WDTT_LINK_MODE, profile)] ?: false)
put("peer", prefs[getProfileKey(PEER, profile)].orEmpty())
put("vkHashes", prefs[getProfileKey(VK_HASHES, profile)].orEmpty())
put("secondaryVkHash", prefs[getProfileKey(SECONDARY_VK_HASH, profile)].orEmpty())
put("workersPerHash", prefs[getProfileKey(WORKERS_PER_HASH, profile)] ?: 16)
put("protocol", prefs[getProfileKey(PROTOCOL, profile)] ?: "udp")
put("listenPort", prefs[getProfileKey(LISTEN_PORT, profile)] ?: 9000)
put("manualPortsEnabled", prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] ?: false)
put("serverDtlsPort", prefs[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000)
put("serverWgPort", prefs[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001)
put("sni", prefs[getProfileKey(SNI, profile)].orEmpty())
put("noDtls", prefs[getProfileKey(NO_DTLS, profile)] ?: false)
put("noDns", prefs[getProfileKey(NO_DNS, profile)] ?: false)
put("userAgent", prefs[getProfileKey(USER_AGENT, profile)].orEmpty())
put("connectionPassword", readSecret(prefs, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile))
put("deployIp", prefs[getProfileKey(DEPLOY_IP, profile)].orEmpty())
put("deployLogin", prefs[getProfileKey(DEPLOY_LOGIN, profile)].orEmpty())
put("deployPassword", readSecret(prefs, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, profile))
put("deploySshPort", prefs[getProfileKey(DEPLOY_SSH_PORT, profile)].orEmpty())
put("deployDns1", prefs[getProfileKey(DEPLOY_DNS1, profile)] ?: "1.1.1.1")
put("deployDns2", prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1")
put("deployMainPassword", readSecret(prefs, DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, profile))
put("deployAdminId", readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile))
put("deployBotToken", readSecret(prefs, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile))
put("proxyMode", prefs[getProfileKey(PROXY_MODE, profile)] ?: "tun")
put("proxyHost", prefs[getProfileKey(PROXY_HOST, profile)] ?: "127.0.0.1")
put("proxyPort", prefs[getProfileKey(PROXY_PORT, profile)] ?: 1080)
put("vkCallsPreflight", prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true)
put("captchaMode", prefs[getProfileKey(CAPTCHA_MODE, profile)] ?: "auto")
put("captchaSolveMethod", prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] ?: "auto")
put("captchaWbvSolveMethod", prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] ?: "auto")
put("isWhitelist", prefs[getProfileKey(IS_WHITELIST, profile)] ?: false)
put("blacklistApps", prefs[getProfileKey(BLACKLIST_APPS, profile)].orEmpty())
put("whitelistApps", prefs[getProfileKey(WHITELIST_APPS, profile)].orEmpty())
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")
})
}
JSONObject().apply {
put("format", "wdtt-plus-admin-settings")
put("version", 1)
put("activeProfile", (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1))
put("themeMode", prefs[THEME_MODE] ?: "system")
put("dynamicColor", prefs[IS_DYNAMIC_COLOR] ?: false)
put("themePalette", prefs[THEME_PALETTE] ?: "indigo")
put("showSystemApps", prefs[SHOW_SYSTEM_APPS] ?: false)
put("loggingEnabled", prefs[LOGGING_ENABLED] ?: true)
put("updateCheckIntervalHours", prefs[UPDATE_CHECK_INTERVAL_HOURS] ?: 12)
put("profiles", profiles)
put("outbound", exportSharedPreferences("wdtt_outbound_forms"))
}.toString()
}.first()
suspend fun importAdminSettings(settingsJson: String) {
val root = runCatching { JSONObject(settingsJson) }
.getOrElse { throw IllegalArgumentException("Расшифрованные настройки повреждены.") }
require(root.optString("format") == "wdtt-plus-admin-settings" && root.optInt("version") == 1) {
"Версия настроек не поддерживается."
}
val profiles = root.optJSONArray("profiles")
?: throw IllegalArgumentException("В файле нет профилей VPN.")
require(profiles.length() == VPN_PROFILE_COUNT) { "Файл должен содержать три профиля VPN." }
dataStore.edit { prefs ->
repeat(VPN_PROFILE_COUNT) { profile ->
val item = profiles.getJSONObject(profile)
prefs[getProfileKey(WDTT_LINK, profile)] = item.optString("wdttLink")
prefs[getProfileKey(WDTT_LINK_MODE, profile)] = item.optBoolean("wdttLinkMode")
prefs[getProfileKey(PEER, profile)] = item.optString("peer")
prefs[getProfileKey(VK_HASHES, profile)] = item.optString("vkHashes")
prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = item.optString("secondaryVkHash")
prefs[getProfileKey(VK_HASH_NEXT_SLOT, profile)] = 0
prefs.remove(getProfileKey(EXCLUDED_APPS, profile))
prefs[getProfileKey(WORKERS_PER_HASH, profile)] = item.optInt("workersPerHash", 16).coerceIn(1, 128)
prefs[getProfileKey(PROTOCOL, profile)] = item.optString("protocol", "udp").takeIf { it in setOf("udp", "tcp") } ?: "udp"
prefs[getProfileKey(LISTEN_PORT, profile)] = item.safePort("listenPort", 9000)
prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = item.optBoolean("manualPortsEnabled")
prefs[getProfileKey(SERVER_DTLS_PORT, profile)] = item.safePort("serverDtlsPort", 56000)
prefs[getProfileKey(SERVER_WG_PORT, profile)] = item.safePort("serverWgPort", 56001)
prefs[getProfileKey(SNI, profile)] = item.optString("sni")
prefs[getProfileKey(NO_DTLS, profile)] = item.optBoolean("noDtls")
prefs[getProfileKey(NO_DNS, profile)] = item.optBoolean("noDns")
prefs[getProfileKey(USER_AGENT, profile)] = item.optString("userAgent")
prefs.putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, item.optString("connectionPassword"), profile)
prefs[getProfileKey(DEPLOY_IP, profile)] = item.optString("deployIp")
prefs[getProfileKey(DEPLOY_LOGIN, profile)] = item.optString("deployLogin")
prefs.putSecret(DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_PASSWORD, item.optString("deployPassword"), profile)
prefs[getProfileKey(DEPLOY_SSH_PORT, profile)] = item.optString("deploySshPort")
prefs[getProfileKey(DEPLOY_DNS1, profile)] = item.optString("deployDns1", "1.1.1.1")
prefs[getProfileKey(DEPLOY_DNS2, profile)] = item.optString("deployDns2", "1.0.0.1")
prefs.putSecret(DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, item.optString("deployMainPassword"), profile)
prefs.putSecret(DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, item.optString("deployAdminId"), profile)
prefs.putSecret(DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, item.optString("deployBotToken"), profile)
prefs[getProfileKey(PROXY_MODE, profile)] = item.optString("proxyMode", "tun")
prefs[getProfileKey(PROXY_HOST, profile)] = item.optString("proxyHost", "127.0.0.1")
prefs[getProfileKey(PROXY_PORT, profile)] = item.safePort("proxyPort", 1080)
prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] = item.optBoolean("vkCallsPreflight", true)
prefs[getProfileKey(CAPTCHA_MODE, profile)] = item.optString("captchaMode", "auto")
prefs[getProfileKey(CAPTCHA_SOLVE_METHOD, profile)] = item.optString("captchaSolveMethod", "auto")
prefs[getProfileKey(CAPTCHA_WBV_SOLVE_METHOD, profile)] = item.optString("captchaWbvSolveMethod", "auto")
prefs[getProfileKey(IS_WHITELIST, profile)] = item.optBoolean("isWhitelist")
prefs[getProfileKey(BLACKLIST_APPS, profile)] = item.optString("blacklistApps")
prefs[getProfileKey(WHITELIST_APPS, profile)] = item.optString("whitelistApps")
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")
}
prefs[ACTIVE_PROFILE] = root.optInt("activeProfile", 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
prefs[THEME_MODE] = root.optString("themeMode", "system")
prefs[IS_DYNAMIC_COLOR] = root.optBoolean("dynamicColor")
prefs[THEME_PALETTE] = root.optString("themePalette", "indigo")
prefs[SHOW_SYSTEM_APPS] = root.optBoolean("showSystemApps")
prefs[LOGGING_ENABLED] = root.optBoolean("loggingEnabled", true)
prefs[UPDATE_CHECK_INTERVAL_HOURS] = root.optInt("updateCheckIntervalHours", 12)
prefs[INTERFACE_ROLE] = "admin"
}
importSharedPreferences("wdtt_outbound_forms", root.optJSONObject("outbound") ?: JSONObject())
}
suspend fun applyWdttDeepLink(plan: WdttDeepLinkApplyPlan): WdttDeepLinkApplyResult? {
val parts = WdttDeepLink.parse(plan.link) ?: return null
val profile = plan.targetProfile.coerceIn(0, VPN_PROFILE_COUNT - 1)
@@ -942,10 +1136,15 @@ class SettingsStore(context: Context) {
private fun Preferences.isTunnelProfileEmpty(profile: Int): Boolean {
val hasLink = (this[getProfileKey(WDTT_LINK, profile)] ?: "").isNotBlank()
val hasManualTunnel = (this[getProfileKey(PEER, profile)] ?: "").isNotBlank() &&
(this[getProfileKey(VK_HASHES, profile)] ?: "").split(",").any { it.isNotBlank() } &&
readSecret(this, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile).isNotBlank()
return !hasLink && !hasManualTunnel
val hasManualData = (this[getProfileKey(PEER, profile)] ?: "").isNotBlank() ||
(this[getProfileKey(VK_HASHES, profile)] ?: "").split(",").any { it.isNotBlank() } ||
(this[getProfileKey(SECONDARY_VK_HASH, profile)] ?: "").isNotBlank() ||
readSecret(this, CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, profile).isNotBlank() ||
(this[getProfileKey(MANUAL_PORTS_ENABLED, profile)] == true &&
((this[getProfileKey(SERVER_DTLS_PORT, profile)] ?: 56000) != 56000 ||
(this[getProfileKey(SERVER_WG_PORT, profile)] ?: 56001) != 56001 ||
(this[getProfileKey(LISTEN_PORT, profile)] ?: 9000) != 9000))
return !hasLink && !hasManualData
}
private fun MutablePreferences.clearManualTunnelFields(profile: Int) {
@@ -973,4 +1172,38 @@ class SettingsStore(context: Context) {
}
}
}
private fun exportSharedPreferences(name: String): JSONObject {
val result = JSONObject()
appContext.getSharedPreferences(name, Context.MODE_PRIVATE).all.forEach { (key, value) ->
when (value) {
is String, is Boolean, is Int, is Long, is Float -> result.put(key, value)
is Set<*> -> result.put(key, JSONArray(value.filterIsInstance<String>()))
}
}
return result
}
private fun importSharedPreferences(name: String, json: JSONObject) {
val editor = appContext.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear()
val keys = json.keys()
while (keys.hasNext()) {
val key = keys.next()
when (val value = json.get(key)) {
is String -> editor.putString(key, value)
is Boolean -> editor.putBoolean(key, value)
is Int -> editor.putInt(key, value)
is Long -> editor.putLong(key, value)
is Double -> editor.putFloat(key, value.toFloat())
is JSONArray -> editor.putStringSet(
key,
(0 until value.length()).mapNotNull { value.optString(it).takeIf(String::isNotBlank) }.toSet()
)
}
}
editor.apply()
}
private fun JSONObject.safePort(name: String, fallback: Int): Int =
optInt(name, fallback).takeIf { it in 1..65535 } ?: fallback
}
@@ -0,0 +1,187 @@
package com.wdtt.plus
import org.json.JSONObject
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.net.URLDecoder
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.security.SecureRandom
import java.util.Base64
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
private const val TRANSFER_FORMAT = "wdtt-plus-transfer"
private const val TRANSFER_VERSION = 1
private const val ADMIN_KIND = "admin-settings"
private const val PBKDF2_ITERATIONS = 210_000
private const val KEY_BITS = 256
private const val GCM_TAG_BITS = 128
data class AdminTransferPreview(
val createdAt: Long,
val profileCount: Int,
val sourceVersion: String
)
object WdttTransferCodec {
private val random = SecureRandom()
fun buildConnectionLink(parts: WdttLinkParts): String {
val values = linkedMapOf(
"v" to "1",
"host" to parts.host,
"dtls" to parts.dtlsPort.toString(),
"wg" to parts.wgPort.toString(),
"local" to parts.localPort.toString(),
"password" to parts.password,
"hashes" to parts.hashes
)
return "wdtt://connect?" + values.entries.joinToString("&") { (key, value) ->
"${encode(key)}=${encode(value)}"
}
}
fun parseConnectionLink(value: String): WdttLinkParts? = runCatching {
parseConnectionLinkUnsafe(value)
}.getOrNull()
private fun parseConnectionLinkUnsafe(value: String): WdttLinkParts? {
val clean = extractWdttLink(value) ?: return null
if (!clean.startsWith("wdtt://connect?", ignoreCase = true)) return null
val query = clean.substringAfter('?', "")
val values = query.split('&')
.mapNotNull { token ->
val separator = token.indexOf('=')
if (separator <= 0) null
else decode(token.substring(0, separator)) to decode(token.substring(separator + 1))
}
.toMap()
if (values["v"] != "1") return null
return WdttLinkParts(
host = values["host"].orEmpty(),
dtlsPort = values["dtls"]?.toIntOrNull() ?: return null,
wgPort = values["wg"]?.toIntOrNull() ?: return null,
localPort = values["local"]?.toIntOrNull() ?: return null,
password = values["password"].orEmpty(),
hashes = values["hashes"].orEmpty()
)
}
fun extractWdttLink(value: String): String? {
val start = value.indexOf("wdtt://", ignoreCase = true)
if (start < 0) return null
return value.substring(start)
.substringBeforeAny(charArrayOf('\n', '\r', '\t', ' '))
.trimEnd('.', ',', ';', ')', ']', '}', '»', '"', '\'')
.takeIf { it.isNotBlank() }
}
fun encryptAdminSettings(settingsJson: String, password: CharArray): String {
require(password.size >= 8) { "Пароль должен содержать не меньше 8 символов." }
val salt = ByteArray(16).also(random::nextBytes)
val iv = ByteArray(12).also(random::nextBytes)
val key = deriveKey(password, salt, PBKDF2_ITERATIONS)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv))
val compressed = gzip(settingsJson.toByteArray(StandardCharsets.UTF_8))
val encrypted = cipher.doFinal(compressed)
key.encoded?.fill(0)
return JSONObject()
.put("format", TRANSFER_FORMAT)
.put("version", TRANSFER_VERSION)
.put("kind", ADMIN_KIND)
.put("createdAt", System.currentTimeMillis())
.put("sourceVersion", BuildConfig.VERSION_NAME)
.put("kdf", "PBKDF2-HMAC-SHA256")
.put("iterations", PBKDF2_ITERATIONS)
.put("salt", Base64.getEncoder().encodeToString(salt))
.put("iv", Base64.getEncoder().encodeToString(iv))
.put("data", Base64.getEncoder().encodeToString(encrypted))
.toString()
}
fun isAdminTransfer(value: String): Boolean = runCatching {
val json = JSONObject(value.trim())
json.optString("format") == TRANSFER_FORMAT &&
json.optInt("version") == TRANSFER_VERSION &&
json.optString("kind") == ADMIN_KIND
}.getOrDefault(false)
fun documentFormat(value: String): String? = runCatching {
JSONObject(value.trim()).optString("format").takeIf { it.isNotBlank() }
}.getOrNull()
fun previewAdminTransfer(value: String): AdminTransferPreview {
val json = requireAdminEnvelope(value)
return AdminTransferPreview(
createdAt = json.optLong("createdAt"),
profileCount = 3,
sourceVersion = json.optString("sourceVersion", "неизвестно")
)
}
fun decryptAdminSettings(value: String, password: CharArray): String {
require(password.isNotEmpty()) { "Введите пароль файла." }
val json = requireAdminEnvelope(value)
val iterations = json.optInt("iterations", 0)
require(iterations in 100_000..1_000_000) { "Некорректные параметры защиты файла." }
val salt = Base64.getDecoder().decode(json.getString("salt"))
val iv = Base64.getDecoder().decode(json.getString("iv"))
val encrypted = Base64.getDecoder().decode(json.getString("data"))
require(salt.size == 16 && iv.size == 12) { "Файл передачи повреждён." }
val key = deriveKey(password, salt, iterations)
return try {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(GCM_TAG_BITS, iv))
ungzip(cipher.doFinal(encrypted)).toString(StandardCharsets.UTF_8)
} catch (_: Exception) {
throw IllegalArgumentException("Неверный пароль или файл повреждён.")
} finally {
key.encoded?.fill(0)
}
}
private fun requireAdminEnvelope(value: String): JSONObject {
val json = runCatching { JSONObject(value.trim()) }
.getOrElse { throw IllegalArgumentException("Файл передачи повреждён или имеет неизвестный формат.") }
require(json.optString("format") == TRANSFER_FORMAT) { "Это не файл передачи WDTT Plus." }
require(json.optInt("version") == TRANSFER_VERSION) { "Версия файла пока не поддерживается." }
require(json.optString("kind") == ADMIN_KIND) { "В файле нет настроек администратора." }
return json
}
private fun deriveKey(password: CharArray, salt: ByteArray, iterations: Int): SecretKeySpec {
val spec = PBEKeySpec(password, salt, iterations, KEY_BITS)
return try {
val bytes = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded
SecretKeySpec(bytes, "AES")
} finally {
spec.clearPassword()
}
}
private fun gzip(value: ByteArray): ByteArray = ByteArrayOutputStream().use { output ->
GZIPOutputStream(output).use { it.write(value) }
output.toByteArray()
}
private fun ungzip(value: ByteArray): ByteArray =
GZIPInputStream(ByteArrayInputStream(value)).use { it.readBytes() }
private fun encode(value: String): String = URLEncoder.encode(value, StandardCharsets.UTF_8.name())
.replace("+", "%20")
private fun decode(value: String): String = URLDecoder.decode(value, StandardCharsets.UTF_8.name())
private fun String.substringBeforeAny(delimiters: CharArray): String {
val index = indexOfFirst { it in delimiters }
return if (index < 0) this else substring(0, index)
}
}
@@ -0,0 +1,246 @@
package com.wdtt.plus
import android.content.Context
import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ImageDecoder
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.core.content.FileProvider
import androidx.core.content.ContextCompat
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.InvertedLuminanceSource
import com.google.zxing.MultiFormatReader
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import java.io.File
import java.io.ByteArrayOutputStream
import java.nio.charset.StandardCharsets
object TransferFiles {
private const val MAX_TRANSFER_BYTES = 5 * 1024 * 1024
const val MAX_QR_TEXT_BYTES = 2_600
fun createQrBitmap(context: Context, text: String, size: Int = 900): Bitmap {
require(text.toByteArray(StandardCharsets.UTF_8).size <= MAX_QR_TEXT_BYTES) {
"Эти данные слишком велики для одного QR-кода. Передайте их файлом."
}
val icon = loadAppIcon(context)
val highCorrection = runCatching {
createQrMatrix(text, size, ErrorCorrectionLevel.H)
}.getOrNull()
if (highCorrection != null) {
val plain = renderQr(highCorrection, size)
val branded = drawCenteredIcon(plain, icon)
if (runCatching { decodeQrBitmap(branded) }.getOrNull() == text) return branded
}
val compact = renderQr(createQrMatrix(text, size, ErrorCorrectionLevel.L), size)
return drawFooter(compact, icon)
}
private fun createQrMatrix(text: String, size: Int, correction: ErrorCorrectionLevel) =
QRCodeWriter().encode(
text,
BarcodeFormat.QR_CODE,
size,
size,
mapOf(
com.google.zxing.EncodeHintType.CHARACTER_SET to "UTF-8",
com.google.zxing.EncodeHintType.ERROR_CORRECTION to correction,
com.google.zxing.EncodeHintType.MARGIN to 2
)
)
private fun renderQr(matrix: com.google.zxing.common.BitMatrix, size: Int): Bitmap {
val pixels = IntArray(size * size)
for (y in 0 until size) {
val offset = y * size
for (x in 0 until size) {
pixels[offset + x] = if (matrix[x, y]) Color.BLACK else Color.WHITE
}
}
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply {
setPixels(pixels, 0, size, 0, 0, size, size)
}
}
private fun drawCenteredIcon(qr: Bitmap, icon: Bitmap): Bitmap {
val result = qr.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(result)
val iconSize = (qr.width * 0.075f).toInt()
val plateSize = (iconSize * 1.22f).toInt()
val centerX = qr.width / 2f
val centerY = qr.height / 2f
canvas.drawCircle(
centerX,
centerY,
plateSize / 2f,
Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE }
)
val iconLeft = (qr.width - iconSize) / 2f
val iconTop = (qr.height - iconSize) / 2f
val iconBounds = RectF(iconLeft, iconTop, iconLeft + iconSize, iconTop + iconSize)
canvas.save()
canvas.clipPath(Path().apply { addOval(iconBounds, Path.Direction.CW) })
canvas.drawBitmap(icon, null, iconBounds, Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG))
canvas.restore()
return result
}
private fun loadAppIcon(context: Context): Bitmap {
val drawable = ContextCompat.getDrawable(context, R.mipmap.ic_launcher)?.mutate()
?: throw IllegalStateException("Не удалось загрузить иконку WDTT Plus.")
val size = 192
return Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).also { bitmap ->
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, size, size)
drawable.draw(canvas)
}
}
private fun drawFooter(qr: Bitmap, icon: Bitmap): Bitmap {
val footerHeight = (qr.width * 0.13f).toInt()
val result = Bitmap.createBitmap(qr.width, qr.height + footerHeight, Bitmap.Config.ARGB_8888)
val canvas = Canvas(result)
canvas.drawColor(Color.WHITE)
canvas.drawBitmap(qr, 0f, 0f, null)
val iconSize = (footerHeight * 0.56f).toInt()
val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.rgb(35, 35, 45)
textSize = footerHeight * 0.30f
typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
}
val label = "WDTT Plus"
val spacing = footerHeight * 0.14f
val groupWidth = iconSize + spacing + textPaint.measureText(label)
val iconLeft = (qr.width - groupWidth) / 2f
val iconTop = qr.height + (footerHeight - iconSize) / 2f
canvas.drawBitmap(icon, null, RectF(iconLeft, iconTop, iconLeft + iconSize, iconTop + iconSize), Paint(Paint.ANTI_ALIAS_FLAG))
val textX = iconLeft + iconSize + spacing
val textY = qr.height + footerHeight / 2f - (textPaint.ascent() + textPaint.descent()) / 2f
canvas.drawText(label, textX, textY, textPaint)
return result
}
fun decodeQrImage(context: Context, uri: Uri): String {
val source = ImageDecoder.createSource(context.contentResolver, uri)
val bitmap = ImageDecoder.decodeBitmap(source) { decoder, info, _ ->
decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE
val width = info.size.width
val height = info.size.height
val longest = maxOf(width, height)
if (longest > 2400) {
val scale = 2400f / longest
decoder.setTargetSize((width * scale).toInt(), (height * scale).toInt())
}
}.copy(Bitmap.Config.ARGB_8888, false)
return decodeQrBitmap(bitmap)
}
private fun decodeQrBitmap(bitmap: Bitmap): String {
val pixels = IntArray(bitmap.width * bitmap.height)
bitmap.getPixels(pixels, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)
val sourcePixels = RGBLuminanceSource(bitmap.width, bitmap.height, pixels)
val hints = mapOf(
DecodeHintType.POSSIBLE_FORMATS to listOf(BarcodeFormat.QR_CODE),
DecodeHintType.TRY_HARDER to true,
DecodeHintType.CHARACTER_SET to "UTF-8"
)
val reader = MultiFormatReader().apply { setHints(hints) }
return runCatching {
reader.decodeWithState(BinaryBitmap(HybridBinarizer(sourcePixels))).text
}.recoverCatching {
reader.reset()
reader.setHints(hints)
reader.decodeWithState(BinaryBitmap(HybridBinarizer(InvertedLuminanceSource(sourcePixels)))).text
}.getOrElse {
throw IllegalArgumentException("На выбранном изображении не найден читаемый QR-код.")
}.also { reader.reset() }
}
fun readText(context: Context, uri: Uri): String {
val bytes = context.contentResolver.openInputStream(uri)?.use { input ->
val output = ByteArrayOutputStream()
val buffer = ByteArray(8192)
var total = 0
while (true) {
val count = input.read(buffer)
if (count < 0) break
total += count
require(total <= MAX_TRANSFER_BYTES) { "Файл передачи слишком большой." }
output.write(buffer, 0, count)
}
output.toByteArray()
} ?: throw IllegalArgumentException("Не удалось открыть выбранный файл.")
return bytes.toString(StandardCharsets.UTF_8).removePrefix("\uFEFF").trim()
}
fun writeTransferText(context: Context, fileName: String, text: String): Uri {
val directory = File(context.cacheDir, "transfers").apply { mkdirs() }
directory.listFiles()?.forEach { file ->
if (System.currentTimeMillis() - file.lastModified() > 24L * 60L * 60L * 1000L) file.delete()
}
val safeName = fileName.toSafeTransferFileName("WDTT-Plus-transfer")
val file = File(directory, safeName).apply { writeText(text, Charsets.UTF_8) }
return FileProvider.getUriForFile(context, "${context.packageName}.files", file)
}
fun writeQrPng(context: Context, fileName: String, bitmap: Bitmap): Uri {
val directory = File(context.cacheDir, "transfers").apply { mkdirs() }
val safeName = fileName.toSafeTransferFileName("WDTT-Plus-QR.png")
val file = File(directory, safeName)
file.outputStream().use { output ->
require(bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)) { "Не удалось создать изображение QR-кода." }
}
return FileProvider.getUriForFile(context, "${context.packageName}.files", file)
}
fun saveQrToGallery(context: Context, fileName: String, bitmap: Bitmap): Uri {
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
put(MediaStore.Images.Media.MIME_TYPE, "image/png")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/WDTT Plus")
put(MediaStore.Images.Media.IS_PENDING, 1)
}
}
val collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val uri = context.contentResolver.insert(collection, values)
?: throw IllegalStateException("Не удалось создать изображение в галерее.")
try {
context.contentResolver.openOutputStream(uri)?.use { output ->
require(bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)) {
"Не удалось сохранить QR-код."
}
} ?: throw IllegalStateException("Не удалось открыть файл изображения.")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values.clear()
values.put(MediaStore.Images.Media.IS_PENDING, 0)
context.contentResolver.update(uri, values, null, null)
}
return uri
} catch (error: Exception) {
context.contentResolver.delete(uri, null, null)
throw error
}
}
private fun String.toSafeTransferFileName(fallback: String): String =
replace(Regex("[^\\p{L}\\p{N}._-]+"), "-")
.replace(Regex("-+"), "-")
.trim('-', '.', '_')
.ifBlank { fallback }
}
@@ -979,6 +979,19 @@ object TunnelManager {
updateLog("dtls_ok", "[DTLS] Соединение установлено ✓", 1, false)
lineTrim.contains("Активна ✓") ->
updateLog("ready", "[READY] Туннель готов к работе ✓", 2, false)
lineTrim.contains("Ошибка конфига", true) &&
lineTrim.contains("чтение ответа конфига", true) &&
(lineTrim.contains("timeout", true) || lineTrim.contains("context deadline exceeded", true)) ->
updateLog(
"worker_config_timeout_active",
if (activeWorkers.value > 0) {
"[ПОТОК] Один канал не получил конфигурацию вовремя; активных=${activeWorkers.value}, работа продолжается"
} else {
"[ПОТОК] Один канал не получил конфигурацию вовремя; пробуем через другие каналы"
},
3,
false
)
isError -> {
val errorKey = when {
File diff suppressed because it is too large. Load diff
@@ -7,7 +7,6 @@ import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
@@ -122,7 +121,10 @@ private fun AppItem.matchesVpnDetectionApp(): Boolean {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ExceptionsTab() {
fun ExceptionsTab(
firstVisibleItemIndex: MutableIntState = rememberSaveable { mutableIntStateOf(0) },
firstVisibleItemScrollOffset: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
) {
val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
@@ -350,7 +352,10 @@ fun ExceptionsTab() {
CircularProgressIndicator()
}
} else {
val listState = rememberLazyListState()
val listState = rememberRememberedLazyListState(
firstVisibleItemIndex,
firstVisibleItemScrollOffset
)
if (filteredApps.isEmpty()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
@@ -1,13 +1,16 @@
package com.wdtt.plus.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.background
import androidx.compose.foundation.border
@@ -45,6 +48,7 @@ import kotlin.math.roundToInt
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Share
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
@@ -65,6 +69,7 @@ fun FloatingToolbar(
onFingerprintChange: (String) -> Unit,
activeClientIds: String,
onClientIdsChange: (String) -> Unit,
onTransferRequested: () -> Unit,
modifier: Modifier = Modifier
) {
val configuration = LocalConfiguration.current
@@ -185,6 +190,7 @@ fun FloatingToolbar(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.animateContentSize(animationSpec = spring(stiffness = Spring.StiffnessMediumLow))
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
@@ -241,6 +247,17 @@ fun FloatingToolbar(
}
}
OutlinedButton(
onClick = {
onTransferRequested()
},
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
shape = RoundedCornerShape(12.dp)
) {
Icon(Icons.Filled.Share, contentDescription = null, modifier = Modifier.size(18.dp))
Text(" Передать или получить", fontSize = 12.sp)
}
HorizontalDivider(
modifier = Modifier.padding(vertical = 4.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
@@ -339,8 +356,12 @@ fun FloatingToolbar(
)
}
AnimatedVisibility(visible = showPalettes) {
Column {
AnimatedVisibility(
visible = showPalettes,
enter = expandVertically(animationSpec = spring(stiffness = Spring.StiffnessMediumLow)) + fadeIn(),
exit = shrinkVertically(animationSpec = spring(stiffness = Spring.StiffnessMediumLow)) + fadeOut()
) {
Column(modifier = Modifier.fillMaxWidth()) {
HorizontalDivider(
modifier = Modifier.padding(vertical = 4.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
+21 -3
View File
@@ -60,7 +60,9 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
@@ -104,6 +106,7 @@ private const val ReleasesUrl = "https://github.com/Ivan4537/WDTT-Plus/releases"
private const val IssuesUrl = "https://github.com/Ivan4537/WDTT-Plus/issues/new/choose"
private const val DeveloperProfileUrl = "https://github.com/Ivan4537"
private const val RepositoryUrl = "https://github.com/Ivan4537/WDTT-Plus"
private const val ChangelogUrl = "$RepositoryUrl/blob/main/CHANGELOG.md"
private const val DonateUrl = "https://yoomoney.ru/to/410012216336438"
private const val OriginalDonateUrl = "https://yoomoney.ru/to/4100119505530465/"
private val DonateActionButtonColor = Color(0xFF00AEA5)
@@ -165,12 +168,13 @@ private fun openUrlInBrowser(context: Context, url: String) {
@Composable
fun InfoTab(
actionsExpandedState: MutableState<Boolean> = rememberSaveable { mutableStateOf(true) },
projectExpandedState: MutableState<Boolean> = rememberSaveable { mutableStateOf(true) }
projectExpandedState: MutableState<Boolean> = rememberSaveable { mutableStateOf(true) },
scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
val infoScrollState = rememberScrollState()
val infoScrollState = rememberRememberedScrollState(scrollPosition)
val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() }
var actionsSectionY by remember { mutableStateOf(0f) }
var projectSectionY by remember { mutableStateOf(0f) }
@@ -377,7 +381,7 @@ fun InfoTab(
ExpandableSectionCard(
title = "О проекте",
itemCount = "3 ссылки",
itemCount = "4 ссылки",
expanded = projectExpanded,
modifier = Modifier.onGloballyPositioned { projectSectionY = it.positionInParent().y },
onToggle = {
@@ -440,6 +444,20 @@ fun InfoTab(
)
}
)
ProjectLinkRow(
title = "История изменений",
subtitle = "Что менялось в версиях WDTT Plus",
onClick = { openUrlInBrowser(context, ChangelogUrl) },
icon = {
Icon(
imageVector = Icons.Default.Update,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp)
)
}
)
}
Spacer(modifier = Modifier.height(20.dp))
@@ -9,7 +9,6 @@ import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
@@ -17,6 +16,7 @@ import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
@@ -34,13 +34,19 @@ import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LogsTab() {
fun LogsTab(
firstVisibleItemIndex: MutableIntState = rememberSaveable { mutableIntStateOf(0) },
firstVisibleItemScrollOffset: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
) {
val context = LocalContext.current
val settingsStore = remember { SettingsStore(context) }
val loggingEnabled by settingsStore.loggingEnabled.collectAsStateWithLifecycle(initialValue = true)
val scope = rememberCoroutineScope()
val currentLogs by TunnelManager.logs.collectAsStateWithLifecycle()
val listState = rememberLazyListState()
val listState = rememberRememberedLazyListState(
firstVisibleItemIndex,
firstVisibleItemScrollOffset
)
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
// Toolbar
@@ -0,0 +1,82 @@
package com.wdtt.plus.ui
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull
@Composable
fun rememberRememberedScrollState(savedPosition: MutableIntState): ScrollState {
val scrollState = rememberScrollState(initial = savedPosition.intValue)
var restored by remember { mutableStateOf(false) }
LaunchedEffect(scrollState) {
val target = savedPosition.intValue
if (target > 0) {
withTimeoutOrNull(900) {
snapshotFlow { scrollState.maxValue }
.filter { maxValue -> maxValue >= target }
.first()
}
scrollState.scrollTo(target.coerceIn(0, scrollState.maxValue))
}
restored = true
}
LaunchedEffect(scrollState, restored) {
if (!restored) return@LaunchedEffect
snapshotFlow { scrollState.value }.collect { position ->
savedPosition.intValue = position
}
}
return scrollState
}
@Composable
fun rememberRememberedLazyListState(
savedFirstVisibleItemIndex: MutableIntState,
savedFirstVisibleItemScrollOffset: MutableIntState
): LazyListState {
val listState = rememberLazyListState(
initialFirstVisibleItemIndex = savedFirstVisibleItemIndex.intValue,
initialFirstVisibleItemScrollOffset = savedFirstVisibleItemScrollOffset.intValue
)
var restored by remember { mutableStateOf(false) }
LaunchedEffect(listState) {
val targetIndex = savedFirstVisibleItemIndex.intValue
val targetOffset = savedFirstVisibleItemScrollOffset.intValue
if (targetIndex > 0 || targetOffset > 0) {
snapshotFlow { listState.layoutInfo.totalItemsCount }
.filter { itemCount -> itemCount > 0 }
.first()
val itemCount = listState.layoutInfo.totalItemsCount
listState.scrollToItem(targetIndex.coerceAtMost(itemCount - 1), targetOffset)
}
restored = true
}
LaunchedEffect(listState, restored) {
if (!restored) return@LaunchedEffect
snapshotFlow {
listState.firstVisibleItemIndex to listState.firstVisibleItemScrollOffset
}.collect { (index, offset) ->
savedFirstVisibleItemIndex.intValue = index
savedFirstVisibleItemScrollOffset.intValue = offset
}
}
return listState
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,13 @@
package com.wdtt.plus.ui
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.lifecycle.ViewModel
import com.wdtt.plus.ServerAdminState
class ServerClientsViewModel : ViewModel() {
val serverState = mutableStateOf<ServerAdminState?>(null)
val clientSearch = mutableStateOf("")
val selectedClientIndex = mutableIntStateOf(0)
var targetKey: String = ""
}
@@ -90,7 +90,9 @@ private fun isValidTunnelHost(value: String): Boolean {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsTab() {
fun SettingsTab(
scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
@@ -99,13 +101,18 @@ fun SettingsTab() {
CompositionLocalProvider(
LocalDensity provides Density(currentDensity.density, fontScale = 1f)
) {
SettingsTabContent(context, scope, settingsStore)
SettingsTabContent(context, scope, settingsStore, scrollPosition)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsTabContent(context: android.content.Context, scope: kotlinx.coroutines.CoroutineScope, settingsStore: SettingsStore) {
fun SettingsTabContent(
context: android.content.Context,
scope: kotlinx.coroutines.CoroutineScope,
settingsStore: SettingsStore,
scrollPosition: MutableIntState
) {
val savedConnectionPassword by settingsStore.connectionPassword.collectAsStateWithLifecycle(initialValue = "")
val savedManualPortsEnabled by settingsStore.manualPortsEnabled.collectAsStateWithLifecycle(initialValue = false)
val savedServerDtlsPort by settingsStore.serverDtlsPort.collectAsStateWithLifecycle(initialValue = 56000)
@@ -288,7 +295,7 @@ fun SettingsTabContent(context: android.content.Context, scope: kotlinx.coroutin
}
}
val scrollState = rememberScrollState()
val scrollState = rememberRememberedScrollState(scrollPosition)
val isPeerValid = isValidTunnelHost(peerInput)
val isHashesValid = combinedHashes.isNotBlank()
@@ -0,0 +1,506 @@
package com.wdtt.plus.ui
import android.Manifest
import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.FileOpen
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.QrCode2
import androidx.compose.material.icons.filled.SaveAlt
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
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 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 kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
private enum class AdminExportAction { Qr, File }
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun TransferCenterDialog(
settingsStore: SettingsStore,
activeProfile: Int,
isAdmin: Boolean,
onIncomingContent: (String) -> Unit,
onDismiss: () -> Unit
) {
val context = androidx.compose.ui.platform.LocalContext.current
val scope = rememberCoroutineScope()
var busy by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
var qrData by remember { mutableStateOf<Pair<String, Bitmap>?>(null) }
var adminAction by remember { mutableStateOf<AdminExportAction?>(null) }
fun runCatchingUi(block: suspend () -> Unit) {
busy = true
error = null
scope.launch {
runCatching { block() }
.onFailure { error = it.message ?: "Не удалось выполнить передачу." }
busy = false
}
}
val cameraLauncher = rememberLauncherForActivityResult(ScanContract()) { result ->
result.contents?.takeIf { it.isNotBlank() }?.let(onIncomingContent)
}
val galleryLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) runCatchingUi {
val text = withContext(Dispatchers.IO) { TransferFiles.decodeQrImage(context, uri) }
onIncomingContent(text)
}
}
val fileLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
if (uri != null) runCatchingUi {
val text = withContext(Dispatchers.IO) { TransferFiles.readText(context, uri) }
onIncomingContent(text)
}
}
AlertDialog(
onDismissRequest = { if (!busy) onDismiss() },
properties = DialogProperties(usePlatformDefaultWidth = false),
modifier = Modifier.fillMaxWidth(0.94f),
text = {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Box(modifier = Modifier.fillMaxWidth()) {
IconButton(
onClick = onDismiss,
enabled = !busy,
modifier = Modifier.align(androidx.compose.ui.Alignment.CenterEnd).size(32.dp)
) {
Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
}
}
Text("Получение VPN", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
FlowRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
TransferButton("Камера", Icons.Default.CameraAlt, busy) {
cameraLauncher.launch(
ScanOptions()
.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
.setPrompt("Наведите камеру на QR-код WDTT Plus")
.setBeepEnabled(false)
.setCaptureActivity(QrCaptureActivity::class.java)
.setOrientationLocked(false)
)
}
TransferButton("Галерея", Icons.Default.Image, busy) { galleryLauncher.launch("image/*") }
TransferButton("Файл", Icons.Default.FileOpen, busy) { fileLauncher.launch("*/*") }
}
HorizontalDivider()
Text("Передача VPN ${activeProfile + 1}", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"Ссылка содержит пароль подключения и VK-хеши. Передавайте её только тому, кому доверяете.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
FlowRow(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
TransferButton("QR", Icons.Default.QrCode2, busy) {
runCatchingUi {
val link = settingsStore.connectionLinkForProfile(activeProfile)
val bitmap = withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, link) }
qrData = "VPN ${activeProfile + 1}" to bitmap
}
}
TransferButton("Ссылка", Icons.Default.Share, busy) {
runCatchingUi {
shareText(context, settingsStore.connectionLinkForProfile(activeProfile))
}
}
TransferButton("Файл", Icons.AutoMirrored.Filled.InsertDriveFile, busy) {
runCatchingUi {
val link = settingsStore.connectionLinkForProfile(activeProfile)
val uri = withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(context, "WDTT-Plus-VPN-${activeProfile + 1}.wdtt", link)
}
shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать подключение WDTT Plus")
}
}
}
if (isAdmin) {
HorizontalDivider()
Text("Настройки администратора", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"Все три VPN-профиля, параметры деплоя, пароли, токен бота, исключения и настройки выхода. Данные шифруются указанным паролем.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
OutlinedButton(
onClick = { adminAction = AdminExportAction.Qr },
enabled = !busy,
modifier = Modifier.weight(1f)
) {
Icon(Icons.Default.QrCode2, null, Modifier.size(18.dp))
Text(" QR")
}
OutlinedButton(
onClick = { adminAction = AdminExportAction.File },
enabled = !busy,
modifier = Modifier.weight(1f)
) {
Icon(Icons.AutoMirrored.Filled.InsertDriveFile, null, Modifier.size(18.dp))
Text(" Файл")
}
}
}
error?.let {
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall)
}
if (busy) Text("Подготавливаю…", style = MaterialTheme.typography.bodySmall)
}
},
confirmButton = {}
)
adminAction?.let { action ->
AdminExportPasswordDialog(
onDismiss = { adminAction = null },
onConfirm = { password ->
adminAction = null
runCatchingUi {
val plain = settingsStore.exportAdminSettings()
val encrypted = try {
withContext(Dispatchers.Default) {
WdttTransferCodec.encryptAdminSettings(plain, password)
}
} finally {
password.fill('\u0000')
}
when (action) {
AdminExportAction.Qr -> {
val bitmap = withContext(Dispatchers.Default) { TransferFiles.createQrBitmap(context, encrypted) }
qrData = "Настройки администратора" to bitmap
}
AdminExportAction.File -> {
val stamp = SimpleDateFormat("yyyyMMdd-HHmm", Locale.US).format(Date())
val uri = withContext(Dispatchers.IO) {
TransferFiles.writeTransferText(context, "WDTT-Plus-admin-$stamp.wdtt-backup", encrypted)
}
shareUri(context, uri, "application/vnd.wdtt.plus.transfer", "Передать настройки WDTT Plus")
}
}
}
}
)
}
qrData?.let { (title, bitmap) ->
QrDisplayDialog(
title = title,
bitmap = bitmap,
onDismiss = { qrData = null },
onShare = {
runCatchingUi {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
val fileName = "WDTT-Plus-QR-${title.safeQrFileName()}-$stamp.png"
val uri = withContext(Dispatchers.IO) {
TransferFiles.writeQrPng(context, fileName, bitmap)
}
shareUri(context, uri, "image/png", "Передать QR-код WDTT Plus")
}
},
onSave = {
scope.launch {
val stamp = SimpleDateFormat("yyyyMMdd-HHmmss", Locale.US).format(Date())
runCatching {
withContext(Dispatchers.IO) {
TransferFiles.saveQrToGallery(context, "WDTT-Plus-QR-$stamp.png", bitmap)
}
}.onSuccess {
Toast.makeText(context, "QR-код сохранён в галерею.", Toast.LENGTH_SHORT).show()
}.onFailure {
Toast.makeText(context, it.message ?: "Не удалось сохранить QR-код.", Toast.LENGTH_LONG).show()
}
}
}
)
}
}
@Composable
fun AdminImportDialog(
settingsStore: SettingsStore,
encryptedDocument: String,
onFinished: (String) -> Unit,
onDismiss: () -> Unit
) {
val scope = rememberCoroutineScope()
val preview = remember(encryptedDocument) { runCatching { WdttTransferCodec.previewAdminTransfer(encryptedDocument) }.getOrNull() }
var password by remember { mutableStateOf("") }
var passwordFocused by remember { mutableStateOf(false) }
var decrypted by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
var error by remember { mutableStateOf<String?>(null) }
AlertDialog(
onDismissRequest = { if (!busy) onDismiss() },
title = { Text(if (decrypted == null) "Защищённые настройки" else "Заменить настройки?") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
if (decrypted == null) {
Text("Источник: WDTT Plus ${preview?.sourceVersion ?: "?"}. Для расшифровки введите пароль, заданный при передаче.")
OutlinedTextField(
value = password,
onValueChange = { password = it; error = null },
label = { Text("Пароль файла") },
visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(),
singleLine = true,
modifier = Modifier.fillMaxWidth().onFocusChanged { passwordFocused = it.isFocused }
)
} else {
Text("Будут заменены все три VPN-профиля и локальные настройки администратора. Текущие данные приложения восстановить автоматически не получится.")
}
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
}
},
confirmButton = {
Button(
enabled = !busy && (decrypted != null || password.isNotEmpty()),
onClick = {
busy = true
error = null
scope.launch {
if (decrypted == null) {
runCatching {
withContext(Dispatchers.Default) {
val chars = password.toCharArray()
try {
WdttTransferCodec.decryptAdminSettings(encryptedDocument, chars)
} finally {
chars.fill('\u0000')
}
}
}.onSuccess {
decrypted = it
password = ""
}.onFailure { error = it.message ?: "Не удалось расшифровать настройки." }
busy = false
} else {
runCatching { settingsStore.importAdminSettings(decrypted!!) }
.onSuccess { onFinished("Настройки администратора импортированы. Активирован режим администратора.") }
.onFailure { error = it.message ?: "Не удалось импортировать настройки." }
busy = false
}
}
}
) { Text(if (decrypted == null) "Проверить" else "Заменить") }
},
dismissButton = { TextButton(onClick = onDismiss, enabled = !busy) { Text("Отмена") } }
)
}
@Composable
private fun AdminExportPasswordDialog(onDismiss: () -> Unit, onConfirm: (CharArray) -> Unit) {
var password by remember { mutableStateOf("") }
var repeat by remember { mutableStateOf("") }
var passwordFocused by remember { mutableStateOf(false) }
var repeatFocused by remember { mutableStateOf(false) }
val error = when {
password.isNotEmpty() && password.length < 8 -> "Минимум 8 символов"
repeat.isNotEmpty() && password != repeat -> "Пароли не совпадают"
else -> null
}
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("Защитить настройки") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Пароль не сохраняется. Передайте его получателю отдельно.")
OutlinedTextField(
password,
{ password = it },
label = { Text("Пароль") },
visualTransformation = if (passwordFocused) VisualTransformation.None else PasswordVisualTransformation(),
singleLine = true,
modifier = Modifier.fillMaxWidth().onFocusChanged { passwordFocused = it.isFocused }
)
OutlinedTextField(
repeat,
{ repeat = it },
label = { Text("Повторите пароль") },
visualTransformation = if (repeatFocused) VisualTransformation.None else PasswordVisualTransformation(),
singleLine = true,
modifier = Modifier.fillMaxWidth().onFocusChanged { repeatFocused = it.isFocused }
)
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
}
},
confirmButton = {
Button(onClick = { onConfirm(password.toCharArray()); password = ""; repeat = "" }, enabled = password.length >= 8 && password == repeat) {
Text("Продолжить")
}
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Отмена") } }
)
}
@Composable
private fun QrDisplayDialog(
title: String,
bitmap: Bitmap,
onDismiss: () -> Unit,
onShare: () -> Unit,
onSave: () -> Unit
) {
val context = androidx.compose.ui.platform.LocalContext.current
val permissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) onSave()
else Toast.makeText(context, "Без разрешения Android 9 не может сохранить QR-код в галерею.", Toast.LENGTH_LONG).show()
}
AlertDialog(
onDismissRequest = onDismiss,
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = androidx.compose.ui.Alignment.CenterVertically
) {
Text(title, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
IconButton(onClick = onDismiss, modifier = Modifier.size(32.dp)) {
Icon(Icons.Default.Close, contentDescription = "Закрыть", modifier = Modifier.size(20.dp))
}
}
Image(bitmap = bitmap.asImageBitmap(), contentDescription = "QR-код WDTT Plus", modifier = Modifier.fillMaxWidth())
Text("QR содержит секретные данные. Не публикуйте изображение.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedButton(
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp),
onClick = {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P &&
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
) {
permissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
} else {
onSave()
}
}
) {
Icon(Icons.Default.SaveAlt, null, Modifier.size(18.dp))
Text(" Сохранить", maxLines = 1)
}
Button(
onClick = onShare,
modifier = Modifier.weight(1f).heightIn(min = 48.dp),
contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp)
) {
Icon(Icons.Default.Share, null, Modifier.size(18.dp))
Text(" Поделиться", maxLines = 1)
}
}
}
},
confirmButton = {}
)
}
@Composable
private fun TransferButton(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, busy: Boolean, onClick: () -> Unit) {
OutlinedButton(onClick = onClick, enabled = !busy) {
Icon(icon, null, Modifier.size(18.dp))
Text(" $label")
}
}
private fun shareText(context: Context, text: String) {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_TEXT, text)
}
context.startActivity(Intent.createChooser(intent, "Передать подключение WDTT Plus"))
}
private fun String.safeQrFileName(): String =
replace(Regex("[^\\p{L}\\p{N}._-]+"), "-")
.replace(Regex("-+"), "-")
.trim('_', '.', '-')
.take(48)
.trim('_', '.', '-')
.ifBlank { "qr" }
private fun shareUri(context: Context, uri: Uri, mimeType: String, title: String) {
val intent = Intent(Intent.ACTION_SEND).apply {
type = mimeType
putExtra(Intent.EXTRA_STREAM, uri)
clipData = ClipData.newUri(context.contentResolver, title, uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(Intent.createChooser(intent, title))
}