Release WDTT Plus v1

Prepare WDTT Plus for the public fork repository: update release links, refresh the displayed release date, and publish the current WDTT Plus source tree on top of the original project history.
This commit is contained in:
Ivan4537 committed 2026-07-01 18:25:54 +03:00
1 parent d82483ae36
commit 9b69abe3d5
127 files changed
+17412 -6579

No files matched your search

@@ -1,839 +0,0 @@
package com.wdtt.client
import android.content.Context
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import java.io.File
import androidx.compose.runtime.Stable
@Stable
data class LogEntry(
val key: String,
val message: String,
val count: Int = 1,
val priority: Int = 99, // 0 - Creds, 1 - DTLS, 2 - Ready, 3 - Stats, 99 - Errors/Other
val isError: Boolean = false
)
object TunnelManager {
// 100% защита от утечек: единый управляемый глобальный Scope
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private var process: Process? = null
private var readerJob: Job? = null
private var watchdogJob: Job? = null
private var wgHelper: WireGuardHelper? = null
private val startStopMutex = kotlinx.coroutines.sync.Mutex()
// Error counters for circuit breaker
private var floodCount = 0
private var mismatchCount = 0
private var refusedCount = 0
private var currentHashErrorCount = 0
private var wrapAuthTimeoutCount = 0
var processStartedAtMs = 0L
private var lastActiveAtMs = 0L
private var activeHashIndex = 0 // 0: primary, 1: secondary
private var currentParams: TunnelParams? = null
private var lastContext: Context? = null
private var forceRegenerateUA = false // принудительная перегенерация UA при ошибках
private var currentCaptchaMode = "wv" // режим обхода капчи: "wv" или "rjs"
private var currentCaptchaSolveMethod = "auto" // "manual" или "auto"
@Volatile
var isLoggingEnabled = true
val running = MutableStateFlow(false)
val logs = MutableStateFlow<List<LogEntry>>(emptyList())
val unreadErrorCount = MutableStateFlow(0)
val config = MutableStateFlow<String?>(null)
val stats = MutableStateFlow("Ожидание данных...")
val activeWorkers = MutableStateFlow(0)
val cooldownActive = MutableStateFlow(false)
private var cooldownJob: Job? = null
fun clearUnreadErrors() {
unreadErrorCount.value = 0
}
private var observersInitialized = false
fun initObservers(context: Context) {
if (observersInitialized) return
observersInitialized = true
val appContext = context.applicationContext
scope.launch {
running.collect { running ->
try {
VpnWidgetProvider.updateAllWidgets(appContext)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
android.service.quicksettings.TileService.requestListeningState(
appContext,
android.content.ComponentName(appContext, QuickToggleTileService::class.java)
)
}
} catch (e: Exception) {
// Ignore
}
}
}
}
// Добавляем лог с Деплоя
fun addDeployErrorLog(message: String) {
val hash = message.hashCode().toString()
updateLog("deploy_err_$hash", "[ДЕПЛОЙ] $message", 99, true)
}
fun addDeploySuccessLog(message: String) {
val hash = message.hashCode().toString() + System.currentTimeMillis()
updateLog("deploy_ok_$hash", message, 2, false)
}
private fun updateLog(key: String, message: String, priority: Int, isError: Boolean = false) {
if (!isLoggingEnabled) return
if (isError) {
val list = logs.value
if (list.none { it.key == key }) {
unreadErrorCount.value++
}
}
logs.update { currentList ->
val current = currentList.toMutableList()
val index = current.indexOfFirst { it.key == key }
if (index != -1) {
// Обновляем текст и счётчик НА МЕСТЕ
val entry = current[index]
current[index] = entry.copy(count = entry.count + 1, message = message, priority = priority, isError = isError)
} else {
// Новая запись
current.add(LogEntry(key, message, 1, priority, isError))
}
// Сортировка: по приоритету (наименьший сверху), затем ошибки
// Приоритеты: Основной=1, Капча=5, Готов=10, Статы=100, Ошибки=200
val sorted = current.sortedWith(compareBy({ it.priority }, { if (it.isError) 1 else 0 }, { it.key }))
// Лимит 100 записей
if (sorted.size > 100) sorted.takeLast(100) else sorted
}
}
fun start(context: Context, params: TunnelParams, isSwitching: Boolean = false) {
scope.launch {
startStopMutex.lock()
try {
if (running.value && !isSwitching) return@launch
val appContext = context.applicationContext // Защита от Memory Leak
if (!isSwitching) {
clearLogs()
config.value = null
stats.value = "Ожидание данных..."
floodCount = 0
mismatchCount = 0
refusedCount = 0
currentHashErrorCount = 0
wrapAuthTimeoutCount = 0
processStartedAtMs = 0L
lastActiveAtMs = 0L
activeHashIndex = 0
currentParams = params
lastContext = appContext
forceRegenerateUA = false
currentCaptchaMode = params.captchaMode
currentCaptchaSolveMethod = params.captchaSolveMethod
}
wgHelper = WireGuardHelper(appContext)
val targetHash = if (activeHashIndex == 0) params.vkHashes else params.secondaryVkHash
// Robust hash parsing: split by comma, newline, or whitespace
val hashList = targetHash
.split(Regex("[,\\s\\n]+"))
.map { it.trim() }
.filter { it.isNotEmpty() }
.take(3)
if (hashList.isEmpty()) {
updateLog("hash_error", "Ошибка: Хеш не указан", 99, true)
running.value = false
return@launch
}
if (params.connectionPassword.isBlank()) {
updateLog("password_error", "Ошибка: пароль подключения не указан", 99, true)
running.value = false
return@launch
}
val hashCount = hashList.size.coerceIn(1, 3)
val totalWorkers = params.workersPerHash.coerceIn(1, 128)
val hashMode = if (activeHashIndex == 0) "Основной" else "Запасной"
updateLog("config_info", "[$hashMode] Хешей=$hashCount, Потоков=$totalWorkers", 1)
val binaryPath = context.applicationInfo.nativeLibraryDir + "/libclient.so"
val binaryFile = File(binaryPath)
if (!binaryFile.exists()) {
updateLog("binary_error", "Ошибка: Бинарный файл не найден", 99, true)
return@launch
}
val cmd = mutableListOf(
binaryPath,
"-peer", params.peer,
"-vk", hashList.joinToString(","),
"-n", totalWorkers.toString(),
"-listen", "127.0.0.1:${params.port}"
)
if (params.fingerprint.isNotEmpty()) {
cmd.add("-fingerprint")
cmd.add(params.fingerprint)
}
if (params.clientIds.isNotEmpty()) {
cmd.add("-client-ids")
cmd.add(params.clientIds)
}
cmd.add("-vk-auth-mode")
cmd.add(params.vkAuthMode)
val androidId = android.provider.Settings.Secure.getString(context.contentResolver, android.provider.Settings.Secure.ANDROID_ID) ?: "unknown"
cmd.add("-device-id")
cmd.add(androidId)
cmd.add("-password")
cmd.add(params.connectionPassword)
cmd.add("-captcha-mode")
cmd.add(params.captchaMode)
val pb = ProcessBuilder(cmd)
pb.directory(context.filesDir)
pb.redirectErrorStream(true)
val env = pb.environment()
env["LD_LIBRARY_PATH"] = context.applicationInfo.nativeLibraryDir
process = pb.start()
processStartedAtMs = System.currentTimeMillis()
wrapAuthTimeoutCount = 0
lastActiveAtMs = 0L
running.value = true
startLogReader()
startWatchdog(appContext, params)
} catch (e: Exception) {
updateLog("critical_start_error", "Критическая ошибка запуска: ${e.message}", 99, true)
e.printStackTrace()
running.value = false
} finally {
startStopMutex.unlock()
}
}
}
private fun startLogReader() {
readerJob = scope.launch {
val reader = process?.inputStream?.bufferedReader() ?: return@launch
var collectingConfig = false
val configBuilder = StringBuilder()
try {
var lastResetTime = System.currentTimeMillis()
reader.forEachLine { line ->
val now = System.currentTimeMillis()
if (now - lastResetTime > 60000) {
refusedCount = 0
floodCount = 0
mismatchCount = 0
currentHashErrorCount = 0
lastResetTime = now
}
val msgPrefixReplaced = line.replace(Regex("^\\d{4}/\\d{2}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?\\s"), "")
val lineTrim = msgPrefixReplaced.trim()
val isError = lineTrim.contains("Ошибка", true) || lineTrim.contains("error", true) || lineTrim.contains("FAIL", true) || lineTrim.contains("timeout", true) || lineTrim.contains("refused", true) || lineTrim.contains("FATAL_AUTH", true)
if (lineTrim.contains("FATAL_AUTH")) {
val isWrapHandshakeTimeout = lineTrim.contains("DTLS timeout", true) ||
lineTrim.contains("WRAP_AUTH_TIMEOUT", true)
if (isWrapHandshakeTimeout) {
if (activeWorkers.value > 0) {
wrapAuthTimeoutCount = 0
updateLog(
"wrap_timeout_recovered",
"[WRAP] Один поток не прошёл handshake, активных=${activeWorkers.value}; повторяем",
50,
true
)
} else {
wrapAuthTimeoutCount++
updateLog(
"wrap_timeout_wait",
"[WRAP] Handshake не подтвердился, проверяем пароль/сеть ($wrapAuthTimeoutCount)",
50,
true
)
}
return@forEachLine
}
val reason = when {
lineTrim.contains("неверный пароль") -> "Неверный пароль подключения"
lineTrim.contains("истёк") -> "Срок действия пароля истёк"
lineTrim.contains("другому устройству") -> "Пароль привязан к другому устройству"
else -> "Ошибка авторизации"
}
handleCriticalError("\uD83D\uDD12 $reason. Воркеры остановлены.")
return@forEachLine
}
if (lineTrim.contains("WRAP_AUTH_TIMEOUT", true)) {
if (activeWorkers.value > 0) {
wrapAuthTimeoutCount = 0
updateLog(
"wrap_timeout_recovered",
"[WRAP] Один поток не прошёл handshake, активных=${activeWorkers.value}; повторяем",
50,
true
)
} else {
wrapAuthTimeoutCount++
updateLog(
"wrap_timeout_wait",
"[WRAP] Handshake не подтвердился, проверяем пароль/сеть ($wrapAuthTimeoutCount)",
50,
true
)
}
return@forEachLine
}
if (lineTrim.startsWith("CAPTCHA_SOLVE|")) {
val payload = lineTrim.substringAfter("CAPTCHA_SOLVE|")
val parts = payload.split("|", limit = 3)
when (parts.size) {
3 -> {
val requestMode = parts[0]
val redirectUri = parts[1]
val sessionToken = parts[2]
scope.launch {
handleCaptchaSolve(requestMode, redirectUri, sessionToken)
}
}
2 -> {
val redirectUri = parts[0]
val sessionToken = parts[1]
scope.launch {
handleCaptchaSolve("selected", redirectUri, sessionToken)
}
}
else -> {
writeCaptchaResult("error:invalid CAPTCHA_SOLVE format")
}
}
return@forEachLine
}
if (isError) {
when {
lineTrim.contains("Flood control", true) -> {
floodCount++
if (floodCount >= 5) {
handleCriticalError("Flood Control (ВК ограничил ваш IP). Попробуйте позже.")
return@forEachLine
}
}
lineTrim.contains("ip mismatch", true) -> {
mismatchCount++
if (mismatchCount >= 5) {
handleCriticalError("IP Mismatch (IP утерян). Попробуйте переподключиться.")
return@forEachLine
}
}
lineTrim.contains("connection refused", true) || lineTrim.contains("timeout", true) -> {
refusedCount++
if (refusedCount >= 400) {
handleCriticalError("Критическое отсутствие сети (400+ таймаутов). Отключение.")
return@forEachLine
}
}
lineTrim.contains("9000") || lineTrim.contains("Call not found", true) -> {
currentHashErrorCount++
if (currentHashErrorCount >= 10) {
handleHashError()
return@forEachLine
}
}
}
}
if (lineTrim.contains("[СТАТИСТИКА]")) {
val msg = lineTrim.substringAfter("[СТАТИСТИКА]").trim()
stats.value = msg
val match = Regex("Активных:\\s*(\\d+)").find(msg)
if (match != null) {
val active = match.groupValues[1].toIntOrNull() ?: 0
activeWorkers.value = active
if (active > 0) {
lastActiveAtMs = now
wrapAuthTimeoutCount = 0
}
}
updateLog("stats", "[СТАТИСТИКА] $msg", 3, false)
return@forEachLine
}
when {
lineTrim.contains("[КАПЧА] AUTO:") -> {
var text = lineTrim.substringAfter("[КАПЧА] AUTO:").trim()
text = text.replace(Regex("\\s*\\([^)]+\\)\\s*"), " ").trim()
val isErr = text.contains("ошибка", true) ||
text.contains("timeout", true) ||
text.contains("не решил", true)
val stableKey = when {
text.contains("старт") -> "captcha_auto_1"
text.contains("Go v2") && text.contains("2 попыт") -> "captcha_auto_2"
text.contains("WBV Auto попытка") -> "captcha_auto_3"
text.contains("финальная") -> "captcha_auto_4"
text.contains("ручной WebView") -> "captcha_auto_5"
text.contains("решил") || text.contains("решила") -> "captcha_auto_done"
else -> "captcha_auto_${text.take(18).hashCode()}"
}
updateLog(stableKey, "[КАПЧА AUTO] $text", 5, isErr)
}
lineTrim.contains("[КАПЧА] RJS:") -> {
var text = lineTrim.substringAfter("[КАПЧА] RJS:").trim()
text = text.replace(Regex("\\s*\\([^)]+\\)\\s*"), " ").trim()
val stableKey = when {
text.contains("Загрузка") || text.contains("fetch") -> "captcha_rjs_1"
text.contains("PoW") -> "captcha_rjs_2"
text.contains("осматривает") || text.contains("человек") -> "captcha_rjs_3"
text.contains("captchaNotRobot") || text.contains("Отправка") -> "captcha_rjs_4"
text.contains("endSession") -> "captcha_rjs_5"
text.contains("решена") -> "captcha_rjs_6"
else -> "captcha_rjs_${text.take(15).hashCode()}"
}
updateLog(stableKey, "[КАПЧА RJS] $text", 5, false)
}
lineTrim.contains("[КАПЧА] WBV:") -> {
var text = lineTrim.substringAfter("[КАПЧА] WBV:").trim()
text = text.replace(Regex("\\s*\\([^)]+\\)\\s*"), " ").trim()
val isErr = text.contains("Ошибка")
val stableKey = when {
text.contains("Запрос") -> "captcha_wv_step_2"
text.contains("Токен") -> "captcha_wv_step_5"
isErr -> "captcha_wv_err"
else -> "captcha_wv_go_other"
}
updateLog(stableKey, "[КАПЧА WBV] $text", 5, isErr)
}
lineTrim.contains("Старт") || lineTrim.contains("Ожидайте") ->
updateLog("creds_start", "[ВК] Получение учетных данных...", 2, false)
lineTrim.contains("Креды получены") ->
updateLog("creds_lifetime", lineTrim, 2, false)
lineTrim.contains("Креды OK") || lineTrim.contains("Первые креды") ->
updateLog("creds_ok", "[ВК] Учетные данные проверены ✓", 2, false)
lineTrim.contains("Решаю VK Smart Captcha") ->
updateLog("captcha_start", "[КАПЧА] Решение капчи...", 5, false)
lineTrim.contains("Smart Captcha решена") ->
updateLog("captcha_done", "[КАПЧА] Капча решена ✓", 5, false)
lineTrim.contains("капча не решена") || lineTrim.contains("ошибка решения капчи") ->
updateLog("captcha_failed", "[КАПЧА] Ошибка решения капчи", 5, true)
lineTrim.contains("[WRAP]") -> {
val text = lineTrim.substringAfter("[WRAP]").trim()
updateLog("wrap_status", "[WRAP] $text", 1, false)
}
lineTrim.contains("[TURN]") -> {
val text = lineTrim.substringAfter("[TURN]").trim()
val turnError = text.contains("Ошибка", true) ||
text.contains("не удалось", true) ||
text.contains("неполный ответ", true)
updateLog("turn_${text.take(32).hashCode()}", "[TURN] $text", 2, turnError)
}
lineTrim.contains("Relay:") ->
updateLog("dtls_start", "[DTLS] Рукопожатие (Handshake)...", 1, false)
lineTrim.contains("DTLS ОК") ->
updateLog("dtls_ok", "[DTLS] Соединение установлено ✓", 1, false)
lineTrim.contains("Активна ✓") ->
updateLog("ready", "[READY] Туннель готов к работе ✓", 2, false)
isError -> {
val errorKey = when {
lineTrim.contains("lookup login.vk.ru", true) -> "err_vk_dns"
lineTrim.contains("connection refused") -> "err_conn_refused"
lineTrim.contains("timeout") -> "err_timeout"
lineTrim.contains("кредов") -> "err_creds"
lineTrim.contains("DTLS") -> "err_dtls"
else -> "general_error_" + lineTrim.take(15).hashCode()
}
val errorMessage = if (errorKey == "err_vk_dns") {
"[СЕТЬ] DNS до VK недоступен: login.vk.ru"
} else {
lineTrim
}
updateLog(errorKey, errorMessage, 99, true)
}
}
if (line.contains("╔") && line.contains("WireGuard")) {
collectingConfig = true
configBuilder.clear()
return@forEachLine
} else if (collectingConfig) {
if (line.contains("╚")) {
collectingConfig = false
val configStr = configBuilder.toString().trim()
config.value = configStr
scope.launch(Dispatchers.Main) {
try {
wgHelper?.startTunnel(configStr)
} catch (e: Exception) {
updateLog("vpn_start_error", "Ошибка запуска VPN: ${e.readableMessage()}", 99, true)
}
}
} else if (line.contains("║")) {
val content = line.replace("║", "").trim()
if (content.isNotEmpty()) {
configBuilder.appendLine(content)
}
}
return@forEachLine
}
}
} catch (e: Exception) {
if (!e.message.toString().contains("read interrupted by close", ignoreCase = true)) {
updateLog("sys_error", "Системная ошибка: ${e.message}", -1, true)
}
} finally {
running.value = false
process = null
}
}
}
private fun handleCriticalError(message: String) {
updateLog("circuit_breaker", "[СТОП] $message", -1, true)
stop()
}
private fun handleHashError() {
val params = currentParams ?: return
val context = lastContext ?: return
currentHashErrorCount = 0
forceRegenerateUA = true
if (params.secondaryVkHash.isNotEmpty() && activeHashIndex == 0) {
updateLog("hash_switch", "Основной хеш мертв. Переключение на запасной...", 50, true)
activeHashIndex = 1
stopOnlyProcess()
start(context, params, isSwitching = true)
} else {
val msg = if (activeHashIndex == 1) "Запасной хеш тоже мертв. Отключение." else "Хеш умер, запасного нет. Отключение."
handleCriticalError(msg)
}
}
private fun startWatchdog(context: Context, params: TunnelParams) {
watchdogJob?.cancel()
watchdogJob = scope.launch {
var zeroWorkersSince = 0L
delay(10_000)
while (isActive && running.value) {
val proc = process
if (proc == null || !proc.isAlive) {
updateLog("watchdog", "⚠ Процесс упал. Перезапуск...", 50, true)
activeWorkers.value = 0
forceRegenerateUA = true
killProcess()
delay(2000)
if (running.value) {
start(context, params, isSwitching = true)
}
return@launch
}
val workers = activeWorkers.value
if (workers <= 0) {
if (zeroWorkersSince == 0L) {
zeroWorkersSince = System.currentTimeMillis()
} else if (
wrapAuthTimeoutCount >= 3 &&
processStartedAtMs > 0L &&
System.currentTimeMillis() - processStartedAtMs > 30_000 &&
lastActiveAtMs == 0L &&
!ManlCaptchaWebViewManager.isCaptchaPending
) {
handleCriticalError("\uD83D\uDD12 Неверный пароль подключения или несовместимый WRAP. Воркеры остановлены.")
return@launch
} else if (System.currentTimeMillis() - zeroWorkersSince > 90_000 && !ManlCaptchaWebViewManager.isCaptchaPending) {
updateLog("watchdog", "⚠ Зомби-процесс (0 воркеров 90с). Перезапуск...", 50, true)
forceRegenerateUA = true
killProcess()
delay(2000)
if (running.value) {
start(context, params, isSwitching = true)
}
return@launch
}
} else {
zeroWorkersSince = 0L
}
delay(5_000)
}
}
}
fun restartTransport() {
val params = currentParams ?: return
val context = lastContext ?: return
updateLog("network_restart", "[СЕТЬ] Перезапуск транспорта из-за смены сети...", 50, false)
killProcess()
scope.launch {
delay(1500)
start(context, params, isSwitching = true)
}
}
fun pause() {
if (!running.value) return
killProcess()
activeWorkers.value = 0
}
fun resume() {
if (currentParams != null && lastContext != null) {
scope.launch {
start(lastContext!!, currentParams!!, isSwitching = true)
}
}
}
private fun killProcess() {
watchdogJob?.cancel()
readerJob?.cancel()
val proc = process
process = null
if (proc != null) {
try { proc.destroy() } catch (_: Exception) {}
try { proc.waitFor(500, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
if (proc.isAlive) {
try { proc.destroyForcibly() } catch (_: Exception) {}
try { proc.waitFor(1000, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
}
}
}
private fun stopOnlyProcess() {
killProcess()
running.value = false
}
fun stop() {
scope.launch {
startStopMutex.lock()
try {
withContext(Dispatchers.Main) {
wgHelper?.stopTunnel()
}
killProcess()
running.value = false
activeWorkers.value = 0
currentParams = null
ManlCaptchaWebViewManager.cancelCaptcha()
} finally {
startStopMutex.unlock()
}
}
}
suspend fun stopAndWait() {
startStopMutex.lock()
try {
withContext(Dispatchers.Main) {
wgHelper?.stopTunnel()
}
withContext(Dispatchers.IO) {
killProcess()
running.value = false
activeWorkers.value = 0
currentParams = null
ManlCaptchaWebViewManager.cancelCaptcha()
}
} finally {
startStopMutex.unlock()
}
}
fun reloadWireGuard() {
if (running.value) {
scope.launch {
wgHelper?.reloadTunnel()
}
}
}
private suspend fun handleCaptchaSolve(requestMode: String, redirectUri: String, sessionToken: String) {
val ctx = lastContext ?: run {
writeCaptchaResult("error:context is null")
return
}
val mode = requestMode.lowercase()
try {
val token = when (mode) {
"auto" -> solveSingleAutoWebViewCaptcha(redirectUri, sessionToken)
"manual" -> {
updateLog("captcha_wv_step_1", "[КАПЧА WBV] Создание ручного WebView...", 5, false)
ManlCaptchaWebViewManager.solveCaptchaAsync(ctx, redirectUri, sessionToken)
}
else -> {
if (currentCaptchaSolveMethod == "auto") {
solveAutoWebViewCaptcha(ctx, redirectUri, sessionToken)
} else {
updateLog("captcha_wv_step_1", "[КАПЧА WBV] Создание ручного WebView...", 5, false)
ManlCaptchaWebViewManager.solveCaptchaAsync(ctx, redirectUri, sessionToken)
}
}
}
updateLog("captcha_wv_step_4", "[КАПЧА WBV] Капча решена ✓", 5, false)
writeCaptchaResult(token)
} catch (e: IllegalStateException) {
val errorMsg = e.message ?: "WV state error"
updateLog("captcha_wv_err", "[КАПЧА WBV] $errorMsg", 5, true)
writeCaptchaResult("error:$errorMsg")
} catch (e: kotlinx.coroutines.TimeoutCancellationException) {
updateLog("captcha_wv_err", "[КАПЧА WBV] Таймаут WebView", 5, true)
writeCaptchaResult("error:timeout")
} catch (e: kotlin.coroutines.cancellation.CancellationException) {
updateLog("captcha_wv_err", "[КАПЧА WBV] Отменено", 5, true)
writeCaptchaResult("error:cancelled")
} catch (e: Exception) {
val errorMsg = e.message ?: "${e::class.simpleName}"
if (errorMsg != "tunnel stopped") {
updateLog("captcha_wv_err", "[КАПЧА WBV] Ошибка — $errorMsg", 5, true)
}
writeCaptchaResult("error:$errorMsg")
}
updateLog("captcha_wv_step_6", "[КАПЧА WBV] WebView уничтожен", 5, false)
}
private suspend fun solveSingleAutoWebViewCaptcha(
redirectUri: String,
sessionToken: String
): String {
updateLog("captcha_wv_step_1", "[КАПЧА WBV] Авто WebView попытка 10с...", 5, false)
return CaptchaWebViewManager.solveCaptchaAsync(redirectUri, sessionToken) { step ->
updateLog("captcha_wv_auto_step", "[КАПЧА WBV] $step", 5, false)
}
}
private suspend fun solveAutoWebViewCaptcha(
ctx: Context,
redirectUri: String,
sessionToken: String
): String {
for (attempt in 1..2) {
updateLog("captcha_wv_step_1", "[КАПЧА WBV] Авто WebView попытка $attempt/2...", 5, false)
try {
return CaptchaWebViewManager.solveCaptchaAsync(redirectUri, sessionToken) { step ->
updateLog("captcha_wv_auto_step", "[КАПЧА WBV] $step", 5, false)
}
} catch (e: kotlinx.coroutines.TimeoutCancellationException) {
updateLog("captcha_wv_timeout_$attempt", "[КАПЧА WBV] Авто таймаут 10с ($attempt/2)", 5, attempt == 2)
if (attempt == 2) {
updateLog("captcha_wv_fallback", "[КАПЧА WBV] 2 таймаута авто, открыт ручной WebView", 5, false)
return ManlCaptchaWebViewManager.solveCaptchaAsync(ctx, redirectUri, sessionToken)
}
} catch (e: IllegalStateException) {
if (e.message == CaptchaWebViewManager.ERROR_SLIDER_DETECTED) {
updateLog("captcha_wv_fallback", "[КАПЧА WBV] Обнаружен слайдер, открыт ручной WebView", 5, false)
return ManlCaptchaWebViewManager.solveCaptchaAsync(ctx, redirectUri, sessionToken)
}
throw e
}
}
return ManlCaptchaWebViewManager.solveCaptchaAsync(ctx, redirectUri, sessionToken)
}
private fun writeCaptchaResult(result: String) {
val proc = process
if (proc == null || !proc.isAlive) return
try {
val line = "CAPTCHA_RESULT|$result\n"
proc.outputStream.write(line.toByteArray(Charsets.UTF_8))
proc.outputStream.flush()
} catch (e: Exception) {
updateLog("captcha_write_err", "[КАПЧА] Ошибка записи: ${e.message}", 200, true)
}
}
fun clearLogs() {
logs.value = emptyList()
if (!running.value) {
activeWorkers.value = 0
}
}
fun startCooldown(millis: Long) {
cooldownJob?.cancel()
cooldownActive.value = true
cooldownJob = scope.launch(Dispatchers.Main) {
delay(millis)
cooldownActive.value = false
}
}
private fun Throwable.readableMessage(): String {
val text = message ?: localizedMessage
return if (text.isNullOrBlank()) this::class.java.simpleName else "${this::class.java.simpleName}: $text"
}
}
data class TunnelParams(
val peer: String,
val vkHashes: String,
val secondaryVkHash: String = "",
val workersPerHash: Int,
val port: Int,
val sni: String = "",
val connectionPassword: String = "",
val protocol: String = "udp",
val vkAuthMode: String = "vkcalls",
val captchaMode: String = "auto",
val captchaSolveMethod: String = "auto",
val fingerprint: String = "chrome",
val clientIds: String = "6287487,8202606"
)
@@ -1,407 +0,0 @@
package com.wdtt.client
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiManager
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4"
private const val TUNNEL_NOTIFICATION_ID = 1
class TunnelService : Service() {
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
private var updateJob: Job? = null
private var lastNotificationText: String? = null
// Network Monitoring
private var connectivityManager: ConnectivityManager? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
private var lastNetworkChangeTime = 0L
private val activeNetworks = mutableSetOf<Network>()
private var isTunnelPaused = false
override fun onCreate() {
super.onCreate()
createNotificationChannel()
// Сразу берем лок при создании
acquireWakeLock()
setupNetworkCallback()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) {
restoreTunnel()
return START_STICKY
}
when (intent.action) {
"START" -> {
val notification = createNotification("Запуск...")
startPersistentForeground(notification)
val params = TunnelParams(
peer = intent.getStringExtra("peer") ?: "",
vkHashes = intent.getStringExtra("vk_hashes") ?: "",
secondaryVkHash = intent.getStringExtra("secondary_vk_hash") ?: "",
workersPerHash = intent.getIntExtra("workers_per_hash", 16),
port = intent.getIntExtra("port", 9000),
sni = intent.getStringExtra("sni") ?: "",
connectionPassword = intent.getStringExtra("connection_password") ?: "",
protocol = intent.getStringExtra("protocol") ?: "udp",
vkAuthMode = sanitizeVkAuthMode(intent.getStringExtra("vk_auth_mode")),
captchaMode = sanitizeCaptchaMode(intent.getStringExtra("captcha_mode")),
captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto",
fingerprint = intent.getStringExtra("fingerprint") ?: "chrome",
clientIds = intent.getStringExtra("client_ids") ?: "6287487,8202606"
)
startTunnel(params)
}
"STOP" -> stopTunnel()
"DEPLOY_START" -> {
val notification = createNotification("Установка на сервер...", "DEPLOY_CANCEL", "Отменить")
startPersistentForeground(notification)
acquireWakeLock()
}
"DEPLOY_CANCEL" -> {
com.wdtt.client.DeployManager.writeError("[!] ❌ Установка отменена пользователем")
com.wdtt.client.DeployManager.stopDeploy("error: Отменена пользователем")
stopForeground(STOP_FOREGROUND_REMOVE)
}
"DEPLOY_STOP" -> {
if (!TunnelManager.running.value) {
stopTunnel()
} else {
updateNotification("Туннель активен")
}
}
}
return START_STICKY
}
private fun restoreTunnel() {
val notification = createNotification("Восстановление соединения...")
startPersistentForeground(notification)
val appContext = applicationContext
TunnelManager.scope.launch {
try {
val store = SettingsStore(appContext)
val basePeer = store.peer.first()
val manualPortsEnabled = store.manualPortsEnabled.first()
val serverDtlsPort = if (manualPortsEnabled) store.serverDtlsPort.first() else 56000
val peerWithPort = if (basePeer.isBlank() || basePeer.contains(":")) basePeer else "$basePeer:$serverDtlsPort"
val params = TunnelParams(
peer = peerWithPort,
vkHashes = store.vkHashes.first(),
secondaryVkHash = store.secondaryVkHash.first(),
workersPerHash = store.workersPerHash.first(),
port = store.listenPort.first(),
sni = store.sni.first(),
connectionPassword = store.connectionPassword.first(),
vkAuthMode = sanitizeVkAuthMode(store.vkAuthMode.first()),
captchaMode = sanitizeCaptchaMode(store.captchaMode.first()),
captchaSolveMethod = store.captchaSolveMethod.first(),
fingerprint = store.selectedFingerprint.first(),
clientIds = store.activeClientIds.first()
)
if (params.peer.isNotEmpty() && params.vkHashes.isNotEmpty()) {
launch(Dispatchers.Main) {
startTunnel(params)
}
} else {
launch(Dispatchers.Main) {
stopTunnel()
}
}
} catch (e: Exception) {
launch(Dispatchers.Main) {
stopTunnel()
}
}
}
}
private fun startTunnel(params: TunnelParams) {
updateNotification("Подключение...")
acquireWakeLock()
acquireWifiLock()
// Подготавливаем CaptchaWebViewManager (не создаёт WebView — просто сохраняет контекст)
// Вызываем всегда — дёшево, а WebView создаётся на лету при каждом запросе капчи
CaptchaWebViewManager.onTunnelStart(applicationContext)
TunnelManager.start(this, params)
startStatsUpdater()
}
private fun stopTunnel() {
updateJob?.cancel()
// Уничтожаем текущий WebView (если капча решается) и чистим контекст
CaptchaWebViewManager.onTunnelStop()
TunnelManager.stop()
releaseWakeLock()
releaseWifiLock()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
private fun setupNetworkCallback() {
connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
activeNetworks.clear()
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
val wasEmpty = activeNetworks.isEmpty()
activeNetworks.add(network)
if (wasEmpty) {
if (isTunnelPaused) {
isTunnelPaused = false
Log.d("TunnelService", "Сеть появилась, возобновляем туннель")
TunnelManager.resume()
updateNotification("Подключение...")
} else {
handleNetworkChange()
}
} else {
handleNetworkChange()
}
}
override fun onLost(network: Network) {
super.onLost(network)
activeNetworks.remove(network)
if (activeNetworks.isEmpty() && TunnelManager.running.value && !isTunnelPaused) {
isTunnelPaused = true
Log.d("TunnelService", "Сеть потеряна, приостанавливаем туннель")
TunnelManager.pause()
updateNotification("Ожидание сети (Фоновый сон)")
}
}
}
// ВАЖНО: Слушаем только реальные (не VPN) сети с доступом в интернет.
// Иначе интерфейс VPN (tun0) считается активной сетью, и при "Режиме полёта" activeNetworks не падает до 0.
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.build()
connectivityManager?.registerNetworkCallback(request, networkCallback!!)
}
private fun handleNetworkChange() {
val now = System.currentTimeMillis()
if (now - lastNetworkChangeTime < 5000) return
lastNetworkChangeTime = now
if (TunnelManager.running.value && !isTunnelPaused) {
Log.d("TunnelService", "Сеть изменилась, мягкий перезапуск Go-клиента")
TunnelManager.restartTransport()
}
}
private fun sanitizeCaptchaMode(mode: String?): String {
return when (mode?.lowercase()) {
"auto" -> "auto"
"rjs" -> "rjs"
"wv" -> "wv"
else -> "auto"
}
}
private fun sanitizeVkAuthMode(mode: String?): String {
return when (mode?.lowercase()) {
"legacy" -> "legacy"
else -> "vkcalls"
}
}
private fun acquireWakeLock() {
if (wakeLock?.isHeld == true) return
val pm = getSystemService(POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"wdtt:tunnel_cpu"
).apply {
setReferenceCounted(false)
acquire()
}
}
@Suppress("DEPRECATION")
private fun acquireWifiLock() {
if (wifiLock?.isHeld == true) return
val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
// Используем WIFI_MODE_FULL_LOW_LATENCY для Android 10+,
// это предотвращает отключение радиомодуля при выключенном экране
val mode = if (Build.VERSION.SDK_INT >= 29) {
WifiManager.WIFI_MODE_FULL_LOW_LATENCY
} else {
WifiManager.WIFI_MODE_FULL_HIGH_PERF
}
wifiLock = wm.createWifiLock(mode, "wdtt:wifi_perf").apply {
setReferenceCounted(false)
acquire()
}
}
private fun releaseWakeLock() {
if (wakeLock?.isHeld == true) {
wakeLock?.release()
}
wakeLock = null
}
private fun releaseWifiLock() {
if (wifiLock?.isHeld == true) {
wifiLock?.release()
}
wifiLock = null
}
private fun startStatsUpdater() {
updateJob?.cancel()
updateJob = TunnelManager.scope.launch(Dispatchers.Main) {
// Сторож следит за ПРОПАЖОЙ уже поднятого VPN-интерфейса, а не за его
// отсутствием во время подключения. Фаза установки туннеля (капча → VK-креды →
// WRAP → TURN/DTLS → выдача WireGuard-конфига) может занимать значительно больше
// времени, чем любое фиксированное окно, особенно при ручном обходе капчи, поэтому
// аварийно глушим туннель только если интерфейс был поднят и затем пропал/заменён.
var wasEverUp = false
delay(1000)
while (isActive) {
if (!TunnelManager.running.value && !isTunnelPaused) {
// Туннель полностью остановлен (не на паузе) — убиваем сервис
stopSelf()
break
}
if (TunnelManager.running.value && !isTunnelPaused) {
val helper = WireGuardHelper(applicationContext)
if (helper.isTunnelUp()) {
wasEverUp = true
} else if (wasEverUp) {
Log.w("TunnelService", "Обнаружена пропажа или замена VPN-интерфейса! Экстренное выключение туннеля.")
stopTunnel()
break
}
}
if (!isTunnelPaused) {
updateNotification(buildTunnelNotificationText())
}
delay(2000)
}
}
}
private fun buildTunnelNotificationText(): String {
val statsText = TunnelManager.stats.value.trim()
return when {
statsText.isEmpty() -> "Туннель активен"
statsText == "Ожидание данных..." -> "Туннель активен"
else -> statsText
}
}
private fun createNotificationChannel() {
val channel = NotificationChannel(
TUNNEL_NOTIFICATION_CHANNEL_ID,
"WDTT Туннель",
NotificationManager.IMPORTANCE_LOW
).apply {
description = "Уведомление о работе туннеля"
setShowBadge(false)
// ВАЖНО: Разрешаем показывать на экране блокировки
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
setSound(null, null)
enableVibration(false)
}
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
}
private fun createNotification(text: String, actionName: String = "STOP", actionTitle: String = "Отключить"): Notification {
val openIntent = PendingIntent.getActivity(
this, 0,
Intent(this, MainActivity::class.java),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val stopIntent = PendingIntent.getService(
this, if (actionName == "STOP") 1 else 2,
Intent(this, TunnelService::class.java).apply { action = actionName },
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(this, TUNNEL_NOTIFICATION_CHANNEL_ID)
.setContentTitle("WDTT")
.setContentText(text)
.setSmallIcon(R.drawable.ic_stat_connected)
.setOngoing(true)
.setLocalOnly(true)
.setContentIntent(openIntent)
.addAction(R.drawable.ic_stop, actionTitle, stopIntent)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_DEFAULT)
// ВАЖНО: Делаем уведомление публичным (видимым на локскрине)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
// Категория SERVICE помогает системе понять важность
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setOnlyAlertOnce(true) // Не издавать звук и не будить экран при обновлении статистики!
.setSilent(true) // Делаем тихим само уведомление
.setShowWhen(false)
.setUsesChronometer(false)
.setWhen(0L)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build()
}
private fun startPersistentForeground(notification: Notification) {
if (Build.VERSION.SDK_INT >= 34) {
startForeground(TUNNEL_NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
} else {
startForeground(TUNNEL_NOTIFICATION_ID, notification)
}
}
private fun updateNotification(text: String) {
if (lastNotificationText == text) return
lastNotificationText = text
val notification = createNotification(text)
getSystemService(NotificationManager::class.java).notify(TUNNEL_NOTIFICATION_ID, notification)
}
override fun onDestroy() {
super.onDestroy()
networkCallback?.let {
connectivityManager?.unregisterNetworkCallback(it)
}
stopTunnel()
}
override fun onBind(intent: Intent?): IBinder? = null
}
@@ -1,961 +0,0 @@
package com.wdtt.client.ui
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.CloudUpload
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Key
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import com.wdtt.client.TunnelService
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.jcraft.jsch.ChannelExec
import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import com.wdtt.client.DeployManager
import com.wdtt.client.SettingsStore
import com.wdtt.client.TunnelManager
import com.wdtt.client.WDTTColors
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.util.Properties
private const val CMD_TIMEOUT = 900000L // 15 minutes
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeployTab() {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
LaunchedEffect(Unit) { DeployManager.init(context) }
val savedIp by settingsStore.deployIp.collectAsStateWithLifecycle(initialValue = "")
val savedLogin by settingsStore.deployLogin.collectAsStateWithLifecycle(initialValue = "")
val savedPassword by settingsStore.deployPassword.collectAsStateWithLifecycle(initialValue = "")
var ip by remember { mutableStateOf("") }
var login by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val savedDns1 by settingsStore.deployDns1.collectAsStateWithLifecycle(initialValue = "1.1.1.1")
val savedDns2 by settingsStore.deployDns2.collectAsStateWithLifecycle(initialValue = "1.0.0.1")
var dns1 by remember { mutableStateOf("1.1.1.1") }
var dns2 by remember { mutableStateOf("1.0.0.1") }
val savedMainPass by settingsStore.deployMainPassword.collectAsStateWithLifecycle(initialValue = "")
val savedAdminId by settingsStore.deployAdminId.collectAsStateWithLifecycle(initialValue = "")
val savedBotToken by settingsStore.deployBotToken.collectAsStateWithLifecycle(initialValue = "")
val savedSshPort by settingsStore.deploySshPort.collectAsStateWithLifecycle(initialValue = "22")
val savedManualPorts by settingsStore.manualPortsEnabled.collectAsStateWithLifecycle(initialValue = false)
val savedServerDtlsPort by settingsStore.serverDtlsPort.collectAsStateWithLifecycle(initialValue = 56000)
val savedServerWgPort by settingsStore.serverWgPort.collectAsStateWithLifecycle(initialValue = 56001)
var showSecretsDialog by remember { mutableStateOf(false) }
var showUninstallDialog by remember { mutableStateOf(false) }
var showSuccessBanner by rememberSaveable { mutableStateOf(false) }
var successCountdown by rememberSaveable { mutableIntStateOf(5) }
LaunchedEffect(showSuccessBanner) {
if (showSuccessBanner) {
while (successCountdown > 0) {
kotlinx.coroutines.delay(1000)
successCountdown--
}
showSuccessBanner = false
}
}
val isDeploying by DeployManager.isDeploying.collectAsStateWithLifecycle()
val deployProgress by DeployManager.deployProgress.collectAsStateWithLifecycle()
val currentStep by DeployManager.currentStep.collectAsStateWithLifecycle()
LaunchedEffect(savedIp) { ip = savedIp }
LaunchedEffect(savedLogin) { login = savedLogin }
LaunchedEffect(savedPassword) { password = savedPassword }
LaunchedEffect(savedDns1) { dns1 = savedDns1 }
LaunchedEffect(savedDns2) { dns2 = savedDns2 }
val animatedProgress by animateFloatAsState(
targetValue = deployProgress,
animationSpec = tween(durationMillis = 1200, easing = androidx.compose.animation.core.FastOutSlowInEasing),
label = "progress"
)
Column(
modifier = Modifier.fillMaxSize().padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Text(
"Настройки сервера",
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
color = MaterialTheme.colorScheme.onSurface
)
// ═══ Поля ввода в Card ═══
AppSectionCard(
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = ip,
onValueChange = {
ip = it.filter { c -> !c.isWhitespace() }
scope.launch { settingsStore.saveDeploy(ip, login, password, savedSshPort, dns1, dns2) }
},
label = { Text("IP сервера или домен (без порта)") },
placeholder = { Text("1.2.3.4 (без порта)") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
enabled = !isDeploying,
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = login,
onValueChange = {
login = it.filter { c -> !c.isWhitespace() }
scope.launch { settingsStore.saveDeploy(ip, login, password, savedSshPort, dns1, dns2) }
},
label = { Text("Логин") },
placeholder = { Text("root") },
singleLine = true,
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(16.dp),
enabled = !isDeploying,
)
OutlinedTextField(
value = password,
onValueChange = {
password = it.filter { c -> !c.isWhitespace() }
scope.launch { settingsStore.saveDeploy(ip, login, password, savedSshPort, dns1, dns2) }
},
label = { Text("Пароль SSH") },
placeholder = { Text("password") },
singleLine = true,
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(16.dp),
enabled = !isDeploying,
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
OutlinedTextField(
value = dns1,
onValueChange = {
dns1 = it.filter { c -> !c.isWhitespace() }
scope.launch { settingsStore.saveDeploy(ip, login, password, savedSshPort, dns1, dns2) }
},
label = { Text("Основной DNS") },
placeholder = { Text("1.1.1.1") },
singleLine = true,
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(16.dp),
enabled = !isDeploying,
)
OutlinedTextField(
value = dns2,
onValueChange = {
dns2 = it.filter { c -> !c.isWhitespace() }
scope.launch { settingsStore.saveDeploy(ip, login, password, savedSshPort, dns1, dns2) }
},
label = { Text("Резервный DNS") },
placeholder = { Text("1.0.0.1") },
singleLine = true,
modifier = Modifier.weight(1f),
shape = RoundedCornerShape(16.dp),
enabled = !isDeploying,
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
"Ручное управление портами",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Medium,
modifier = Modifier.weight(1f),
color = MaterialTheme.colorScheme.onSurface
)
Switch(
checked = savedManualPorts,
enabled = !isDeploying,
onCheckedChange = { enabled ->
scope.launch { settingsStore.saveManualPortsEnabled(enabled) }
}
)
}
}
if (showSecretsDialog) {
DeploySecretsDialog(
settingsStore = settingsStore,
initialMainPass = savedMainPass,
initialAdminId = savedAdminId,
initialBotToken = savedBotToken,
initialSshPort = savedSshPort,
manualPortsEnabled = savedManualPorts,
initialServerDtlsPort = savedServerDtlsPort.toString(),
initialServerWgPort = savedServerWgPort.toString(),
onSaved = { _, _ -> },
onDismiss = { showSecretsDialog = false }
)
}
// ═══ Прогресс ═══
if (isDeploying) {
AppSectionCard(
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = currentStep,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Medium,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Text(
text = "${(animatedProgress * 100).toInt()}%",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
LinearProgressIndicator(
progress = { animatedProgress },
modifier = Modifier.fillMaxWidth().height(8.dp).clip(RoundedCornerShape(4.dp)),
color = MaterialTheme.colorScheme.primary,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
}
}
// ═══ Кнопки ═══
val deploySecretsMissing = savedMainPass.isBlank()
OutlinedButton(
onClick = { showSecretsDialog = true },
modifier = Modifier.fillMaxWidth().height(48.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.outlinedButtonColors(
containerColor = if (deploySecretsMissing) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.surface,
contentColor = if (deploySecretsMissing) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onSurface
),
border = BorderStroke(
1.dp,
if (deploySecretsMissing) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)
)
) {
Icon(Icons.Default.Key, null, Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text(
if (savedManualPorts) "Секреты (BOT, Пароли, Порты)" else "Секреты (BOT, Пароли)",
fontWeight = FontWeight.SemiBold
)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Button(
onClick = {
if (ip.isBlank() || password.isBlank() || savedMainPass.isBlank()) return@Button
val effectiveLogin = if (login.isBlank()) "root" else login
val effectiveDtlsPort = if (savedManualPorts) savedServerDtlsPort.coerceIn(1, 65535) else 56000
val effectiveWgPort = if (savedManualPorts) savedServerWgPort.coerceIn(1, 65535) else 56001
val appContext = context.applicationContext
DeployManager.scope.launch {
try {
DeployManager.startDeploy()
val intent = Intent(appContext, TunnelService::class.java).apply { action = "DEPLOY_START" }
if (Build.VERSION.SDK_INT >= 26) appContext.startForegroundService(intent)
else appContext.startService(intent)
val success = performDeploy(
context = appContext,
host = ip, user = effectiveLogin, pass = password, port = savedSshPort.toIntOrNull() ?: 22,
mainPass = savedMainPass, adminId = savedAdminId, botToken = savedBotToken,
dtlsPort = effectiveDtlsPort, wgPort = effectiveWgPort, dns1 = dns1, dns2 = dns2,
onProgress = { p, s -> DeployManager.updateProgress(p, s) }
)
if (success) {
successCountdown = 5
showSuccessBanner = true
}
} finally {
try { appContext.startService(Intent(appContext, TunnelService::class.java).apply { action = "DEPLOY_STOP" }) } catch (_: Exception) {}
}
}
},
modifier = Modifier.weight(1f).height(50.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary),
enabled = !isDeploying && ip.isNotBlank() && password.isNotBlank() && savedMainPass.isNotBlank()
) {
if (isDeploying) {
CircularProgressIndicator(modifier = Modifier.size(18.dp), color = MaterialTheme.colorScheme.onPrimary, strokeWidth = 2.dp)
} else {
Icon(Icons.Default.CloudUpload, null, Modifier.size(18.dp))
}
Spacer(Modifier.width(8.dp))
Text(if (isDeploying) "Установка..." else "Установить", fontWeight = FontWeight.Bold)
}
Button(
onClick = {
if (ip.isBlank() || password.isBlank()) return@Button
showUninstallDialog = true
},
modifier = Modifier.weight(1f).height(50.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.error,
contentColor = MaterialTheme.colorScheme.onError
),
enabled = !isDeploying && ip.isNotBlank() && password.isNotBlank()
) {
Icon(Icons.Default.Delete, null, Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text("Удалить", fontWeight = FontWeight.Bold)
}
}
if (showUninstallDialog) {
UninstallConfirmDialog(
onDismiss = { showUninstallDialog = false },
onConfirm = {
showUninstallDialog = false
val effectiveLogin = if (login.isBlank()) "root" else login
val effectiveDtlsPort = if (savedManualPorts) savedServerDtlsPort.coerceIn(1, 65535) else 56000
val effectiveWgPort = if (savedManualPorts) savedServerWgPort.coerceIn(1, 65535) else 56001
DeployManager.scope.launch {
try {
DeployManager.startDeploy()
performUninstall(
host = ip, user = effectiveLogin, pass = password, port = savedSshPort.toIntOrNull() ?: 22,
dtlsPort = effectiveDtlsPort, wgPort = effectiveWgPort,
onProgress = { p, s -> DeployManager.updateProgress(p, s) }
)
} catch (_: Exception) {}
}
}
)
}
Spacer(modifier = Modifier.weight(1f))
// ═══ Success Banner ═══
if (showSuccessBanner) {
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
color = WDTTColors.connected.copy(alpha = 0.12f),
contentColor = MaterialTheme.colorScheme.onSurface,
border = BorderStroke(1.dp, WDTTColors.connected.copy(alpha = 0.4f))
) {
Row(
modifier = Modifier.padding(16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(Icons.Default.CheckCircle, contentDescription = null, tint = WDTTColors.connected)
Spacer(Modifier.width(8.dp))
Text(
text = "Деплой успешно завершен ($successCountdown)",
color = WDTTColors.connected,
fontWeight = FontWeight.Bold,
style = MaterialTheme.typography.bodyMedium
)
}
}
}
}
}
// ==================== SSH ====================
private class SSHClient(private val session: Session, private val pass: String) {
fun exec(command: String, timeout: Long = CMD_TIMEOUT): String {
if (!session.isConnected) {
DeployManager.writeError("SSH exec: сессия разорвана перед командой: ${command.take(80)}")
return "error: session is down"
}
var channel: ChannelExec? = null
val result = StringBuilder()
return try {
channel = session.openChannel("exec") as ChannelExec
val cmd = if (command.contains("sudo") && !command.contains("sudo -S")) {
command.replace("sudo ", "sudo -S ")
} else command
channel.setCommand(cmd)
val outStream = channel.outputStream
val input = channel.inputStream
val err = channel.errStream
channel.connect(15000)
if (cmd.contains("sudo -S")) {
outStream.write("$pass\n".toByteArray())
outStream.flush()
}
val reader = input.bufferedReader()
val errReader = err.bufferedReader()
val startTime = System.currentTimeMillis()
val progressRegex = Regex("^WDTT_PROGRESS\\|(\\d+\\.?\\d*)\\|(.+)$")
while (!channel.isClosed || reader.ready() || errReader.ready()) {
if (System.currentTimeMillis() - startTime > timeout) {
DeployManager.writeError("SSH timeout (${timeout/1000}s): ${command.take(80)}")
try { channel.disconnect() } catch (_: Exception) {}
return "error: timeout"
}
if (reader.ready()) {
val line = reader.readLine()
if (line != null) {
val match = progressRegex.find(line.trim())
if (match != null) {
val p = match.groupValues[1].toFloatOrNull() ?: 0f
DeployManager.updateProgress(p, match.groupValues[2])
} else if (!line.contains("WDTT_PROGRESS")) {
val clean = line.replace(Regex("\u001B\\[[;\\d]*m"), "")
result.appendLine(clean)
if (clean.contains("[✗]") || clean.contains("FAIL") ||
(clean.contains("error", true) && !clean.contains("2>/dev/null"))) {
DeployManager.writeError("REMOTE: $clean")
TunnelManager.addDeployErrorLog("REMOTE: $clean")
}
}
}
}
if (errReader.ready()) {
val line = errReader.readLine()
if (line != null && !line.contains("password for")) {
val clean = line.replace(Regex("\u001B\\[[;\\d]*m"), "")
result.appendLine(clean)
if (clean.isNotBlank() && !clean.startsWith("Warning:")) {
DeployManager.writeError("STDERR: $clean")
TunnelManager.addDeployErrorLog("STDERR: $clean")
}
}
}
if (!reader.ready() && !errReader.ready()) Thread.sleep(100)
}
result.toString()
} catch (e: Exception) {
DeployManager.writeError("SSH exec error: ${e.message} | cmd: ${command.take(80)}")
TunnelManager.addDeployErrorLog("SSH exec error: ${e.message}")
"error: ${e.message}"
} finally {
try { channel?.disconnect() } catch (_: Exception) {}
}
}
fun upload(localFile: File, remotePath: String) {
if (!session.isConnected) {
DeployManager.writeError("SSH upload: сессия разорвана")
throw Exception("Session is down")
}
var sftp: ChannelSftp? = null
try {
sftp = session.openChannel("sftp") as ChannelSftp
sftp.connect(15000)
sftp.put(localFile.absolutePath, remotePath)
} catch (e: Exception) {
DeployManager.writeError("SFTP upload error: ${e.message} | file: ${localFile.name}")
throw e
} finally {
try { sftp?.disconnect() } catch (_: Exception) {}
}
}
}
private fun createSSHSession(host: String, user: String, pass: String, port: Int = 22): Session {
val jsch = JSch()
val session = jsch.getSession(user, host, port)
session.setPassword(pass)
session.setConfig(Properties().apply {
put("StrictHostKeyChecking", "no")
put("ServerAliveInterval", "10")
put("ServerAliveCountMax", "6")
put("ConnectTimeout", "15000")
put("PreferredAuthentications", "password,keyboard-interactive")
})
session.connect(20000)
return session
}
private fun shellQuote(value: String): String {
return "'" + value.replace("'", "'\"'\"'") + "'"
}
private fun rootCommand(command: String): String {
val quoted = shellQuote(command)
return "if command -v sudo >/dev/null 2>&1; then sudo 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 File.containsBinaryToken(token: String): Boolean {
val data = readBytes()
val needle = token.toByteArray()
if (needle.isEmpty() || data.size < needle.size) return false
for (i in 0..data.size - needle.size) {
var matched = true
for (j in needle.indices) {
if (data[i + j] != needle[j]) {
matched = false
break
}
}
if (matched) return true
}
return false
}
private fun isUnsafeLegacyServerAsset(serverFile: File): Boolean {
return serverFile.containsBinaryToken("/etc/wireguard") ||
(serverFile.containsBinaryToken("wg0") && !serverFile.containsBinaryToken("wdtt0"))
}
// ==================== Deploy ====================
private suspend fun performDeploy(
context: Context,
host: String, user: String, pass: String, port: Int,
mainPass: String, adminId: String, botToken: String,
dtlsPort: Int, wgPort: Int, dns1: String, dns2: String,
onProgress: (Float, String) -> Unit
): Boolean = withContext(Dispatchers.IO) {
var session: Session? = null
try {
onProgress(0.02f, "Подключение...")
session = createSSHSession(host, user, pass, port)
DeployManager.activeSession = session
val ssh = SSHClient(session, pass)
onProgress(0.05f, "Подготовка файлов...")
val passArg = if (mainPass.isNotBlank()) "-password $mainPass " else ""
val adminArg = if (adminId.isNotBlank()) "-admin $adminId " else ""
val botArg = if (botToken.isNotBlank()) "-bot-token $botToken " else ""
// -dns поддерживается сервером (server.go, флаг -dns). Передаём только при заданном
// значении; несколько адресов — через запятую. Пустые поля -> сервер берёт свой default.
val dnsValue = listOf(dns1, dns2).map { it.trim() }.filter { it.isNotEmpty() }.joinToString(",")
val dnsArg = if (dnsValue.isNotEmpty()) "-dns $dnsValue " else ""
val args = "$passArg$adminArg$botArg$dnsArg".trim()
val scriptFile = File(context.cacheDir, "deploy.sh")
val serverFile = File(context.cacheDir, "server")
try {
context.assets.open("deploy.sh").use { inp -> FileOutputStream(scriptFile).use { out -> inp.copyTo(out) } }
context.assets.open("server").use { inp -> FileOutputStream(serverFile).use { out -> inp.copyTo(out) } }
} catch (e: Exception) {
DeployManager.writeError("Assets extraction failed: ${e.message}")
DeployManager.stopDeploy("Ошибка: файлы не найдены в assets")
return@withContext false
}
if (isUnsafeLegacyServerAsset(serverFile)) {
scriptFile.delete()
serverFile.delete()
DeployManager.writeError("Unsafe legacy server asset: найдено wg0 или /etc/wireguard. Нужна пересборка server под wdtt0 и /etc/wdtt.")
DeployManager.stopDeploy("Нужна пересборка server asset")
return@withContext false
}
onProgress(0.06f, "Загрузка на сервер...")
ssh.upload(scriptFile, "/tmp/deploy.sh")
ssh.upload(serverFile, "/tmp/wdtt-server")
scriptFile.delete()
serverFile.delete()
onProgress(0.08f, "Установка...")
val output = ssh.exec(
rootCommand("env WDTT_ARGS=${shellQuote(args)} WDTT_DTLS_PORT=$dtlsPort WDTT_WG_PORT=$wgPort WDTT_SSH_PORT=$port bash /tmp/deploy.sh"),
timeout = CMD_TIMEOUT
)
if (output.contains("✅") || output.contains("Деплой успешно") || output.contains("active")) {
DeployManager.stopDeploy("success")
TunnelManager.addDeploySuccessLog("Деплой успешно завершен. Сервис активен.")
return@withContext true
} else if (output.contains("error:")) {
DeployManager.writeError("Deploy script output contains error")
DeployManager.stopDeploy("Ошибка выполнения скрипта (см. errors.log)")
return@withContext false
} else {
DeployManager.stopDeploy("success")
TunnelManager.addDeploySuccessLog("Деплой завершён. (Проверьте подключение)")
return@withContext true
}
} catch (e: Exception) {
DeployManager.writeError("Deploy critical: ${e.message}\n${e.stackTraceToString().take(500)}")
DeployManager.stopDeploy("Ошибка: ${e.message?.take(100)}")
return@withContext false
} finally {
try { session?.disconnect() } catch (_: Exception) {}
DeployManager.activeSession = null
}
}
// ==================== Uninstall ====================
private suspend fun performUninstall(
host: String, user: String, pass: String, port: Int,
dtlsPort: Int, wgPort: Int,
onProgress: (Float, String) -> Unit
) = withContext(Dispatchers.IO) {
var session: Session? = null
try {
onProgress(0.05f, "Подключение...")
session = createSSHSession(host, user, pass, port)
DeployManager.activeSession = session
val ssh = SSHClient(session, pass)
onProgress(0.15f, "Остановка сервиса...")
ssh.exec(
rootCommand(
"systemctl unmask wdtt 2>/dev/null || true; " +
"systemctl stop wdtt 2>/dev/null || true; " +
"systemctl disable wdtt 2>/dev/null || true; " +
"rm -f /etc/systemd/system/wdtt.service; " +
"systemctl daemon-reload 2>/dev/null || true"
),
timeout = 15000L
)
onProgress(0.30f, "Удаление через deploy.sh...")
ssh.exec(rootCommand("[ -f /tmp/deploy.sh ] && env WDTT_DTLS_PORT=$dtlsPort WDTT_WG_PORT=$wgPort WDTT_SSH_PORT=$port bash /tmp/deploy.sh uninstall 2>/dev/null || true"), timeout = 30000L)
onProgress(0.45f, "Удаление бинарника...")
ssh.exec(rootCommand("pkill -x wdtt-server 2>/dev/null || true; rm -f /usr/local/bin/wdtt-server"), timeout = 10000L)
onProgress(0.60f, "Очистка firewall...")
ssh.exec(
rootCommand(
"if command -v iptables >/dev/null 2>&1; then " +
"for i in 1 2 3 4 5; do " +
"for iface in $(ls /sys/class/net 2>/dev/null || true); do " +
"iptables -t nat -D POSTROUTING -s 10.66.66.0/24 -o \"${'$'}iface\" -m comment --comment WDTT_MANAGED -j MASQUERADE 2>/dev/null || true; " +
"done; " +
"iptables -D INPUT -p udp --dport $dtlsPort -m comment --comment WDTT_MANAGED -j ACCEPT 2>/dev/null || true; " +
"iptables -D INPUT -p udp --dport $wgPort -m comment --comment WDTT_MANAGED -j ACCEPT 2>/dev/null || true; " +
"iptables -D INPUT -p udp --dport 56000 -m comment --comment WDTT_MANAGED -j ACCEPT 2>/dev/null || true; " +
"iptables -D INPUT -p udp --dport 56001 -m comment --comment WDTT_MANAGED -j ACCEPT 2>/dev/null || true; " +
"iptables -D INPUT -p tcp --dport $port -m comment --comment WDTT_MANAGED -j ACCEPT 2>/dev/null || true; " +
"iptables -D INPUT -p tcp --dport 22 -m comment --comment WDTT_MANAGED -j ACCEPT 2>/dev/null || true; " +
"iptables -D FORWARD -i wdtt0 -m comment --comment WDTT_MANAGED -j ACCEPT 2>/dev/null || true; " +
"iptables -D FORWARD -o wdtt0 -m comment --comment WDTT_MANAGED -j ACCEPT 2>/dev/null || true; " +
"done; fi; " +
"if command -v nft >/dev/null 2>&1; then " +
"nft delete table ip wdtt 2>/dev/null || true; " +
"nft delete table inet wdtt 2>/dev/null || true; " +
"nft delete table inet wdtt_mangle 2>/dev/null || true; " +
"fi"
),
timeout = 15000L
)
onProgress(0.75f, "Удаление WDTT-интерфейса...")
ssh.exec(
rootCommand(
"ip link show wdtt0 >/dev/null 2>&1 && ip link del wdtt0 2>/dev/null || true; " +
"[ -d /etc/wdtt ] && find /etc/wdtt -mindepth 1 -maxdepth 1 ! -name passwords.json -exec rm -rf {} + 2>/dev/null || true; " +
"[ -f /etc/wdtt/passwords.json ] && chmod 600 /etc/wdtt/passwords.json 2>/dev/null || true"
),
timeout = 10000L
)
onProgress(0.90f, "Очистка sysctl...")
ssh.exec(rootCommand("rm -f /etc/sysctl.d/99-wdtt.conf; sysctl --system >/dev/null 2>&1 || true"), timeout = 15000L)
onProgress(1.0f, "Готово!")
DeployManager.stopDeploy("success")
} catch (e: Exception) {
DeployManager.writeError("Uninstall error: ${e.message}")
DeployManager.stopDeploy("Ошибка: ${e.message?.take(100)}")
} finally {
try { session?.disconnect() } catch (_: Exception) {}
DeployManager.activeSession = null
}
}
// ==================== Dialogs ====================
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeploySecretsDialog(
settingsStore: SettingsStore,
initialMainPass: String,
initialAdminId: String,
initialBotToken: String,
initialSshPort: String,
manualPortsEnabled: Boolean,
initialServerDtlsPort: String,
initialServerWgPort: String,
onSaved: (String, String) -> Unit,
onDismiss: () -> Unit
) {
val scope = rememberCoroutineScope()
var passInput by rememberSaveable { mutableStateOf(initialMainPass) }
var adminIdInput by rememberSaveable { mutableStateOf(initialAdminId) }
var botTokenInput by rememberSaveable { mutableStateOf(initialBotToken) }
var sshPortInput by rememberSaveable { mutableStateOf(if (initialSshPort.isBlank()) "22" else initialSshPort) }
var dtlsPortInput by rememberSaveable { mutableStateOf(initialServerDtlsPort.ifBlank { "56000" }) }
var wgPortInput by rememberSaveable { mutableStateOf(initialServerWgPort.ifBlank { "56001" }) }
fun normalizePort(value: String, fallback: String): String {
return value.toIntOrNull()?.takeIf { it in 1..65535 }?.toString() ?: fallback
}
androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
tonalElevation = 8.dp
) {
Column(modifier = Modifier.padding(24.dp).fillMaxWidth().verticalScroll(rememberScrollState())) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text("Секреты Деплоя", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
Spacer(Modifier.height(16.dp))
val isPasswordValid = passInput.isNotEmpty() && passInput.matches(Regex("^[a-zA-Z0-9_.!?:#/-]+$"))
OutlinedTextField(
value = passInput,
onValueChange = { passInput = it.filter { c -> !c.isWhitespace() } },
label = { Text("Задайте пароль туннеля (любой)") },
placeholder = { Text("Придумайте надежный пароль") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
isError = passInput.isNotEmpty() && !isPasswordValid,
supportingText = if (passInput.isNotEmpty() && !isPasswordValid) {
{ Text("Разрешены только буквы, цифры и симв: _ . ! ? : # - /", color = MaterialTheme.colorScheme.error) }
} else null
)
Spacer(Modifier.height(16.dp))
HorizontalDivider()
Spacer(Modifier.height(8.dp))
Text("Телеграм бот для управления", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = adminIdInput,
onValueChange = { adminIdInput = it },
label = { Text("ID Админа (Опционально)") },
placeholder = { Text("ID из @getmyid_bot") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number
)
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = botTokenInput,
onValueChange = { botTokenInput = it },
label = { Text("Токен Бота (Опционально)") },
placeholder = { Text("Токен от BotFather") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp)
)
Spacer(Modifier.height(16.dp))
HorizontalDivider()
Spacer(Modifier.height(8.dp))
Text("SSH Порт", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = sshPortInput,
onValueChange = { sshPortInput = it.filter(Char::isDigit).take(5) },
label = { Text("Порт для деплоя SSH") },
placeholder = { Text("22") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number
)
)
if (manualPortsEnabled) {
Spacer(Modifier.height(16.dp))
HorizontalDivider()
Spacer(Modifier.height(8.dp))
Text("Порты сервера", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = dtlsPortInput,
onValueChange = { dtlsPortInput = it.filter(Char::isDigit).take(5) },
label = { Text("Порт DTLS сервера") },
placeholder = { Text("56000") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number
)
)
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = wgPortInput,
onValueChange = { wgPortInput = it.filter(Char::isDigit).take(5) },
label = { Text("Порт WireGuard сервера") },
placeholder = { Text("56001") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
keyboardType = androidx.compose.ui.text.input.KeyboardType.Number
)
)
}
Spacer(Modifier.height(24.dp))
Button(
onClick = {
val finalPort = if (sshPortInput.isBlank()) "22" else sshPortInput
val finalDtls = normalizePort(dtlsPortInput, "56000")
val finalWg = normalizePort(wgPortInput, "56001")
scope.launch {
settingsStore.saveDeploySecrets(passInput, adminIdInput, botTokenInput, finalPort)
settingsStore.savePorts(finalDtls.toInt(), finalWg.toInt(), settingsStore.listenPort.first())
onSaved(finalDtls, finalWg)
onDismiss()
}
},
modifier = Modifier.fillMaxWidth().height(48.dp),
shape = RoundedCornerShape(16.dp),
enabled = isPasswordValid,
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary)
) { Text("Сохранить", fontWeight = FontWeight.SemiBold) }
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UninstallConfirmDialog(onDismiss: () -> Unit, onConfirm: () -> Unit) {
var confirmText by remember { mutableStateOf("") }
val isConfirmed = confirmText.trim().lowercase() == "да"
androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) {
Surface(
shape = RoundedCornerShape(24.dp),
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
tonalElevation = 8.dp
) {
Column(modifier = Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
Text(
"Удаление WDTT с сервера",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.error
)
Text(
"Будут удалены: бинарник, systemd-сервис, бот, конфигурация WDTT и только помеченные правила firewall/NAT для WDTT.\n\nЭто действие необратимо.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
OutlinedTextField(
value = confirmText,
onValueChange = { confirmText = it },
label = { Text("Введите «да» для подтверждения") },
singleLine = true,
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(16.dp),
colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = MaterialTheme.colorScheme.error,
unfocusedBorderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
)
)
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
OutlinedButton(
onClick = onDismiss, modifier = Modifier.weight(1f).height(48.dp),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.onSurface)
) { Text("Отмена") }
Button(
onClick = onConfirm, modifier = Modifier.weight(1f).height(48.dp),
shape = RoundedCornerShape(16.dp), enabled = isConfirmed,
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.error,
contentColor = MaterialTheme.colorScheme.onError
)
) {
Icon(Icons.Default.Delete, null, Modifier.size(18.dp))
Spacer(Modifier.width(6.dp))
Text("Удалить", fontWeight = FontWeight.Bold)
}
}
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.util.Log
import kotlinx.coroutines.Dispatchers
@@ -14,14 +14,14 @@ const val UPDATE_DIALOG_ACTION_POSTPONED = "postponed"
const val UPDATE_DIALOG_ACTION_UPDATE = "update"
private const val UPDATE_LOG_TAG = "WDTT"
private const val GITHUB_RELEASES_URL = "https://api.github.com/repos/amurcanov/proxy-turn-vk-android/releases?per_page=30"
private const val GITHUB_LATEST_RELEASE_URL = "https://api.github.com/repos/amurcanov/proxy-turn-vk-android/releases/latest"
private const val GITHUB_LATEST_RELEASE_WEB_URL = "https://github.com/amurcanov/proxy-turn-vk-android/releases/latest"
private const val GITHUB_RELEASE_TAG_URL_PREFIX = "https://github.com/amurcanov/proxy-turn-vk-android/releases/tag/"
private const val GITHUB_TAGS_URL = "https://api.github.com/repos/amurcanov/proxy-turn-vk-android/tags?per_page=100"
private const val GITHUB_TAG_TREE_URL_PREFIX = "https://github.com/amurcanov/proxy-turn-vk-android/tree/"
private const val GITHUB_RELEASES_URL = "https://api.github.com/repos/Ivan4537/WDTT-Plus/releases?per_page=30"
private const val GITHUB_LATEST_RELEASE_URL = "https://api.github.com/repos/Ivan4537/WDTT-Plus/releases/latest"
private const val GITHUB_LATEST_RELEASE_WEB_URL = "https://github.com/Ivan4537/WDTT-Plus/releases/latest"
private const val GITHUB_RELEASE_TAG_URL_PREFIX = "https://github.com/Ivan4537/WDTT-Plus/releases/tag/"
private const val GITHUB_TAGS_URL = "https://api.github.com/repos/Ivan4537/WDTT-Plus/tags?per_page=100"
private const val GITHUB_TAG_TREE_URL_PREFIX = "https://github.com/Ivan4537/WDTT-Plus/tree/"
private const val GITHUB_API_RATE_LIMIT_FALLBACK_MS = 30L * 60L * 1000L
private val VERSION_NUMBER_REGEX = Regex("\\d+(?:\\.\\d+)*")
private val SIMPLE_VERSION_TAG_REGEX = Regex("^v?(\\d+)$", RegexOption.IGNORE_CASE)
@Volatile
private var githubApiCooldownUntilMs = 0L
@@ -253,14 +253,17 @@ private fun JSONObject.toAppReleaseInfo(): AppReleaseInfo? {
}
private fun versionParts(version: String): List<Int> {
val normalized = VERSION_NUMBER_REGEX.find(version.trim())?.value ?: return emptyList()
return normalized.split(".").mapNotNull { it.toIntOrNull() }
return listOfNotNull(versionNumber(version))
}
private fun normalizeVersionTag(version: String): String {
val trimmed = version.trim()
if (trimmed.isBlank()) return ""
return if (trimmed.startsWith("v", ignoreCase = true)) trimmed else "v$trimmed"
val number = versionNumber(version) ?: return ""
return "v$number"
}
private fun versionNumber(version: String): Int? {
val match = SIMPLE_VERSION_TAG_REGEX.matchEntire(version.trim()) ?: return null
return match.groupValues.getOrNull(1)?.toIntOrNull()
}
private fun extractTagFromReleaseUrl(releaseUrl: String): String? {
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.annotation.SuppressLint
import android.content.Context
@@ -22,6 +22,8 @@ import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.security.MessageDigest
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import kotlin.coroutines.cancellation.CancellationException
import kotlin.random.Random
@@ -30,30 +32,31 @@ import kotlin.random.Random
* Управляет «невидимым» WebView для автоматического прохождения VK Smart Captcha.
*
* Один запрос = один свежий WebView:
* 1. Создаёт WebView с рандомизированным fingerprint (UA, viewport)
* 1. Создаёт WebView с системным Android fingerprint и варьируемым viewport
* 2. Загружает redirect_uri, ждёт короткую паузу загрузки
* 3. Находит чекбокс "Я не робот" (label.vkc__Checkbox-module__Checkbox)
* 4. Кликает в рандомную точку внутри label с коротким human-like таймингом
* 3. Находит чекбокс "Я не робот"
* 4. Кликает в рандомную точку внутри квадратной зоны чекбокса
* 5. JS-interceptor перехватывает captchaNotRobot.check → success_token
* 6. Уничтожает WebView
*/
object CaptchaWebViewManager {
private const val TAG = "CaptchaWV"
private const val CAPTCHA_TIMEOUT_MS = 10_000L
private const val CAPTCHA_TIMEOUT_MS = 18_000L
private const val WV_CREATE_TIMEOUT_MS = 3000L
private const val AUTO_PROBE_ATTEMPTS = 16
private const val AUTO_PROBE_INTERVAL_MS = 350L
private const val AUTO_CHECK_REQUEST_TIMEOUT_MS = 3_500L
private const val AUTO_POST_CLICK_TIMEOUT_MS = 8_000L
const val ERROR_SLIDER_DETECTED = "slider_detected"
const val ERROR_CHECKBOX_NOT_FOUND = "checkbox_not_found"
const val ERROR_AUTO_CHECK_NOT_SENT = "auto_check_not_sent"
const val ERROR_AUTO_NO_RESULT = "auto_no_result"
// Рандомизируемые параметры viewport (чтобы VK не видел одинаковый size)
private val VIEWPORT_WIDTHS = intArrayOf(356, 358, 360, 362, 364, 366, 368)
private val VIEWPORT_HEIGHTS = intArrayOf(376, 378, 380, 382, 384, 386, 388)
// Пул Chrome-версий (minor builds) для варьирования
private val CHROME_BUILDS = arrayOf(
"146.0.0.0", "145.0.6422.60", "145.0.6422.53",
"144.0.6367.78", "144.0.6367.61", "143.0.6312.99"
)
private val mainHandler = Handler(Looper.getMainLooper())
private val captchaMutex = Mutex()
@@ -65,6 +68,9 @@ object CaptchaWebViewManager {
private val pendingResult = AtomicReference<CompletableDeferred<Result<String>>?>(null)
private val postClickSliderWatcher = AtomicReference<Runnable?>(null)
private val postClickCheckRequestWatchdog = AtomicReference<Runnable?>(null)
private val postClickResultWatchdog = AtomicReference<Runnable?>(null)
private val postClickCheckRequestSeen = AtomicBoolean(false)
@Volatile
private var currentWebView: WebView? = null
@@ -75,17 +81,51 @@ object CaptchaWebViewManager {
if (window.__wdtt_interceptor_installed) return;
window.__wdtt_interceptor_installed = true;
function getParam(body, key) {
try {
if (!body) return '';
if (typeof body === 'string') return new URLSearchParams(body).get(key) || '';
if (body instanceof URLSearchParams) return body.get(key) || '';
if (body instanceof FormData) return body.get(key) || '';
} catch(e) {}
return '';
}
function reportPayload(body) {
try {
const browserFp = getParam(body, 'browser_fp');
const adFp = getParam(body, 'adFp');
const debugInfo = getParam(body, 'debug_info');
if (browserFp || adFp || debugInfo) {
window.WdttCaptcha.onCheckPayload(browserFp || '', adFp || '', debugInfo || '');
}
} catch(e) {}
}
const origFetch = window.fetch;
window.fetch = async function() {
const args = arguments;
const url = args[0] || '';
if (typeof url === 'string' && url.includes('captchaNotRobot.check')) {
const input = args[0];
const url = typeof input === 'string'
? input
: (input && input.url ? input.url : String(input || ''));
if (url.includes('captchaNotRobot.check')) {
window.WdttCaptcha.onCheckRequest();
reportPayload(args[1] && args[1].body);
const response = await origFetch.apply(this, args);
const clone = response.clone();
try {
const data = await clone.json();
if (data.response && data.response.success_token) {
window.WdttCaptcha.onSuccess(data.response.success_token);
} else if (data.response && data.response.status) {
window.WdttCaptcha.onCheckStatus(
data.response.status || '',
data.response.show_captcha_type || ''
);
if (data.response.show_captcha_type === 'slider') {
window.WdttCaptcha.onSliderDetected('check_response');
}
} else if (
data.response &&
data.response.show_captcha_type === 'slider'
@@ -103,17 +143,27 @@ object CaptchaWebViewManager {
const origXHROpen = XMLHttpRequest.prototype.open;
const origXHRSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function(method, url) {
this._wdtt_url = url;
this._wdtt_url = url && url.toString ? url.toString() : String(url || '');
return origXHROpen.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function() {
const xhr = this;
if (xhr._wdtt_url && xhr._wdtt_url.includes('captchaNotRobot.check')) {
window.WdttCaptcha.onCheckRequest();
reportPayload(arguments[0]);
xhr.addEventListener('load', function() {
try {
const data = JSON.parse(xhr.responseText);
if (data.response && data.response.success_token) {
window.WdttCaptcha.onSuccess(data.response.success_token);
} else if (data.response && data.response.status) {
window.WdttCaptcha.onCheckStatus(
data.response.status || '',
data.response.show_captcha_type || ''
);
if (data.response.show_captcha_type === 'slider') {
window.WdttCaptcha.onSliderDetected('check_response');
}
} else if (
data.response &&
data.response.show_captcha_type === 'slider'
@@ -130,6 +180,57 @@ object CaptchaWebViewManager {
})();
""".trimIndent()
private val fingerprintProbeJSCode = """
(function() {
try {
var canvasOk = false;
try {
var canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 16;
var ctx = canvas.getContext('2d');
canvasOk = !!ctx;
if (ctx) {
ctx.fillText('wdtt', 2, 12);
canvas.toDataURL();
}
} catch(e) {}
var webgl = 'none';
try {
var glCanvas = document.createElement('canvas');
var gl = glCanvas.getContext('webgl') || glCanvas.getContext('experimental-webgl');
if (gl) {
var ext = gl.getExtension('WEBGL_debug_renderer_info');
if (ext) {
var vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) || '';
var renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) || '';
webgl = vendor + ' / ' + renderer;
} else {
webgl = 'available';
}
}
} catch(e) {}
window.WdttCaptcha.onFingerprintProbe(JSON.stringify({
webdriver: navigator.webdriver === true,
ua: navigator.userAgent || '',
platform: navigator.platform || '',
languages: navigator.languages ? navigator.languages.join(',') : navigator.language || '',
touch: navigator.maxTouchPoints || 0,
hw: navigator.hardwareConcurrency || 0,
dpr: window.devicePixelRatio || 0,
screen: (screen.width || 0) + 'x' + (screen.height || 0),
inner: window.innerWidth + 'x' + window.innerHeight,
canvas: canvasOk,
webgl: webgl
}));
} catch(e) {
window.WdttCaptcha.onFingerprintProbe('probe_error:' + e.message);
}
})();
""".trimIndent()
// ═══════════════════════════════════════════════════════════════
// Lifecycle
// ═══════════════════════════════════════════════════════════════
@@ -177,6 +278,7 @@ object CaptchaWebViewManager {
private suspend fun doSolveCaptcha(context: Context, redirectUri: String, onStep: (String) -> Unit): String {
val deferred = CompletableDeferred<Result<String>>()
pendingResult.set(deferred)
postClickCheckRequestSeen.set(false)
val webView = createWebViewSync(context, onStep)
?: throw IllegalStateException("Не удалось создать WebView")
@@ -212,10 +314,9 @@ object CaptchaWebViewManager {
// Рандомизируем параметры для КАЖДОГО запроса
val vw = VIEWPORT_WIDTHS[Random.Default.nextInt(VIEWPORT_WIDTHS.size)]
val vh = VIEWPORT_HEIGHTS[Random.Default.nextInt(VIEWPORT_HEIGHTS.size)]
val chromeBuild = CHROME_BUILDS[Random.Default.nextInt(CHROME_BUILDS.size)]
val ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/$chromeBuild Safari/537.36"
val ua = android.webkit.WebSettings.getDefaultUserAgent(context)
Log.d(TAG, "Fingerprint: ${vw}x${vh}, Chrome/$chromeBuild")
Log.d(TAG, "Fingerprint: системный Android WebView, viewport=${vw}x${vh}")
val latch = CountDownLatch(1)
var webView: WebView? = null
@@ -252,6 +353,7 @@ object CaptchaWebViewManager {
val isCaptchaPage = url?.let {
it.contains("not_robot_captcha") ||
it.contains("id.vk.ru/captcha") ||
it.contains("id.vk.com/captcha") ||
it.contains("not_robot")
} ?: false
@@ -260,8 +362,8 @@ object CaptchaWebViewManager {
view.evaluateJavascript(interceptorJSCode, null)
if (currentWebView === view && isTunnelActive) {
// Быстрый auto-pass: WebView получает такой же короткий темп, как Go v2.
val pageLoadDelay = 650L + Random.Default.nextLong(0, 550)
view.evaluateJavascript(fingerprintProbeJSCode, null)
val pageLoadDelay = 900L + Random.Default.nextLong(0, 800)
mainHandler.postDelayed({
if (currentWebView === view && isTunnelActive) {
solveCaptchaAutomatedSync(view)
@@ -329,7 +431,7 @@ object CaptchaWebViewManager {
private fun destroyCurrentWebView() {
val wv = currentWebView ?: return
currentWebView = null
postClickSliderWatcher.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
clearPostClickWatchers()
val destroyAction = Runnable {
try {
@@ -371,7 +473,7 @@ object CaptchaWebViewManager {
// кликаем в РАНДОМНУЮ точку внутри него (не в центр).
// ═══════════════════════════════════════════════════════════════
private fun solveCaptchaAutomatedSync(webView: WebView) {
private fun solveCaptchaAutomatedSync(webView: WebView, attemptsLeft: Int = AUTO_PROBE_ATTEMPTS) {
if (currentWebView !== webView || !isTunnelActive) return
// Ищем LABEL целиком (он большой, ~200x32px — как человек кликает).
@@ -381,26 +483,40 @@ object CaptchaWebViewManager {
var slider = document.querySelector(
'[class*="SliderCaptcha"], [class*="Kaleidoscope"], ' +
'.vkc__SliderCaptcha-module__description, ' +
'.vkc__KaleidoscopeScreen-module__captchaId'
'.vkc__KaleidoscopeScreen-module__captchaId, ' +
'.vkc__SwipeButton-module__track, ' +
'[class*="SwipeButton"]'
);
if (slider) return '${ERROR_SLIDER_DETECTED}';
// Приоритет: label обёртка (самый большой кликабельный элемент)
function visibleRect(node) {
if (!node) return null;
var rect = node.getBoundingClientRect();
var style = window.getComputedStyle(node);
if (rect.width < 5 || rect.height < 5 ||
style.display === 'none' || style.visibility === 'hidden') {
return null;
}
return rect;
}
// Приоритет: квадрат чекбокса. У VK text-area label иногда уже не отправляет check.
var el = document.querySelector('label.vkc__Checkbox-module__Checkbox');
// Fallback: прямой поиск по ID
if (!el) el = document.querySelector('label[for="not-robot-captcha-checkbox"]');
// Fallback: сам чекбокс
if (!el) el = document.getElementById('not-robot-captcha-checkbox');
if (!el) return 'not_found';
var rect = el.getBoundingClientRect();
var style = window.getComputedStyle(el);
if (rect.width < 5 || rect.height < 5 ||
style.display === 'none' || style.visibility === 'hidden') {
return 'not_found';
var icon = el.querySelector && el.querySelector(
'[class*="Checkbox__iconBlock"], [class*="iconBlock"], [class*="IconBlock"]'
);
var iconRect = visibleRect(icon);
if (iconRect) {
return 'icon,' + iconRect.left + ',' + iconRect.top + ',' + iconRect.width + ',' + iconRect.height;
}
// Возвращаем left,top,width,height — чтобы кликнуть в РАНДОМНУЮ точку
return rect.left + ',' + rect.top + ',' + rect.width + ',' + rect.height;
var rect = visibleRect(el);
if (!rect) return 'not_found';
return 'label,' + rect.left + ',' + rect.top + ',' + rect.width + ',' + rect.height;
})();
""".trimIndent()
@@ -416,44 +532,42 @@ object CaptchaWebViewManager {
return@evaluateJavascript
}
if (result == "not_found" || result.split(",").size < 4) {
// Fallback: JS .click() — не идеально, но лучше чем ничего
Log.w(TAG, "Label не найден — JS-клик (fallback)")
val jsClick = """
(function() {
var el = document.querySelector('label.vkc__Checkbox-module__Checkbox');
if (!el) el = document.getElementById('not-robot-captcha-checkbox');
if (el) { el.click(); return 'clicked'; }
return 'nothing';
})();
""".trimIndent()
webView.evaluateJavascript(jsClick) { clickResult ->
if ((clickResult ?: "").replace("\"", "") == "clicked") {
startPostClickSliderWatcher(webView)
}
if (result == "not_found" || result.split(",").size < 5) {
if (attemptsLeft > 1) {
mainHandler.postDelayed({
solveCaptchaAutomatedSync(webView, attemptsLeft - 1)
}, AUTO_PROBE_INTERVAL_MS)
} else {
Log.i(TAG, "Checkbox не найден — fallback на следующую стадию")
notifyResult(Result.failure(IllegalStateException(ERROR_CHECKBOX_NOT_FOUND)))
}
return@evaluateJavascript
}
val parts = result.split(",")
val left = parts[0].toFloatOrNull() ?: return@evaluateJavascript
val top = parts[1].toFloatOrNull() ?: return@evaluateJavascript
val width = parts[2].toFloatOrNull() ?: return@evaluateJavascript
val height = parts[3].toFloatOrNull() ?: return@evaluateJavascript
val target = parts[0]
val left = parts[1].toFloatOrNull() ?: return@evaluateJavascript
val top = parts[2].toFloatOrNull() ?: return@evaluateJavascript
val width = parts[3].toFloatOrNull() ?: return@evaluateJavascript
val height = parts[4].toFloatOrNull() ?: return@evaluateJavascript
// Рандомная точка внутри label (60-90% ширины, 25-75% высоты)
// Человек кликает не ровно в центр, а примерно туда
val randX = left + width * (0.15f + Random.Default.nextFloat() * 0.7f)
val randX = if (target == "icon") {
left + width * (0.25f + Random.Default.nextFloat() * 0.5f)
} else {
left + (height * (0.35f + Random.Default.nextFloat() * 0.3f)).coerceAtMost(width * 0.35f)
}
val randY = top + height * (0.25f + Random.Default.nextFloat() * 0.5f)
Log.d(TAG, "Клик: (${randX.toInt()}, ${randY.toInt()}) в зоне ${width.toInt()}x${height.toInt()}")
Log.d(TAG, "Клик: (${randX.toInt()}, ${randY.toInt()}) target=$target zone=${width.toInt()}x${height.toInt()}")
val thinkDelay = 420L + Random.Default.nextLong(0, 260)
val thinkDelay = 600L + Random.Default.nextLong(0, 700)
mainHandler.postDelayed({
if (currentWebView === webView && isTunnelActive) {
simulateHumanTouch(webView, randX, randY)
startPostClickSliderWatcher(webView)
startPostClickCheckRequestWatchdog(webView)
startPostClickResultWatchdog(webView)
}
}, thinkDelay)
}
@@ -515,6 +629,46 @@ object CaptchaWebViewManager {
mainHandler.postDelayed(watcher, 450L)
}
private fun startPostClickCheckRequestWatchdog(webView: WebView) {
postClickCheckRequestWatchdog.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
if (pendingResult.get() == null) return
val watchdog = Runnable {
if (currentWebView === webView &&
isTunnelActive &&
pendingResult.get() != null &&
!postClickCheckRequestSeen.get()
) {
Log.i(TAG, "Auto WebView клик не отправил captchaNotRobot.check — fresh challenge")
notifyResult(Result.failure(IllegalStateException(ERROR_AUTO_CHECK_NOT_SENT)))
}
}
postClickCheckRequestWatchdog.set(watchdog)
mainHandler.postDelayed(watchdog, AUTO_CHECK_REQUEST_TIMEOUT_MS)
}
private fun startPostClickResultWatchdog(webView: WebView) {
postClickResultWatchdog.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
if (pendingResult.get() == null) return
val watchdog = Runnable {
if (currentWebView === webView && isTunnelActive && pendingResult.get() != null) {
Log.i(TAG, "Auto WebView не вернул success_token после клика — fresh challenge")
notifyResult(Result.failure(IllegalStateException(ERROR_AUTO_NO_RESULT)))
}
}
postClickResultWatchdog.set(watchdog)
mainHandler.postDelayed(watchdog, AUTO_POST_CLICK_TIMEOUT_MS)
}
private fun clearPostClickWatchers() {
postClickSliderWatcher.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
postClickCheckRequestWatchdog.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
postClickResultWatchdog.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
}
/**
* Имитирует нативный тач как от пальца:
* - ACTION_DOWN с рандомным pressure (0.5-0.9)
@@ -539,8 +693,22 @@ object CaptchaWebViewManager {
webView.dispatchTouchEvent(downEvent)
downEvent.recycle()
// Удержание пальца: 80-180мс
val holdTime = 80L + Random.Default.nextLong(0, 100)
val moveTime = 70L + Random.Default.nextLong(0, 90)
mainHandler.postDelayed({
if (currentWebView === webView) {
val moveX = physX + (-0.8f + Random.Default.nextFloat() * 1.6f) * density
val moveY = physY + (-0.6f + Random.Default.nextFloat() * 1.2f) * density
val moveEvent = MotionEvent.obtain(
downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_MOVE,
moveX, moveY, pressure, 1f, 0, 1f, 1f, 0, 0
)
moveEvent.source = android.view.InputDevice.SOURCE_TOUCHSCREEN
webView.dispatchTouchEvent(moveEvent)
moveEvent.recycle()
}
}, moveTime)
val holdTime = 150L + Random.Default.nextLong(0, 170)
mainHandler.postDelayed({
if (currentWebView === webView) {
@@ -576,6 +744,36 @@ object CaptchaWebViewManager {
notifyResult(Result.failure(IllegalStateException(ERROR_SLIDER_DETECTED)))
}
@JavascriptInterface
fun onCheckStatus(status: String, showType: String) {
Log.i(TAG, "JS: captcha check status=$status show_type=$showType")
when (status.uppercase()) {
"BOT", "ERROR_LIMIT", "ERROR" -> {
notifyResult(Result.failure(IllegalStateException("captcha_check_$status")))
}
}
}
@JavascriptInterface
fun onCheckRequest() {
postClickCheckRequestSeen.set(true)
postClickCheckRequestWatchdog.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
Log.i(TAG, "JS: captcha check request sent")
}
@JavascriptInterface
fun onCheckPayload(browserFp: String, adFp: String, debugInfo: String) {
val fpHash = browserFp.safeHashPrefix()
val adHash = adFp.safeHashPrefix()
val dbgHash = debugInfo.safeHashPrefix()
Log.i(TAG, "JS: check payload browser_fp=${browserFp.length}:$fpHash adFp=${adFp.length}:$adHash debug=${debugInfo.length}:$dbgHash")
}
@JavascriptInterface
fun onFingerprintProbe(data: String) {
Log.i(TAG, "JS: fingerprint probe ${data.take(700)}")
}
@JavascriptInterface
fun onError(error: String) {
Log.e(TAG, "JS: ошибка — $error")
@@ -583,7 +781,14 @@ object CaptchaWebViewManager {
}
}
private fun String.safeHashPrefix(): String {
if (isBlank()) return "-"
val digest = MessageDigest.getInstance("SHA-256").digest(toByteArray(Charsets.UTF_8))
return digest.take(4).joinToString("") { "%02x".format(it) }
}
private fun notifyResult(result: Result<String>) {
clearPostClickWatchers()
val deferred = pendingResult.getAndSet(null) ?: return
if (!deferred.isCompleted) {
deferred.complete(result)
@@ -591,6 +796,7 @@ object CaptchaWebViewManager {
}
private fun cancelPendingResult(reason: String) {
clearPostClickWatchers()
val deferred = pendingResult.getAndSet(null) ?: return
if (!deferred.isCompleted) {
deferred.complete(Result.failure(CancellationException(reason)))
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.content.Context
import kotlinx.coroutines.CoroutineScope
@@ -85,4 +85,8 @@ object DeployManager {
deployProgress.value = progress
currentStep.value = step
}
fun failDeploy(message: String) {
stopDeploy("Ошибка: $message")
}
}
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.Manifest
import android.content.Context
@@ -15,6 +15,7 @@ import android.view.HapticFeedbackConstants
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedContent
@@ -34,9 +35,11 @@ import androidx.compose.foundation.shape.GenericShape
import androidx.compose.foundation.shape.RoundedCornerShape
import kotlinx.coroutines.launch
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.BatterySaver
import androidx.compose.material.icons.filled.Cloud
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.VpnKey
import androidx.compose.material.icons.outlined.Cloud
@@ -61,16 +64,19 @@ import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.LocalDensity
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.core.content.ContextCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.compose.ui.platform.LocalContext
import com.wdtt.client.ui.AppUpdateDialog
import com.wdtt.client.ui.FloatingToolbar
import com.wdtt.client.ui.LogsTab
import com.wdtt.client.ui.SettingsTab
import com.wdtt.client.ui.DeployTab
import com.wdtt.client.ui.ExceptionsTab
import com.wdtt.client.ui.InfoTab
import com.wdtt.plus.ui.AppUpdateDialog
import com.wdtt.plus.ui.FloatingToolbar
import com.wdtt.plus.ui.LogsTab
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 kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.first
@@ -81,18 +87,10 @@ import kotlin.math.min
import kotlin.math.sin
class MainActivity : ComponentActivity() {
private val vpnLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
// VPN permission dialog finished
}
private val batteryLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
checkAndRequestVpn()
}
private val notificationLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
checkAndRequestBattery()
}
private var sharedVkHashResult by mutableStateOf<VkHashInsertResult?>(null)
private var sharedVkHashError by mutableStateOf<String?>(null)
private var wdttDeepLinkMessage by mutableStateOf<String?>(null)
private var pendingWdttDeepLinkPlan by mutableStateOf<WdttDeepLinkApplyPlan?>(null)
companion object {
var activeActivities = 0
@@ -119,20 +117,35 @@ class MainActivity : ComponentActivity() {
enableEdgeToEdge()
checkAndRequestNotifications()
setContent {
val settingsStore = remember { SettingsStore(this) }
val themeMode by settingsStore.themeMode.collectAsStateWithLifecycle(initialValue = "system")
val isDynamicColor by settingsStore.isDynamicColor.collectAsStateWithLifecycle(initialValue = false)
val themePalette by settingsStore.themePalette.collectAsStateWithLifecycle(initialValue = "indigo")
val activeFingerprint by settingsStore.selectedFingerprint.collectAsStateWithLifecycle(initialValue = "chrome")
val activeFingerprint by settingsStore.selectedFingerprint.collectAsStateWithLifecycle(initialValue = "firefox")
val activeClientIds by settingsStore.activeClientIds.collectAsStateWithLifecycle(initialValue = "6287487,8202606")
val scope = rememberCoroutineScope()
WDTTTheme(themeMode = themeMode, dynamicColor = isDynamicColor, themePalette = themePalette) {
MainScreen(
settingsStore = settingsStore,
sharedVkHashResult = sharedVkHashResult,
sharedVkHashError = sharedVkHashError,
onSharedVkHashMessageShown = {
sharedVkHashResult = null
sharedVkHashError = null
},
wdttDeepLinkMessage = wdttDeepLinkMessage,
onWdttDeepLinkMessageShown = { wdttDeepLinkMessage = null },
pendingWdttDeepLinkPlan = pendingWdttDeepLinkPlan,
onConfirmWdttDeepLinkOverwrite = { plan ->
pendingWdttDeepLinkPlan = null
applyWdttDeepLinkPlan(plan)
},
onCancelWdttDeepLinkOverwrite = {
pendingWdttDeepLinkPlan = null
wdttDeepLinkMessage = "Импорт wdtt:// ссылки отменён."
},
themeMode = themeMode,
onThemeChange = { mode ->
scope.launch {
@@ -158,49 +171,342 @@ class MainActivity : ComponentActivity() {
)
}
}
handleIncomingShareIntent(intent)
handleIncomingWdttDeepLink(intent)
}
private fun checkAndRequestNotifications() {
if (Build.VERSION.SDK_INT >= 33) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
notificationLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
} else {
checkAndRequestBattery()
}
} else {
checkAndRequestBattery()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIncomingShareIntent(intent)
handleIncomingWdttDeepLink(intent)
}
private fun checkAndRequestBattery() {
val pm = getSystemService(Context.POWER_SERVICE) as PowerManager
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
try {
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
data = Uri.parse("package:$packageName")
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
lifecycleScope.launch {
val store = SettingsStore(this@MainActivity)
runCatching {
store.createWdttDeepLinkApplyPlan(link)
}.onSuccess { plan ->
if (plan == null) {
wdttDeepLinkMessage = WdttDeepLink.validate(link).userMessage()
} else if (plan.requiresConfirmation) {
pendingWdttDeepLinkPlan = plan
} else {
applyWdttDeepLinkPlan(plan)
}
batteryLauncher.launch(intent)
} catch (e: Exception) {
checkAndRequestVpn()
}.onFailure { error ->
wdttDeepLinkMessage = error.message ?: "Не удалось применить wdtt:// ссылку."
}
} else {
checkAndRequestVpn()
}
}
private fun checkAndRequestVpn() {
try {
val vpnIntent = VpnService.prepare(this)
if (vpnIntent != null) {
vpnLauncher.launch(vpnIntent)
private fun applyWdttDeepLinkPlan(plan: WdttDeepLinkApplyPlan) {
lifecycleScope.launch {
val store = SettingsStore(this@MainActivity)
runCatching {
store.applyWdttDeepLink(plan)
}.onSuccess { result ->
wdttDeepLinkMessage = if (result == null) {
WdttDeepLink.validate(plan.link).userMessage()
} else {
val profileLabel = "VPN ${result.targetProfile + 1}"
val action = if (result.overwritten) "перезаписана" else "добавлена"
val mode = if (result.storedAsLink) "сохранена в режиме ссылки" else "разобрана, поля подключения заполнены"
"Ссылка wdtt:// $action в профиль $profileLabel: $mode."
}
}.onFailure { error ->
wdttDeepLinkMessage = error.message ?: "Не удалось применить wdtt:// ссылку."
}
}
}
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
val hash = VkJoinLink.extractHash(sharedText)
if (hash.length < 16) {
sharedVkHashError = "В переданной ссылке не найден VK-хеш звонка."
return
}
lifecycleScope.launch {
runCatching {
SettingsStore(this@MainActivity).insertVkHashFromShare(hash)
}.onSuccess { result ->
sharedVkHashResult = result
sharedVkHashError = null
}.onFailure { error ->
sharedVkHashError = error.message ?: "Не удалось сохранить VK-хеш."
}
}
}
}
// ═══ Навигация ═══
@Composable
private fun RoleSelectionScreen(
onRoleSelected: (String) -> Unit
) {
Box(modifier = Modifier.fillMaxSize()) {
AppBackdrop(modifier = Modifier.matchParentSize())
Column(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Surface(
shape = RoundedCornerShape(28.dp),
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.94f),
tonalElevation = 8.dp,
shadowElevation = 8.dp,
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(22.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
"Как вы будете использовать WDTT Plus?",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center
)
Text(
"Выбор можно поменять позже в шестерёнке настроек.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
lineHeight = 20.sp
)
RoleChoiceButton(
title = "Я - юзер",
body = "Хочу подключиться к VPN, управлять подключением, исключениями и смотреть логи.",
icon = Icons.Filled.VpnKey,
onClick = { onRoleSelected("user") }
)
RoleChoiceButton(
title = "Я - админ",
body = "Хочу подключаться к VPN и дополнительно настраивать, переносить или обслуживать свой сервер.",
icon = Icons.Filled.Cloud,
onClick = { onRoleSelected("admin") }
)
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
// ═══ Навигация ═══
@Composable
private fun RoleChoiceButton(
title: String,
body: String,
icon: ImageVector,
onClick: () -> Unit
) {
Surface(
onClick = onClick,
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)),
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier.padding(14.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
Surface(
shape = RoundedCornerShape(14.dp),
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
) {
Box(modifier = Modifier.size(44.dp), contentAlignment = Alignment.Center) {
Icon(icon, contentDescription = null, modifier = Modifier.size(22.dp))
}
}
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(
title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
body,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 17.sp
)
}
}
}
}
private enum class PermissionOnboardingStep {
Notifications,
Background
}
@Composable
private fun PermissionOnboardingScreen(
onComplete: () -> Unit
) {
val context = LocalContext.current
var step by rememberSaveable { mutableStateOf(PermissionOnboardingStep.Notifications.name) }
var batteryFallbackVisible by rememberSaveable { mutableStateOf(false) }
val currentStep = PermissionOnboardingStep.valueOf(step)
val notificationPermissionLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) {
step = PermissionOnboardingStep.Background.name
}
val batteryLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
if (pm.isIgnoringBatteryOptimizations(context.packageName)) {
onComplete()
} else {
batteryFallbackVisible = true
}
}
fun requestNotificationsOrNext() {
if (Build.VERSION.SDK_INT >= 33 &&
ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
) {
notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
} else {
step = PermissionOnboardingStep.Background.name
}
}
fun requestBackgroundOrFinish() {
val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
if (pm.isIgnoringBatteryOptimizations(context.packageName)) {
onComplete()
} else if (batteryFallbackVisible) {
runCatching {
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.parse("package:${context.packageName}")
}
context.startActivity(intent)
}.onFailure {
onComplete()
}
} else {
runCatching {
val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).apply {
data = Uri.parse("package:${context.packageName}")
}
batteryLauncher.launch(intent)
}.onFailure {
batteryFallbackVisible = true
}
}
}
Box(modifier = Modifier.fillMaxSize()) {
AppBackdrop(modifier = Modifier.matchParentSize())
Column(
modifier = Modifier
.fillMaxSize()
.padding(24.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Surface(
shape = RoundedCornerShape(28.dp),
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.94f),
tonalElevation = 8.dp,
shadowElevation = 8.dp,
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(22.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
val isNotifications = currentStep == PermissionOnboardingStep.Notifications
Surface(
shape = RoundedCornerShape(22.dp),
color = MaterialTheme.colorScheme.primaryContainer,
contentColor = MaterialTheme.colorScheme.onPrimaryContainer
) {
Box(modifier = Modifier.size(58.dp), contentAlignment = Alignment.Center) {
Icon(
imageVector = if (isNotifications) Icons.Filled.Notifications else Icons.Filled.BatterySaver,
contentDescription = null,
modifier = Modifier.size(30.dp)
)
}
}
Text(
if (isNotifications) "Уведомления" else "Фоновая работа",
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.Black,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center
)
Text(
if (isNotifications) {
"WDTT Plus использует уведомление, чтобы показывать состояние туннеля, ошибки подключения и важные действия вроде капчи. Для полноценной работы приложения без ошибок очень рекомендуется выдать этот доступ."
} else if (batteryFallbackVisible) {
"Системное окно фонового режима не открылось или разрешение не было выдано. Откройте настройки приложения и отключите ограничения батареи для WDTT Plus; это очень рекомендуется для стабильной работы без ошибок."
} else {
"Фоновый режим помогает туннелю не засыпать при выключенном экране, смене сети и долгой работе VPN. Для полноценной работы приложения без ошибок очень рекомендуется разрешить фоновую работу."
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
lineHeight = 21.sp
)
Row(
modifier = Modifier.fillMaxWidth().height(IntrinsicSize.Min),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = {
if (isNotifications) step = PermissionOnboardingStep.Background.name else onComplete()
},
modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp)
) {
Text("Отказать", fontWeight = FontWeight.SemiBold, textAlign = TextAlign.Center)
}
Button(
onClick = {
if (isNotifications) requestNotificationsOrNext() else requestBackgroundOrFinish()
},
modifier = Modifier.weight(1f).fillMaxHeight().heightIn(min = 50.dp),
shape = RoundedCornerShape(16.dp),
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 8.dp)
) {
Text(
if (!isNotifications && batteryFallbackVisible) "Открыть настройки" else "Разрешить",
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
}
}
}
}
}
}
}
private data class NavItem(
val id: Int,
@@ -221,13 +527,21 @@ private val navItems = listOf(
@Composable
fun MainScreen(
settingsStore: SettingsStore,
sharedVkHashResult: VkHashInsertResult? = null,
sharedVkHashError: String? = null,
onSharedVkHashMessageShown: () -> Unit = {},
wdttDeepLinkMessage: String? = null,
onWdttDeepLinkMessageShown: () -> Unit = {},
pendingWdttDeepLinkPlan: WdttDeepLinkApplyPlan? = null,
onConfirmWdttDeepLinkOverwrite: (WdttDeepLinkApplyPlan) -> Unit = {},
onCancelWdttDeepLinkOverwrite: () -> Unit = {},
themeMode: String = "system",
onThemeChange: (String) -> Unit = {},
isDynamicColor: Boolean = false,
onDynamicColorChange: (Boolean) -> Unit = {},
currentPalette: String = "indigo",
onPaletteChange: (String) -> Unit = {},
activeFingerprint: String = "chrome",
activeFingerprint: String = "firefox",
onFingerprintChange: (String) -> Unit = {},
activeClientIds: String = "6287487,8202606",
onClientIdsChange: (String) -> Unit = {}
@@ -240,6 +554,9 @@ fun MainScreen(
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 isAdminInterface = interfaceRole == "admin"
var selectedTab by rememberSaveable { mutableIntStateOf(0) }
var dragTargetIndex by remember { mutableIntStateOf(-1) }
var dragProgress by remember { mutableFloatStateOf(0f) }
@@ -251,11 +568,29 @@ fun MainScreen(
val safeBottomInset = with(density) { WindowInsets.safeDrawing.getBottom(density).toDp() }
val navOverlayReserve = safeBottomInset + 96.dp
val activeNavItems = remember(wdttLinkMode) {
if (wdttLinkMode) {
navItems.filter { it.id != 1 }
} else {
navItems
if (interfaceRole.isBlank()) {
RoleSelectionScreen(
onRoleSelected = { role ->
scope.launch { settingsStore.saveInterfaceRole(role) }
}
)
return
}
if (!permissionOnboardingComplete) {
PermissionOnboardingScreen(
onComplete = {
scope.launch { settingsStore.savePermissionOnboardingComplete(true) }
}
)
return
}
val activeNavItems = remember(wdttLinkMode, isAdminInterface) {
navItems.filter { item ->
val allowedByRole = isAdminInterface || item.id != 1
val allowedByLinkMode = !wdttLinkMode || item.id != 1
allowedByRole && allowedByLinkMode
}
}
val actionsExpanded = rememberSaveable { mutableStateOf(false) }
@@ -263,8 +598,26 @@ fun MainScreen(
LaunchedEffect(wdttLinkMode) {
if (wdttLinkMode && selectedTab == 1) {
LaunchedEffect(wdttLinkMode, interfaceRole) {
if (activeNavItems.none { it.id == selectedTab }) {
selectedTab = 0
}
}
LaunchedEffect(sharedVkHashResult, sharedVkHashError) {
if (sharedVkHashResult != null || sharedVkHashError != null) {
selectedTab = 0
}
}
LaunchedEffect(wdttDeepLinkMessage) {
if (wdttDeepLinkMessage != null) {
selectedTab = 0
}
}
LaunchedEffect(pendingWdttDeepLinkPlan) {
if (pendingWdttDeepLinkPlan != null) {
selectedTab = 0
}
}
@@ -423,6 +776,10 @@ fun MainScreen(
onActiveProfileChange = { profile ->
scope.launch { settingsStore.saveActiveProfile(profile) }
},
interfaceRole = interfaceRole,
onInterfaceRoleChange = { role ->
scope.launch { settingsStore.saveInterfaceRole(role) }
},
currentTheme = themeMode,
onThemeChange = onThemeChange,
isDynamicColor = isDynamicColor,
@@ -468,6 +825,97 @@ fun MainScreen(
}
)
}
sharedVkHashResult?.let { result ->
SharedVkHashDialog(
result = result,
onDismiss = onSharedVkHashMessageShown
)
}
sharedVkHashError?.let { error ->
AlertDialog(
onDismissRequest = onSharedVkHashMessageShown,
title = { Text("VK-хеш не добавлен") },
text = { Text(error) },
confirmButton = {
TextButton(onClick = onSharedVkHashMessageShown) {
Text("Понятно")
}
}
)
}
wdttDeepLinkMessage?.let { message ->
AlertDialog(
onDismissRequest = onWdttDeepLinkMessageShown,
title = { Text("Ссылка WDTT") },
text = { Text(message) },
confirmButton = {
TextButton(onClick = onWdttDeepLinkMessageShown) {
Text("ОК")
}
}
)
}
pendingWdttDeepLinkPlan?.let { plan ->
val profileLabel = "VPN ${plan.targetProfile + 1}"
AlertDialog(
onDismissRequest = onCancelWdttDeepLinkOverwrite,
title = { Text("Профили VPN заполнены") },
text = {
Text(
"Свободных профилей VPN нет. Ссылка перезапишет профиль $profileLabel. Выполнить действие?"
)
},
confirmButton = {
TextButton(onClick = { onConfirmWdttDeepLinkOverwrite(plan) }) {
Text("Да")
}
},
dismissButton = {
TextButton(onClick = onCancelWdttDeepLinkOverwrite) {
Text("Нет")
}
}
)
}
}
@Composable
private fun SharedVkHashDialog(
result: VkHashInsertResult,
onDismiss: () -> Unit
) {
val previous = result.previousHash
AlertDialog(
onDismissRequest = onDismiss,
title = { Text("VK-хеш добавлен") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Слот VK Хеш ${result.slot} обновлён.")
Text(
text = result.hash,
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.primary
)
if (previous.isNotBlank()) {
Text(
text = "Предыдущее значение было перезаписано: $previous",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
},
confirmButton = {
TextButton(onClick = onDismiss) {
Text("Понятно")
}
}
)
}
@Composable
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.app.NotificationChannel
import android.app.NotificationManager
@@ -8,6 +8,7 @@ import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.ViewGroup
import android.webkit.*
import androidx.activity.ComponentActivity
@@ -41,7 +42,7 @@ import kotlin.random.Random
object ManlCaptchaWebViewManager {
private const val TAG = "ManlCaptchaWV"
private const val CAPTCHA_TIMEOUT_MS = 60_000L
private const val CAPTCHA_TIMEOUT_MS = 180_000L
val captchaMutex = Mutex()
val pendingResult = AtomicReference<CompletableDeferred<Result<String>>?>(null)
@@ -162,17 +163,48 @@ class ManlCaptchaActivity : ComponentActivity() {
if (window.__wdtt_interceptor_installed) return;
window.__wdtt_interceptor_installed = true;
function getParam(body, key) {
try {
if (!body) return '';
if (typeof body === 'string') return new URLSearchParams(body).get(key) || '';
if (body instanceof URLSearchParams) return body.get(key) || '';
if (body instanceof FormData) return body.get(key) || '';
} catch(e) {}
return '';
}
function reportPayload(body) {
try {
const browserFp = getParam(body, 'browser_fp');
const adFp = getParam(body, 'adFp');
const debugInfo = getParam(body, 'debug_info');
if (browserFp || adFp || debugInfo) {
window.WdttCaptcha.onCheckPayload(
browserFp ? browserFp.length : 0,
adFp ? adFp.length : 0,
debugInfo ? debugInfo.length : 0
);
}
} catch(e) {}
}
const origFetch = window.fetch;
window.fetch = async function() {
const args = arguments;
const url = args[0] || '';
if (typeof url === 'string' && url.includes('captchaNotRobot.check')) {
reportPayload(args[1] && args[1].body);
const response = await origFetch.apply(this, args);
const clone = response.clone();
try {
const data = await clone.json();
if (data.response && data.response.success_token) {
window.WdttCaptcha.onSuccess(data.response.success_token);
} else if (data.response && data.response.status) {
window.WdttCaptcha.onCheckStatus(
data.response.status || '',
data.response.show_captcha_type || ''
);
} else if (data.error) {
window.WdttCaptcha.onError(JSON.stringify(data.error));
}
@@ -191,11 +223,17 @@ class ManlCaptchaActivity : ComponentActivity() {
XMLHttpRequest.prototype.send = function() {
const xhr = this;
if (xhr._wdtt_url && xhr._wdtt_url.includes('captchaNotRobot.check')) {
reportPayload(arguments[0]);
xhr.addEventListener('load', function() {
try {
const data = JSON.parse(xhr.responseText);
if (data.response && data.response.success_token) {
window.WdttCaptcha.onSuccess(data.response.success_token);
} else if (data.response && data.response.status) {
window.WdttCaptcha.onCheckStatus(
data.response.status || '',
data.response.show_captcha_type || ''
);
} else if (data.error) {
window.WdttCaptcha.onError(JSON.stringify(data.error));
}
@@ -207,65 +245,15 @@ class ManlCaptchaActivity : ComponentActivity() {
})();
""".trimIndent()
private val hideElementsJSCode = """
private val closeBridgeJSCode = """
(function() {
// Перехватываем клик по нативному крестику ВК, чтобы закрывать Android Activity и останавливать туннель
if (window.__wdtt_close_bridge_installed) return;
window.__wdtt_close_bridge_installed = true;
document.addEventListener('click', function(e) {
if (e.target.closest('.vkc__ModalCardBase-module__dismiss')) {
window.WdttCaptcha.onCancelAndStop();
window.WdttCaptcha.onCancel();
}
});
const style = document.createElement('style');
style.innerHTML = `
/* Скрываем серый фон, лого, id, ссылку и кнопку АУДИО (крестик ВК оставляем!) */
.vkc__VisuallyHiddenModalOverlay-module__host,
.vkc__ModalOverlay-module__host,
.vkc__KaleidoscopeScreen-module__logoBlock,
.vkc__KaleidoscopeScreen-module__captchaId,
.vkc__SliderCaptcha-module__descriptionLink,
.vkc__SliderCaptcha-module__changeTypeButton {
display: none !important;
}
/* Основной фон вокруг окна - прозрачный прозрачным, убираем тени */
body, html, .vkc__ModalCard-module__host, .vkc__AppRoot-module__host, .vkui__root {
background: transparent !important;
box-shadow: none !important;
}
/* Сама карточка (окно) - фон чёрный */
.vkc__ModalCardBase-module__container {
background: #000000 !important;
box-shadow: none !important;
}
/* Стилизуем крестик ВК: левее, меньше, красный */
.vkc__ModalCardBase-module__dismiss {
color: #ef4444 !important;
transform: scale(0.8) translateX(-12px) !important;
}
.vkc__ModalCardBase-module__dismiss svg {
fill: #ef4444 !important;
}
/* Текст "Обновить" и описание капчи делаем белыми */
.vkc__RefreshButton-module__text,
.vkc__SliderCaptcha-module__description {
color: #ffffff !important;
}
/* Поле (трек), где нужно потянуть вправо - делаем белым */
.vkc__SwipeButton-module__track {
background-color: #ffffff !important;
}
/* Текст "Потяните вправо" внутри трека - делаем синим */
.vkc__SwipeButton-module__track span {
color: #0000FF !important;
}
`;
document.head.appendChild(style);
})();
""".trimIndent()
@@ -300,6 +288,21 @@ class ManlCaptchaActivity : ComponentActivity() {
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
isNestedScrollingEnabled = false
setOnTouchListener { v, event ->
when (event.actionMasked) {
MotionEvent.ACTION_DOWN,
MotionEvent.ACTION_MOVE,
MotionEvent.ACTION_POINTER_DOWN -> {
v.parent?.requestDisallowInterceptTouchEvent(true)
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_CANCEL -> {
v.parent?.requestDisallowInterceptTouchEvent(false)
}
}
false
}
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
@@ -309,7 +312,7 @@ class ManlCaptchaActivity : ComponentActivity() {
useWideViewPort = true
blockNetworkLoads = false
cacheMode = WebSettings.LOAD_DEFAULT // Включаем кэш для моментальной загрузки!
userAgentString = "Mozilla/5.0 (Linux; Android 13; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
userAgentString = WebSettings.getDefaultUserAgent(ctx)
}
addJavascriptInterface(object {
@@ -326,10 +329,17 @@ class ManlCaptchaActivity : ComponentActivity() {
finish()
}
@JavascriptInterface
fun onCancelAndStop() {
Log.d("ManlCaptchaWV", "User clicked VK Close. Stopping tunnel.")
TunnelManager.stop()
ManlCaptchaWebViewManager.notifyResult(Result.failure(Exception("Cancelled and stopped by user")))
fun onCheckStatus(status: String, showType: String) {
Log.i("ManlCaptchaWV", "captcha check status=$status show_type=$showType")
}
@JavascriptInterface
fun onCheckPayload(browserFpLen: Int, adFpLen: Int, debugInfoLen: Int) {
Log.i("ManlCaptchaWV", "check payload browser_fp_len=$browserFpLen adFp_len=$adFpLen debug_len=$debugInfoLen")
}
@JavascriptInterface
fun onCancel() {
Log.d("ManlCaptchaWV", "User closed VK captcha")
ManlCaptchaWebViewManager.notifyResult(Result.failure(Exception("Cancelled by user")))
finish()
}
}, "WdttCaptcha")
@@ -342,7 +352,7 @@ class ManlCaptchaActivity : ComponentActivity() {
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
view?.evaluateJavascript(interceptorJSCode, null)
view?.evaluateJavascript(hideElementsJSCode, null)
view?.evaluateJavascript(closeBridgeJSCode, null)
isLoading = false
}
}
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.app.PendingIntent
import android.content.Intent
@@ -55,7 +55,7 @@ class QuickToggleTileService : TileService() {
// Проверяем наличие выданного разрешения VPN перед стартом
if (VpnService.prepare(this) != null) {
Toast.makeText(this, "Откройте WDTT и выдайте VPN-разрешение", Toast.LENGTH_LONG).show()
Toast.makeText(this, "Откройте WDTT Plus и выдайте VPN-разрешение", Toast.LENGTH_LONG).show()
openMainActivity()
return
}
@@ -65,7 +65,7 @@ class QuickToggleTileService : TileService() {
try {
val intent = buildStartIntent()
if (intent == null) {
Toast.makeText(this@QuickToggleTileService, "Заполните настройки подключения в WDTT", Toast.LENGTH_LONG).show()
Toast.makeText(this@QuickToggleTileService, "Заполните настройки подключения в WDTT Plus", Toast.LENGTH_LONG).show()
openMainActivity()
return@launch
}
@@ -113,7 +113,7 @@ class QuickToggleTileService : TileService() {
putExtra("sni", store.sni.first())
putExtra("connection_password", store.connectionPassword.first())
putExtra("protocol", store.protocol.first())
putExtra("vk_auth_mode", store.vkAuthMode.first())
putExtra("vkcalls_preflight", store.vkCallsPreflight.first())
putExtra("captcha_mode", store.captchaMode.first())
putExtra("captcha_solve_method", store.captchaSolveMethod.first())
putExtra("fingerprint", store.selectedFingerprint.first())
@@ -125,8 +125,8 @@ class QuickToggleTileService : TileService() {
private fun updateTile(running: Boolean) {
runCatching {
qsTile?.apply {
label = "WDTT"
icon = Icon.createWithResource(this@QuickToggleTileService, R.drawable.ic_tile_logo_w)
label = "WDTT Plus"
icon = Icon.createWithResource(this@QuickToggleTileService, R.drawable.ic_tile_logo)
state = if (running) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
if (Build.VERSION.SDK_INT >= 29) {
subtitle = if (running) "Подключено" else "Отключено"
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.content.Context
import android.security.keystore.KeyGenParameterSpec
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.content.Context
import androidx.datastore.preferences.core.MutablePreferences
@@ -13,11 +13,194 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import android.os.Build
data class VkHashInsertResult(
val slot: Int,
val hash: String,
val previousHash: String
)
data class WdttLinkParts(
val host: String,
val dtlsPort: Int,
val wgPort: Int,
val localPort: Int,
val password: String,
val hashes: String
)
data class WdttDeepLinkValidation(
val parts: WdttLinkParts?,
val errors: List<String>,
val warnings: List<String> = emptyList()
) {
val canStartVpn: Boolean = parts != null && errors.isEmpty()
fun userMessage(): String {
return if (canStartVpn) {
buildString {
append("Ссылка wdtt:// корректна. VPN сможет использовать эти данные для подключения.")
if (warnings.isNotEmpty()) {
append("\n\nПредупреждения:\n")
append(warnings.joinToString("\n") { "• $it" })
}
}
} else {
buildString {
append("VPN не запустится по этой ссылке, потому что в ней есть ошибки:\n")
append(errors.joinToString("\n") { "• $it" })
append("\n\nПравильный вид: wdtt://адрес:DTLS-порт:WG-порт:локальный-порт:пароль:VK-хеши")
}
}
}
}
data class WdttDeepLinkApplyPlan(
val link: String,
val targetProfile: Int,
val requiresConfirmation: Boolean,
val storeAsLink: Boolean
)
data class WdttDeepLinkApplyResult(
val targetProfile: Int,
val overwritten: Boolean,
val storedAsLink: Boolean
)
object WdttDeepLink {
private val expectedFormat = "wdtt://адрес:DTLS-порт:WG-порт:локальный-порт:пароль:VK-хеши"
fun parse(value: String): WdttLinkParts? {
return validate(value).parts
}
fun validate(value: String): WdttDeepLinkValidation {
val clean = value.trim()
val errors = mutableListOf<String>()
val warnings = mutableListOf<String>()
if (clean.isBlank()) {
return WdttDeepLinkValidation(
parts = null,
errors = listOf("Ссылка пустая. Нужен вид: $expectedFormat.")
)
}
if (!clean.startsWith("wdtt://", ignoreCase = true)) {
return WdttDeepLinkValidation(
parts = null,
errors = listOf("Ссылка должна начинаться с wdtt://.")
)
}
val parts = clean.substringAfter("://").split(":")
if (parts.size != 6) {
val found = parts.size
val detail = when {
found < 6 -> "не хватает ${6 - found} ${fieldWord(6 - found)}"
else -> "лишние поля после VK-хешей"
}
return WdttDeepLinkValidation(
parts = null,
errors = listOf("В ссылке должно быть 6 полей после wdtt://, сейчас $found: $detail.")
)
}
val host = 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 password = parts[4].trim()
if (password.isBlank()) {
errors += "Не указан пароль туннеля."
}
val rawHashes = parts[5].split(",")
val hashes = rawHashes
.map { VkJoinLink.extractHash(it) }
.filter { it.isNotBlank() && it.length >= 16 }
.distinct()
.joinToString(",")
if (hashes.isBlank()) {
errors += "Нет рабочего VK-хеша. Нужен хотя бы один хеш длиной от 16 символов или ссылка VK-звонка."
} else {
val invalidHashes = rawHashes
.map { it.trim() }
.filter { it.isNotBlank() }
.count { VkJoinLink.extractHash(it).length < 16 }
if (invalidHashes > 0) {
warnings += "$invalidHashes ${hashWord(invalidHashes)} короче 16 символов и будет пропущено."
}
}
val linkParts = if (errors.isEmpty() && dtlsPort != null && wgPort != null && localPort != null) {
WdttLinkParts(host, dtlsPort, wgPort, localPort, password, hashes)
} else null
return WdttDeepLinkValidation(linkParts, errors, warnings)
}
private fun validatePort(raw: String, label: String, errors: MutableList<String>): Int? {
val value = raw.trim()
if (value.isBlank()) {
errors += "$label не указан."
return null
}
val port = value.toIntOrNull()
if (port == null) {
errors += "$label должен быть числом от 1 до 65535."
return null
}
if (port !in 1..65535) {
errors += "$label вне диапазона 1-65535."
return null
}
return port
}
private fun isValidTunnelHost(host: String): Boolean {
if (host.isBlank() || host.contains("/") || host.contains(":")) return false
val ipv4 = Regex("""^(\d{1,3}\.){3}\d{1,3}$""")
if (ipv4.matches(host)) return host.split(".").all { it.toIntOrNull()?.let { n -> n in 0..255 } == true }
return host.length <= 253 &&
host.contains(".") &&
host.split(".").all { label ->
label.length in 1..63 &&
!label.startsWith("-") &&
!label.endsWith("-") &&
label.all { it.isLetterOrDigit() || it == '-' }
}
}
private fun fieldWord(count: Int): String {
return when {
count % 10 == 1 && count % 100 != 11 -> "поля"
count % 10 in 2..4 && count % 100 !in 12..14 -> "полей"
else -> "полей"
}
}
private fun hashWord(count: Int): String {
return when {
count % 10 == 1 && count % 100 != 11 -> "хеш"
count % 10 in 2..4 && count % 100 !in 12..14 -> "хеша"
else -> "хешей"
}
}
}
class SettingsStore(context: Context) {
private val appContext = context.applicationContext
companion object {
@@ -31,6 +214,7 @@ class SettingsStore(context: Context) {
private val PEER = stringPreferencesKey("peer")
private val VK_HASHES = stringPreferencesKey("vk_hashes")
private val SECONDARY_VK_HASH = stringPreferencesKey("secondary_vk_hash")
private val VK_HASH_NEXT_SLOT = intPreferencesKey("vk_hash_next_slot")
private val WORKERS_PER_HASH = intPreferencesKey("workers_per_hash")
private val PROTOCOL = stringPreferencesKey("protocol")
private val LISTEN_PORT = intPreferencesKey("listen_port")
@@ -70,13 +254,15 @@ class SettingsStore(context: Context) {
private val PROXY_PORT = intPreferencesKey("proxy_port")
// ═══ Captcha Solve Mode ═══
private val VK_AUTH_MODE = stringPreferencesKey("vk_auth_mode") // "vkcalls" or "legacy"
private val VKCALLS_PREFLIGHT = booleanPreferencesKey("vkcalls_preflight")
private val CAPTCHA_MODE = stringPreferencesKey("captcha_mode") // "auto", "wv", or "rjs"
private val CAPTCHA_SOLVE_METHOD = stringPreferencesKey("captcha_solve_method") // "manual" or "auto"
private val CAPTCHA_WBV_SOLVE_METHOD = stringPreferencesKey("captcha_wbv_solve_method") // "manual" or "auto"
// ═══ VPN Exclusions Mode ═══
// ═══ VPN App Routing ═══
private val IS_WHITELIST = booleanPreferencesKey("is_whitelist")
private val BLACKLIST_APPS = stringPreferencesKey("blacklist_apps")
private val WHITELIST_APPS = stringPreferencesKey("whitelist_apps")
// ═══ Theme Mode ═══
private val THEME_MODE = stringPreferencesKey("theme_mode") // "system", "light", "dark"
@@ -100,15 +286,18 @@ class SettingsStore(context: Context) {
private val UPDATE_DIALOG_LAST_ACTION_AT = longPreferencesKey("update_dialog_last_action_at")
private val CLIENT_ID_CHECK_RESULTS = stringPreferencesKey("client_id_check_results")
private val INTERFACE_ROLE = stringPreferencesKey("interface_role")
private val PERMISSION_ONBOARDING_COMPLETE = booleanPreferencesKey("permission_onboarding_complete")
private const val VPN_PROFILE_COUNT = 3
private fun <T> getProfileKey(baseKey: Preferences.Key<T>, profile: Int): Preferences.Key<T> {
if (profile == 0) return baseKey
val newName = "${baseKey.name}_$profile"
@Suppress("UNCHECKED_CAST")
return when (baseKey) {
PEER, VK_HASHES, SECONDARY_VK_HASH, PROTOCOL, SNI, USER_AGENT, DEPLOY_IP, DEPLOY_LOGIN, DEPLOY_PASSWORD, DEPLOY_PASSWORD_ENCRYPTED, DEPLOY_SSH_PORT, DEPLOY_DNS1, DEPLOY_DNS2, EXCLUDED_APPS, 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, VK_AUTH_MODE, 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, 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 -> booleanPreferencesKey(newName) as Preferences.Key<T>
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>
else -> throw IllegalArgumentException("Unsupported key type: ${baseKey.name}")
}
}
@@ -120,11 +309,12 @@ class SettingsStore(context: Context) {
init {
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
migrateSecretsToKeystore()
migrateVpnAppLists()
}
}
val activeProfile: Flow<Int> = dataStore.data.map { it[ACTIVE_PROFILE] ?: 0 }
val showSystemApps: Flow<Boolean> = dataStore.data.map { it[SHOW_SYSTEM_APPS] ?: true }
val showSystemApps: Flow<Boolean> = dataStore.data.map { it[SHOW_SYSTEM_APPS] ?: false }
val loggingEnabled: Flow<Boolean> = dataStore.data.map { it[LOGGING_ENABLED] ?: true }
val wdttLink: Flow<String> = dataStore.data.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
@@ -208,9 +398,14 @@ class SettingsStore(context: Context) {
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(DEPLOY_DNS2, profile)] ?: "1.0.0.1"
}
val excludedApps: Flow<String> = dataStore.data.map { prefs ->
val vpnAppPackages: Flow<String> = dataStore.data.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(EXCLUDED_APPS, profile)] ?: ""
val baseKey = if (prefs[getProfileKey(IS_WHITELIST, profile)] == true) {
WHITELIST_APPS
} else {
BLACKLIST_APPS
}
prefs[getProfileKey(baseKey, profile)] ?: ""
}
val detailedLogs: Flow<Boolean> = dataStore.data.map { it[DETAILED_LOGS] ?: false }
@@ -248,9 +443,9 @@ class SettingsStore(context: Context) {
}
// ═══ Captcha Solve Mode ═══
val vkAuthMode: Flow<String> = dataStore.data.map { prefs ->
val vkCallsPreflight: Flow<Boolean> = dataStore.data.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(VK_AUTH_MODE, profile)] ?: "vkcalls"
prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true
}
val captchaMode: Flow<String> = dataStore.data.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
@@ -279,7 +474,7 @@ class SettingsStore(context: Context) {
// ═══ Fingerprint & Client IDs ═══
val selectedFingerprint: Flow<String> = dataStore.data.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "chrome"
prefs[getProfileKey(SELECTED_FINGERPRINT, profile)] ?: "firefox"
}
val activeClientIds: Flow<String> = dataStore.data.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
@@ -300,6 +495,28 @@ 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 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()
}
suspend fun saveInterfaceRole(role: String) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
val hadRole = !prefs[INTERFACE_ROLE].isNullOrBlank()
prefs[INTERFACE_ROLE] = role
prefs[getProfileKey(WDTT_LINK_MODE, profile)] = role == "user"
if (!hadRole && !prefs.contains(PERMISSION_ONBOARDING_COMPLETE)) {
prefs[PERMISSION_ONBOARDING_COMPLETE] = false
}
}
}
suspend fun savePermissionOnboardingComplete(complete: Boolean) {
dataStore.edit { prefs ->
prefs[PERMISSION_ONBOARDING_COMPLETE] = complete
}
}
suspend fun saveThemeMode(mode: String) {
dataStore.edit { prefs ->
@@ -400,6 +617,51 @@ class SettingsStore(context: Context) {
}
}
suspend fun createWdttDeepLinkApplyPlan(link: String): WdttDeepLinkApplyPlan? {
WdttDeepLink.parse(link) ?: return null
val cleanLink = link.trim()
return dataStore.data.map { prefs ->
val activeProfile = (prefs[ACTIVE_PROFILE] ?: 0).coerceIn(0, VPN_PROFILE_COUNT - 1)
val freeProfile = (0 until VPN_PROFILE_COUNT).firstOrNull { profile ->
prefs.isTunnelProfileEmpty(profile)
}
WdttDeepLinkApplyPlan(
link = cleanLink,
targetProfile = freeProfile ?: activeProfile,
requiresConfirmation = freeProfile == null,
storeAsLink = prefs[getProfileKey(WDTT_LINK_MODE, activeProfile)] == true
)
}.first()
}
suspend fun applyWdttDeepLink(plan: WdttDeepLinkApplyPlan): WdttDeepLinkApplyResult? {
val parts = WdttDeepLink.parse(plan.link) ?: return null
val profile = plan.targetProfile.coerceIn(0, VPN_PROFILE_COUNT - 1)
dataStore.edit { prefs ->
prefs[ACTIVE_PROFILE] = profile
prefs[getProfileKey(WDTT_LINK_MODE, profile)] = plan.storeAsLink
if (plan.storeAsLink) {
prefs[getProfileKey(WDTT_LINK, profile)] = plan.link
prefs.clearManualTunnelFields(profile)
} else {
prefs.remove(getProfileKey(WDTT_LINK, profile))
prefs[getProfileKey(PEER, profile)] = parts.host
prefs[getProfileKey(SERVER_DTLS_PORT, profile)] = parts.dtlsPort
prefs[getProfileKey(SERVER_WG_PORT, profile)] = parts.wgPort
prefs[getProfileKey(LISTEN_PORT, profile)] = parts.localPort
prefs.putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, parts.password, profile)
prefs[getProfileKey(VK_HASHES, profile)] = parts.hashes
prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = ""
prefs[getProfileKey(MANUAL_PORTS_ENABLED, profile)] = true
}
}
return WdttDeepLinkApplyResult(
targetProfile = profile,
overwritten = plan.requiresConfirmation,
storedAsLink = plan.storeAsLink
)
}
suspend fun saveWdttLinkMode(enabled: Boolean) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
@@ -430,6 +692,48 @@ class SettingsStore(context: Context) {
}
}
suspend fun insertVkHashFromShare(hash: String): VkHashInsertResult {
val cleanedHash = VkJoinLink.extractHash(hash)
require(cleanedHash.length >= 16) { "VK-хеш слишком короткий" }
var result = VkHashInsertResult(slot = 1, hash = cleanedHash, previousHash = "")
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
val hashesKey = getProfileKey(VK_HASHES, profile)
val nextSlotKey = getProfileKey(VK_HASH_NEXT_SLOT, profile)
val slots = parseVkHashSlots(prefs[hashesKey] ?: "")
val duplicateSlot = slots.indexOfFirst { it == cleanedHash }
require(duplicateSlot < 0) {
"Такой VK-хеш уже добавлен в поле VK Хеш ${duplicateSlot + 1}. Добавьте другой хеш."
}
val savedNext = (prefs[nextSlotKey] ?: 0).coerceIn(0, 3)
val slotIndex = slots.indexOfFirst { it.isBlank() }.takeIf { it >= 0 } ?: savedNext
val previous = slots[slotIndex]
slots[slotIndex] = cleanedHash
prefs[hashesKey] = slots.joinToString(",")
prefs[nextSlotKey] = (slotIndex + 1) % 4
result = VkHashInsertResult(slot = slotIndex + 1, hash = cleanedHash, previousHash = previous)
}
return result
}
private fun parseVkHashSlots(raw: String): MutableList<String> {
val tokens = if (raw.contains(",")) {
raw.split(",")
} else {
raw.split(Regex("[\\s\\n]+"))
}
val slots = tokens
.map { VkJoinLink.extractHash(it) }
.take(4)
.toMutableList()
while (slots.size < 4) {
slots.add("")
}
return slots
}
suspend fun saveManualPortsEnabled(enabled: Boolean) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
@@ -465,12 +769,39 @@ class SettingsStore(context: Context) {
}
}
suspend fun saveExcludedApps(packages: String) {
suspend fun toggleVpnAppSelected(packageName: String, whitelist: Boolean) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(EXCLUDED_APPS, profile)] = packages
val key = getProfileKey(if (whitelist) WHITELIST_APPS else BLACKLIST_APPS, profile)
val packages = prefs[key]
.orEmpty()
.split(",")
.map { it.trim() }
.filter { it.isNotEmpty() }
.toMutableSet()
if (!packages.add(packageName)) packages.remove(packageName)
prefs[key] = packages.sorted().joinToString(",")
}
}
suspend fun addBlacklistPackages(newPackages: Set<String>): Int {
var addedCount = 0
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
val key = getProfileKey(BLACKLIST_APPS, profile)
val packages = prefs[key]
.orEmpty()
.split(",")
.map { it.trim() }
.filter { it.isNotEmpty() }
.toMutableSet()
val before = packages.size
packages.addAll(newPackages)
addedCount = packages.size - before
prefs[key] = packages.sorted().joinToString(",")
}
return addedCount
}
suspend fun saveDetailedLogs(enabled: Boolean) {
dataStore.edit { prefs ->
@@ -509,10 +840,10 @@ class SettingsStore(context: Context) {
}
// ═══ Сохранение режима обхода капчи ═══
suspend fun saveVkAuthMode(mode: String) {
suspend fun saveVkCallsPreflight(enabled: Boolean) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(VK_AUTH_MODE, profile)] = if (mode == "legacy") "legacy" else "vkcalls"
prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] = enabled
}
}
@@ -548,15 +879,6 @@ class SettingsStore(context: Context) {
}
}
// Атомарное сохранение обоих параметров для исключения гонки при перезагрузке
suspend fun saveExceptionsMode(packages: String, isWhitelist: Boolean) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(EXCLUDED_APPS, profile)] = packages
prefs[getProfileKey(IS_WHITELIST, profile)] = isWhitelist
}
}
private suspend fun migrateSecretsToKeystore() {
dataStore.edit { prefs ->
for (profile in 0..2) {
@@ -569,6 +891,27 @@ class SettingsStore(context: Context) {
}
}
private suspend fun migrateVpnAppLists() {
dataStore.edit { prefs ->
for (profile in 0 until VPN_PROFILE_COUNT) {
val legacyKey = getProfileKey(EXCLUDED_APPS, profile)
val legacyPackages = prefs[legacyKey].orEmpty()
if (legacyPackages.isBlank()) continue
val targetBaseKey = if (prefs[getProfileKey(IS_WHITELIST, profile)] == true) {
WHITELIST_APPS
} else {
BLACKLIST_APPS
}
val targetKey = getProfileKey(targetBaseKey, profile)
if (prefs[targetKey] == null) {
prefs[targetKey] = legacyPackages
}
prefs.remove(legacyKey)
}
}
}
private fun readSecret(
prefs: Preferences,
encryptedKey: Preferences.Key<String>,
@@ -597,6 +940,22 @@ 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
}
private fun MutablePreferences.clearManualTunnelFields(profile: Int) {
remove(getProfileKey(PEER, profile))
remove(getProfileKey(VK_HASHES, profile))
remove(getProfileKey(SECONDARY_VK_HASH, profile))
putSecret(CONNECTION_PASSWORD_ENCRYPTED, CONNECTION_PASSWORD, "", profile)
remove(getProfileKey(MANUAL_PORTS_ENABLED, profile))
}
private fun MutablePreferences.migrateSecret(
encryptedKey: Preferences.Key<String>,
legacyKey: Preferences.Key<String>
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.os.Build
import android.app.Activity
File diff suppressed because it is too large. Load diff
+720
View File
@@ -0,0 +1,720 @@
package com.wdtt.plus
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ServiceInfo
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiManager
import android.os.Build
import android.os.IBinder
import android.os.PowerManager
import android.util.Log
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4"
private const val TUNNEL_ALERT_CHANNEL_ID = "wdtt_tunnel_alert_v1"
private const val TUNNEL_NOTIFICATION_ID = 1
private const val TUNNEL_ALERT_NOTIFICATION_ID = 2
private const val NETWORK_CHANGE_SETTLE_MS = 90_000L
private const val NETWORK_RETURN_SETTLE_MS = 45_000L
private const val NETWORK_LOSS_GRACE_MS = 2 * 60_000L
private const val STABLE_NETWORK_RECONNECT_DELAY_MS = 15_000L
private const val STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS = 2 * 60_000L
private const val WAKE_RESCUE_GRACE_MS = 60_000L
private const val WAKE_RESCUE_FAIL_OPEN_MS = 2 * 60_000L
private const val INITIAL_VPN_START_GRACE_MS = 90_000L
class TunnelService : Service() {
private var wakeLock: PowerManager.WakeLock? = null
private var wifiLock: WifiManager.WifiLock? = null
private var updateJob: Job? = null
private var networkChangeJob: Job? = null
private var lastNotificationText: String? = null
// Network Monitoring
private var connectivityManager: ConnectivityManager? = null
private var networkCallback: ConnectivityManager.NetworkCallback? = null
private var lastNetworkChangeTime = 0L
private val activeNetworks = mutableSetOf<Network>()
private var isTunnelPaused = false
private var lastValidatedNetwork: Network? = null
private var lastStableNetworkReconnectAt = 0L
private var stableNetworkWasLost = false
private var screenStateReceiver: BroadcastReceiver? = null
private var wakeRescueJob: Job? = null
override fun onCreate() {
super.onCreate()
createNotificationChannel()
// Сразу берем лок при создании
acquireWakeLock()
setupNetworkCallback()
registerScreenStateReceiver()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (intent == null) {
restoreTunnel()
return START_STICKY
}
when (intent.action) {
"START" -> {
val notification = createNotification("Запуск...")
startPersistentForeground(notification)
val params = TunnelParams(
peer = intent.getStringExtra("peer") ?: "",
vkHashes = intent.getStringExtra("vk_hashes") ?: "",
secondaryVkHash = intent.getStringExtra("secondary_vk_hash") ?: "",
workersPerHash = intent.getIntExtra("workers_per_hash", 16),
port = intent.getIntExtra("port", 9000),
sni = intent.getStringExtra("sni") ?: "",
connectionPassword = intent.getStringExtra("connection_password") ?: "",
protocol = intent.getStringExtra("protocol") ?: "udp",
vkCallsPreflight = intent.getBooleanExtra("vkcalls_preflight", true),
captchaMode = sanitizeCaptchaMode(intent.getStringExtra("captcha_mode")),
captchaSolveMethod = intent.getStringExtra("captcha_solve_method") ?: "auto",
fingerprint = intent.getStringExtra("fingerprint") ?: "firefox",
clientIds = intent.getStringExtra("client_ids") ?: "6287487,8202606"
)
startTunnel(params)
}
"STOP" -> stopTunnel()
"DEPLOY_START" -> {
val notification = createNotification("Установка на сервер...", "DEPLOY_CANCEL", "Отменить")
startPersistentForeground(notification)
acquireWakeLock()
}
"DEPLOY_CANCEL" -> {
com.wdtt.plus.DeployManager.writeError("[!] ❌ Установка отменена пользователем")
com.wdtt.plus.DeployManager.stopDeploy("error: Отменена пользователем")
stopForeground(STOP_FOREGROUND_REMOVE)
}
"DEPLOY_STOP" -> {
if (!TunnelManager.running.value) {
stopTunnel()
} else {
updateNotification("Туннель активен")
}
}
}
return START_STICKY
}
private fun restoreTunnel() {
val notification = createNotification("Восстановление соединения...")
startPersistentForeground(notification)
val appContext = applicationContext
TunnelManager.scope.launch {
try {
val store = SettingsStore(appContext)
val basePeer = store.peer.first()
val manualPortsEnabled = store.manualPortsEnabled.first()
val serverDtlsPort = if (manualPortsEnabled) store.serverDtlsPort.first() else 56000
val peerWithPort = if (basePeer.isBlank() || basePeer.contains(":")) basePeer else "$basePeer:$serverDtlsPort"
val params = TunnelParams(
peer = peerWithPort,
vkHashes = store.vkHashes.first(),
secondaryVkHash = store.secondaryVkHash.first(),
workersPerHash = store.workersPerHash.first(),
port = store.listenPort.first(),
sni = store.sni.first(),
connectionPassword = store.connectionPassword.first(),
vkCallsPreflight = store.vkCallsPreflight.first(),
captchaMode = sanitizeCaptchaMode(store.captchaMode.first()),
captchaSolveMethod = store.captchaSolveMethod.first(),
fingerprint = store.selectedFingerprint.first(),
clientIds = store.activeClientIds.first()
)
if (params.peer.isNotEmpty() && params.vkHashes.isNotEmpty()) {
launch(Dispatchers.Main) {
startTunnel(params)
}
} else {
launch(Dispatchers.Main) {
stopTunnel()
}
}
} catch (e: Exception) {
launch(Dispatchers.Main) {
stopTunnel()
}
}
}
}
private fun startTunnel(params: TunnelParams) {
updateNotification("Подключение...")
acquireWakeLock()
acquireWifiLock()
// Подготавливаем CaptchaWebViewManager (не создаёт WebView — просто сохраняет контекст)
// Вызываем всегда — дёшево, а WebView создаётся на лету при каждом запросе капчи
CaptchaWebViewManager.onTunnelStart(applicationContext)
TunnelManager.start(this, params)
startStatsUpdater()
}
private fun stopTunnel() {
updateJob?.cancel()
networkChangeJob?.cancel()
wakeRescueJob?.cancel()
networkChangeJob = null
wakeRescueJob = null
// Уничтожаем текущий WebView (если капча решается) и чистим контекст
CaptchaWebViewManager.onTunnelStop()
TunnelManager.stop()
releaseWakeLock()
releaseWifiLock()
lastValidatedNetwork = null
lastStableNetworkReconnectAt = 0L
stableNetworkWasLost = false
activeNetworks.clear()
stopForeground(STOP_FOREGROUND_REMOVE)
stopSelf()
}
private fun registerScreenStateReceiver() {
if (screenStateReceiver != null) return
screenStateReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
Intent.ACTION_SCREEN_ON -> scheduleWakeRescueCheck()
Intent.ACTION_SCREEN_OFF -> {
wakeRescueJob?.cancel()
wakeRescueJob = null
}
}
}
}
val filter = IntentFilter().apply {
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_SCREEN_OFF)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
registerReceiver(screenStateReceiver, filter, RECEIVER_NOT_EXPORTED)
} else {
@Suppress("DEPRECATION")
registerReceiver(screenStateReceiver, filter)
}
}
private fun scheduleWakeRescueCheck() {
if (!AMNEZIA_STYLE_RECOVERY || !TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return
val wakeAt = System.currentTimeMillis()
TunnelManager.noteWakeRescueStarted()
updateNotification("Проверка VPN после сна...")
wakeRescueJob?.cancel()
wakeRescueJob = TunnelManager.scope.launch(Dispatchers.Main) {
delay(WAKE_RESCUE_GRACE_MS)
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
if (TunnelManager.hasFreshTunnelActivitySince(wakeAt)) {
TunnelManager.noteWakeRescueHealthy()
updateNotification(buildTunnelNotificationText())
return@launch
}
TunnelManager.noteWakeRescueReconnect()
updateNotification("Восстановление VPN...")
val reconnectAt = System.currentTimeMillis()
TunnelManager.restartTransport(
reason = "[СОН] После пробуждения VPN не подал признаков жизни. Мягко переподключаю транспорт.",
minIntervalMs = 60_000L
)
delay(WAKE_RESCUE_FAIL_OPEN_MS)
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
if (TunnelManager.hasFreshTunnelActivitySince(reconnectAt)) {
TunnelManager.noteWakeRescueHealthy()
updateNotification(buildTunnelNotificationText())
return@launch
}
TunnelManager.markStoppedAfterWakeRescue()
showTunnelAlertNotification(
"WDTT Plus остановил VPN",
"После пробуждения VPN не восстановился, поэтому приложение выключило VPN и вернуло прямой интернет."
)
stopTunnel()
}
}
private fun setupNetworkCallback() {
connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
activeNetworks.clear()
networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
val wasEmpty = activeNetworks.isEmpty()
activeNetworks.add(network)
if (AMNEZIA_STYLE_RECOVERY) {
return
}
if (wasEmpty) {
if (isTunnelPaused) {
scheduleResumeAfterNetworkReturn()
} else {
scheduleNetworkSettleCheck("сеть появилась", NETWORK_RETURN_SETTLE_MS, minSpacingMs = 0L)
}
} else {
scheduleNetworkSettleCheck("добавлена ещё одна сеть", NETWORK_CHANGE_SETTLE_MS)
}
}
override fun onLost(network: Network) {
super.onLost(network)
activeNetworks.remove(network)
if (AMNEZIA_STYLE_RECOVERY) {
if (lastValidatedNetwork == network) {
lastValidatedNetwork = null
}
if (activeNetworks.isEmpty() && TunnelManager.running.value) {
stableNetworkWasLost = true
TunnelManager.noteUnderlyingNetworkChanged(
"сеть временно пропала",
graceMs = NETWORK_LOSS_GRACE_MS,
replaceGrace = true
)
updateNotification("Ожидание сети")
}
return
}
if (activeNetworks.isEmpty() && TunnelManager.running.value && !isTunnelPaused) {
scheduleNetworkLossPause()
} else if (activeNetworks.isNotEmpty()) {
scheduleNetworkSettleCheck("одна из сетей отключилась", NETWORK_CHANGE_SETTLE_MS)
}
}
override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities)
if (AMNEZIA_STYLE_RECOVERY) {
handleStableNetworkCapabilities(network, networkCapabilities)
return
}
if (
activeNetworks.contains(network) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
) {
scheduleNetworkSettleCheck("параметры сети изменились", NETWORK_CHANGE_SETTLE_MS, minSpacingMs = NETWORK_CHANGE_SETTLE_MS)
}
}
}
// ВАЖНО: Слушаем только реальные (не VPN) сети с доступом в интернет.
// Иначе интерфейс VPN (tun0) считается активной сетью, и при "Режиме полёта" activeNetworks не падает до 0.
val request = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
.build()
connectivityManager?.registerNetworkCallback(request, networkCallback!!)
}
private fun handleStableNetworkCapabilities(network: Network, networkCapabilities: NetworkCapabilities) {
val isUsableRealNetwork = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) &&
networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
if (!isUsableRealNetwork) return
activeNetworks.add(network)
val previous = lastValidatedNetwork
if (previous == null) {
lastValidatedNetwork = network
if (stableNetworkWasLost) {
stableNetworkWasLost = false
scheduleStableValidatedReconnect("Android подтвердил возвращение рабочей сети")
return
}
if (TunnelManager.running.value) {
TunnelManager.noteUnderlyingNetworkChanged(
"Android подтвердил рабочую сеть",
graceMs = STABLE_NETWORK_RECONNECT_DELAY_MS,
replaceGrace = false
)
}
return
}
if (previous != network) {
lastValidatedNetwork = network
scheduleStableValidatedReconnect("Android подтвердил смену рабочей сети")
}
}
private fun scheduleStableValidatedReconnect(reason: String) {
val now = System.currentTimeMillis()
lastNetworkChangeTime = now
if (!TunnelManager.running.value || isTunnelPaused) return
TunnelManager.noteUnderlyingNetworkChanged(
reason,
graceMs = STABLE_NETWORK_RECONNECT_DELAY_MS + 30_000L,
replaceGrace = true
)
networkChangeJob?.cancel()
networkChangeJob = TunnelManager.scope.launch(Dispatchers.Main) {
Log.d("TunnelService", "$reason, ждём короткую стабилизацию перед reconnect")
delay(STABLE_NETWORK_RECONNECT_DELAY_MS)
if (lastNetworkChangeTime != now) return@launch
if (!TunnelManager.running.value || !hasAnyRealNetwork() || TunnelManager.isCaptchaInProgress()) return@launch
val sinceLastReconnect = System.currentTimeMillis() - lastStableNetworkReconnectAt
if (sinceLastReconnect < STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS) {
Log.d("TunnelService", "Пропускаем reconnect: недавний reconnect уже был")
return@launch
}
lastStableNetworkReconnectAt = System.currentTimeMillis()
TunnelManager.restartTransport(
reason = "[СЕТЬ] Android подтвердил новую сеть. Мягко переподключаю транспорт.",
minIntervalMs = STABLE_NETWORK_RECONNECT_MIN_INTERVAL_MS
)
}
}
@Suppress("DEPRECATION")
private fun hasAnyRealNetwork(): Boolean {
val cm = connectivityManager ?: return activeNetworks.isNotEmpty()
if (activeNetworks.isNotEmpty()) return true
return cm.allNetworks.any { network ->
val caps = cm.getNetworkCapabilities(network) ?: return@any false
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)
}
}
private fun scheduleNetworkSettleCheck(
reason: String,
settleMs: Long,
minSpacingMs: Long = 30_000L
) {
val now = System.currentTimeMillis()
if (now - lastNetworkChangeTime < minSpacingMs) return
lastNetworkChangeTime = now
if (!TunnelManager.running.value || isTunnelPaused) return
TunnelManager.noteUnderlyingNetworkChanged(reason, graceMs = settleMs, replaceGrace = true)
networkChangeJob?.cancel()
networkChangeJob = TunnelManager.scope.launch(Dispatchers.Main) {
Log.d("TunnelService", "Сеть изменилась ($reason), ждём стабилизации без перезапуска")
delay(settleMs)
if (lastNetworkChangeTime != now) return@launch
if (!TunnelManager.running.value || isTunnelPaused || !hasAnyRealNetwork()) return@launch
if (TunnelManager.shouldSoftRestartAfterNetworkSettled(settleMs = settleMs, freshActiveMs = 60_000L)) {
TunnelManager.restartTransport(
reason = "[СЕТЬ] После ожидания сети нет свежей активности. Мягко перезапускаю только транспорт.",
minIntervalMs = 3 * 60_000L
)
}
}
}
private fun scheduleNetworkLossPause() {
val now = System.currentTimeMillis()
lastNetworkChangeTime = now
if (!TunnelManager.running.value || isTunnelPaused) return
TunnelManager.noteUnderlyingNetworkChanged(
"сеть временно пропала",
graceMs = NETWORK_LOSS_GRACE_MS + NETWORK_RETURN_SETTLE_MS,
replaceGrace = true
)
networkChangeJob?.cancel()
networkChangeJob = TunnelManager.scope.launch(Dispatchers.Main) {
Log.d("TunnelService", "Сеть потеряна, ждём: короткие провалы не трогаем")
delay(NETWORK_LOSS_GRACE_MS)
if (lastNetworkChangeTime != now) return@launch
if (!TunnelManager.running.value || isTunnelPaused || hasAnyRealNetwork()) return@launch
isTunnelPaused = true
Log.d("TunnelService", "Сети долго нет, приостанавливаем транспорт без переподключений к VK")
TunnelManager.pause()
updateNotification("Ожидание сети")
}
}
private fun scheduleResumeAfterNetworkReturn() {
val now = System.currentTimeMillis()
lastNetworkChangeTime = now
TunnelManager.noteUnderlyingNetworkChanged("сеть вернулась", graceMs = NETWORK_RETURN_SETTLE_MS, replaceGrace = true)
networkChangeJob?.cancel()
networkChangeJob = TunnelManager.scope.launch(Dispatchers.Main) {
Log.d("TunnelService", "Сеть появилась, ждём стабилизации перед возобновлением")
delay(NETWORK_RETURN_SETTLE_MS)
if (lastNetworkChangeTime != now) return@launch
if (!hasAnyRealNetwork() || !TunnelManager.running.value) return@launch
isTunnelPaused = false
TunnelManager.resume()
updateNotification(buildTunnelNotificationText())
}
}
private fun sanitizeCaptchaMode(mode: String?): String {
return when (mode?.lowercase()) {
"auto" -> "auto"
"rjs" -> "rjs"
"wv" -> "wv"
else -> "auto"
}
}
private fun acquireWakeLock() {
if (wakeLock?.isHeld == true) return
val pm = getSystemService(POWER_SERVICE) as PowerManager
wakeLock = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"wdtt:tunnel_cpu"
).apply {
setReferenceCounted(false)
acquire()
}
}
@Suppress("DEPRECATION")
private fun acquireWifiLock() {
if (wifiLock?.isHeld == true) return
val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
// Используем WIFI_MODE_FULL_LOW_LATENCY для Android 10+,
// это предотвращает отключение радиомодуля при выключенном экране
val mode = if (Build.VERSION.SDK_INT >= 29) {
WifiManager.WIFI_MODE_FULL_LOW_LATENCY
} else {
WifiManager.WIFI_MODE_FULL_HIGH_PERF
}
wifiLock = wm.createWifiLock(mode, "wdtt:wifi_perf").apply {
setReferenceCounted(false)
acquire()
}
}
private fun releaseWakeLock() {
if (wakeLock?.isHeld == true) {
wakeLock?.release()
}
wakeLock = null
}
private fun releaseWifiLock() {
if (wifiLock?.isHeld == true) {
wifiLock?.release()
}
wifiLock = null
}
private fun startStatsUpdater() {
updateJob?.cancel()
updateJob = TunnelManager.scope.launch(Dispatchers.Main) {
delay(1000)
while (isActive) {
if (!TunnelManager.running.value && !isTunnelPaused) {
// Туннель полностью остановлен (не на паузе) — убиваем сервис
stopSelf()
break
}
if (TunnelManager.running.value && !isTunnelPaused) {
val helper = WireGuardHelper(applicationContext)
val startupWindow = System.currentTimeMillis() - TunnelManager.processStartedAtMs < INITIAL_VPN_START_GRACE_MS
val captchaActive = TunnelManager.isCaptchaInProgress()
if (!startupWindow && !captchaActive && android.net.VpnService.prepare(applicationContext) != null) {
Log.w("TunnelService", "VPN-разрешение WDTT Plus отозвано или слот передан другому VPN. Выключаем WDTT Plus.")
stopTunnel()
break
}
if (!startupWindow && !captchaActive && !helper.isTunnelUp()) {
Log.w("TunnelService", "Обнаружена пропажа или замена VPN-интерфейса! Экстренное выключение туннеля.")
stopTunnel()
break
}
if (!startupWindow && !captchaActive) {
when (TunnelManager.pollNetworkRecoveryAction()) {
NetworkRecoveryAction.SoftRestart -> {
Log.w("TunnelService", "Сетевая ошибка туннеля. Мягко перезапускаем транспорт.")
TunnelManager.restartTransport(
reason = "[СЕТЬ] Сетевая ошибка туннеля. Мягкий перезапуск транспорта...",
minIntervalMs = 20_000L
)
}
NetworkRecoveryAction.RecreateVpn -> {
Log.w("TunnelService", "Мягкие попытки не помогли. Пересоздаём VPN-туннель.")
updateNotification("Пересоздание VPN...")
TunnelManager.recreateVpnTunnel()
}
NetworkRecoveryAction.StopVpn -> {
Log.w("TunnelService", "Автовосстановление не помогло. Останавливаем VPN, чтобы вернуть интернет.")
TunnelManager.markStoppedAfterFailedRecovery()
showTunnelAlertNotification(
"WDTT Plus остановил VPN",
"Связь не восстановилась автоматически, поэтому VPN выключен и интернет телефона возвращён напрямую."
)
stopTunnel()
break
}
null -> Unit
}
}
}
if (!isTunnelPaused) {
updateNotification(buildTunnelNotificationText())
}
delay(2000)
}
}
}
private fun buildTunnelNotificationText(): String {
val issueTitle = TunnelManager.connectionIssueTitleForNotification()
if (issueTitle != null) {
return issueTitle
}
val statsText = TunnelManager.stats.value.trim()
return when {
statsText.isEmpty() -> "Туннель активен"
statsText == "Ожидание данных..." -> "Туннель активен"
else -> statsText
}
}
private fun showTunnelAlertNotification(title: String, text: String) {
val openIntent = PendingIntent.getActivity(
this, 3,
Intent(this, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
},
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val notification = NotificationCompat.Builder(this, TUNNEL_ALERT_CHANNEL_ID)
.setContentTitle(title)
.setContentText(text)
.setStyle(NotificationCompat.BigTextStyle().bigText(text))
.setSmallIcon(R.drawable.ic_notification_icon)
.setContentIntent(openIntent)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setCategory(NotificationCompat.CATEGORY_STATUS)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setSilent(true)
.build()
getSystemService(NotificationManager::class.java).notify(TUNNEL_ALERT_NOTIFICATION_ID, notification)
}
private fun createNotificationChannel() {
val channel = NotificationChannel(
TUNNEL_NOTIFICATION_CHANNEL_ID,
"WDTT Plus Туннель",
NotificationManager.IMPORTANCE_LOW
).apply {
description = "Уведомление о работе туннеля"
setShowBadge(false)
// ВАЖНО: Разрешаем показывать на экране блокировки
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
setSound(null, null)
enableVibration(false)
}
getSystemService(NotificationManager::class.java).createNotificationChannel(channel)
val alertChannel = NotificationChannel(
TUNNEL_ALERT_CHANNEL_ID,
"WDTT Plus проблемы туннеля",
NotificationManager.IMPORTANCE_DEFAULT
).apply {
description = "Уведомления, когда VPN не смог восстановить соединение"
lockscreenVisibility = Notification.VISIBILITY_PUBLIC
setSound(null, null)
enableVibration(false)
}
getSystemService(NotificationManager::class.java).createNotificationChannel(alertChannel)
}
private fun createNotification(text: String, actionName: String = "STOP", actionTitle: String = "Отключить"): Notification {
val openIntent = PendingIntent.getActivity(
this, 0,
Intent(this, MainActivity::class.java).apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
},
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
val stopIntent = PendingIntent.getService(
this, if (actionName == "STOP") 1 else 2,
Intent(this, TunnelService::class.java).apply { action = actionName },
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
return NotificationCompat.Builder(this, TUNNEL_NOTIFICATION_CHANNEL_ID)
.setContentTitle("WDTT Plus")
.setContentText(text)
.setSmallIcon(R.drawable.ic_notification_icon)
.setOngoing(true)
.setLocalOnly(true)
.setContentIntent(openIntent)
.addAction(R.drawable.ic_stop, actionTitle, stopIntent)
.setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_DEFAULT)
// ВАЖНО: Делаем уведомление публичным (видимым на локскрине)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
// Категория SERVICE помогает системе понять важность
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setOnlyAlertOnce(true) // Не издавать звук и не будить экран при обновлении статистики!
.setSilent(true) // Делаем тихим само уведомление
.setShowWhen(false)
.setUsesChronometer(false)
.setWhen(0L)
.setPriority(NotificationCompat.PRIORITY_LOW)
.build()
}
private fun startPersistentForeground(notification: Notification) {
if (Build.VERSION.SDK_INT >= 34) {
startForeground(TUNNEL_NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE)
} else {
startForeground(TUNNEL_NOTIFICATION_ID, notification)
}
}
private fun updateNotification(text: String) {
if (lastNotificationText == text) return
lastNotificationText = text
val notification = createNotification(text)
getSystemService(NotificationManager::class.java).notify(TUNNEL_NOTIFICATION_ID, notification)
}
override fun onDestroy() {
super.onDestroy()
wakeRescueJob?.cancel()
networkChangeJob?.cancel()
screenStateReceiver?.let {
runCatching { unregisterReceiver(it) }
}
screenStateReceiver = null
networkCallback?.let {
connectivityManager?.unregisterNetworkCallback(it)
}
stopTunnel()
}
override fun onBind(intent: Intent?): IBinder? = null
}
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.os.Build
import kotlin.random.Random
@@ -0,0 +1,24 @@
package com.wdtt.plus
object VkJoinLink {
fun extractHash(input: String): String {
var s = input.trim().trim('<', '>', '"', '\'')
if (s.isBlank()) return ""
val lower = s.lowercase()
val marker = "/call/join/"
val markerIndex = lower.indexOf(marker)
s = when {
markerIndex >= 0 -> s.substring(markerIndex + marker.length)
lower.startsWith("http://") || lower.startsWith("https://") -> return ""
else -> s
}
val stopIndex = s.indexOfFirst { it == '?' || it == '#' || it == '/' || it.isWhitespace() }
if (stopIndex >= 0) {
s = s.substring(0, stopIndex)
}
return s.trim().trimEnd('/')
}
}
@@ -0,0 +1,40 @@
package com.wdtt.plus
internal val ALWAYS_BYPASSED_VPN_PACKAGES = setOf(
"com.vkontakte.android",
"com.vk.calls"
)
internal fun isAlwaysBypassedVpnPackage(packageName: String, ownPackageName: String): Boolean {
return packageName == ownPackageName || packageName in ALWAYS_BYPASSED_VPN_PACKAGES
}
internal data class VpnAppRouting(
val included: Set<String> = emptySet(),
val excluded: Set<String> = emptySet()
)
internal fun resolveVpnAppRouting(
isWhitelist: Boolean,
selectedPackages: Set<String>,
installedPackages: Set<String>,
ownPackageName: String
): VpnAppRouting {
val alwaysBypassed = (ALWAYS_BYPASSED_VPN_PACKAGES + ownPackageName)
.intersect(installedPackages)
val selectedInstalled = selectedPackages
.intersect(installedPackages)
.minus(alwaysBypassed)
if (!isWhitelist) {
return VpnAppRouting(excluded = alwaysBypassed + selectedInstalled)
}
// Пустой allowed-list в Android означает «ограничение не задано», то есть весь трафик.
// Поэтому для пустого БС явно исключаем все установленные пакеты.
return if (selectedInstalled.isEmpty()) {
VpnAppRouting(excluded = installedPackages)
} else {
VpnAppRouting(included = selectedInstalled)
}
}
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
@@ -21,7 +21,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
companion object {
const val ACTION_WIDGET_TOGGLE = "com.wdtt.client.ACTION_WIDGET_TOGGLE"
const val ACTION_WIDGET_TOGGLE = "com.wdtt.plus.ACTION_WIDGET_TOGGLE"
fun updateAllWidgets(context: Context) {
runCatching {
@@ -59,7 +59,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
}
if (VpnService.prepare(context) != null) {
Toast.makeText(context, "Откройте WDTT и выдайте VPN-разрешение", Toast.LENGTH_LONG).show()
Toast.makeText(context, "Откройте WDTT Plus и выдайте VPN-разрешение", Toast.LENGTH_LONG).show()
openMainActivity(context)
return
}
@@ -69,7 +69,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
try {
val startIntent = buildStartIntent(context)
if (startIntent == null) {
Toast.makeText(context, "Заполните настройки подключения в WDTT", Toast.LENGTH_LONG).show()
Toast.makeText(context, "Заполните настройки подключения в WDTT Plus", Toast.LENGTH_LONG).show()
openMainActivity(context)
return@launch
}
@@ -158,7 +158,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
putExtra("sni", store.sni.first())
putExtra("connection_password", store.connectionPassword.first())
putExtra("protocol", store.protocol.first())
putExtra("vk_auth_mode", store.vkAuthMode.first())
putExtra("vkcalls_preflight", store.vkCallsPreflight.first())
putExtra("captcha_mode", store.captchaMode.first())
putExtra("captcha_solve_method", store.captchaSolveMethod.first())
putExtra("fingerprint", store.selectedFingerprint.first())
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.app.Application
import android.content.Context
@@ -1,4 +1,4 @@
package com.wdtt.client
package com.wdtt.plus
import android.content.Context
import android.content.Intent
@@ -26,9 +26,23 @@ class WireGuardHelper(context: Context) {
var sharedTunnel: WgTunnel? = null
}
class WgTunnel : Tunnel {
override fun getName() = "wdtt"
override fun onStateChange(newState: Tunnel.State) {}
class WgTunnel(
private val onExternalDown: (() -> Unit)? = null
) : Tunnel {
@Volatile
var suppressDownCallback: Boolean = false
override fun getName() = "WDTT Plus"
override fun onStateChange(newState: Tunnel.State) {
if (newState != Tunnel.State.DOWN) return
val isCurrentTunnel = sharedTunnel === this
if (isCurrentTunnel) {
sharedTunnel = null
}
if (isCurrentTunnel && !suppressDownCallback) {
onExternalDown?.invoke()
}
}
}
suspend fun startTunnel(configString: String) = wgMutex.withLock {
@@ -45,6 +59,7 @@ class WireGuardHelper(context: Context) {
sharedTunnel?.let { existingTunnel ->
try {
existingTunnel.suppressDownCallback = true
backend.setState(existingTunnel, Tunnel.State.DOWN, null)
} catch (e: Exception) {
Log.w("WG", "Failed to stop previous tunnel before restart: ${e.readableMessage()}")
@@ -76,18 +91,26 @@ class WireGuardHelper(context: Context) {
// 1. Пакеты, которые всегда исключаются (наше приложение, ВК)
// 2. Получаю настройки пользователя
val settingsStore = SettingsStore(appContext)
val savedExcluded = settingsStore.excludedApps.first()
val userSelected = savedExcluded.split(",").filter { it.isNotEmpty() }.toSet()
// В обоих режимах (ЧС и БС) мы технически используем Blacklist (Checked = Excluded),
// так как пользователю удобнее логика "снимите галочку, чтобы приложение пошло в туннель".
// Разница только в описании и начальном состоянии списка (пустой/полный).
val excluded = mutableSetOf(appContext.packageName, "com.vkontakte.android", "com.vk.calls")
excluded.addAll(userSelected)
val installedExcluded = excluded.filter { it.isInstalledPackage() }.toSet()
if (installedExcluded.isNotEmpty()) {
builder.excludeApplications(installedExcluded)
val selectedPackages = settingsStore.vpnAppPackages.first()
.split(",")
.map { it.trim() }
.filter { it.isNotEmpty() }
.toSet()
val isWhitelist = settingsStore.isWhitelist.first()
val installedPackages = appContext.packageManager
.getInstalledApplications(0)
.map { it.packageName }
.toSet()
val routing = resolveVpnAppRouting(
isWhitelist = isWhitelist,
selectedPackages = selectedPackages,
installedPackages = installedPackages,
ownPackageName = appContext.packageName
)
if (routing.included.isNotEmpty()) {
builder.includeApplications(routing.included)
} else if (routing.excluded.isNotEmpty()) {
builder.excludeApplications(routing.excluded)
}
val newInterface = builder.build()
@@ -109,7 +132,9 @@ class WireGuardHelper(context: Context) {
.addPeer(peerBuilder.build())
.build()
val nextTunnel = WgTunnel()
val nextTunnel = WgTunnel {
TunnelManager.onWireGuardStoppedExternally()
}
setTunnelUpWithRetry(nextTunnel, finalConfig)
sharedTunnel = nextTunnel
Log.d("WG", "WireGuard tunnel started successfully")
@@ -126,6 +151,7 @@ class WireGuardHelper(context: Context) {
val currentTunnel = sharedTunnel ?: return@withContext
try {
val configFlow = TunnelManager.config.first() ?: return@withContext
currentTunnel.suppressDownCallback = true
backend.setState(currentTunnel, Tunnel.State.DOWN, null)
sharedTunnel = null
delay(150)
@@ -150,6 +176,7 @@ class WireGuardHelper(context: Context) {
withContext(Dispatchers.IO) {
try {
sharedTunnel?.let {
it.suppressDownCallback = true
backend.setState(it, Tunnel.State.DOWN, null)
sharedTunnel = null
Log.d("WG", "WireGuard tunnel stopped")
@@ -194,13 +221,6 @@ class WireGuardHelper(context: Context) {
return if (text.isNullOrBlank()) this::class.java.simpleName else "${this::class.java.simpleName}: $text"
}
private fun String.isInstalledPackage(): Boolean {
return runCatching {
appContext.packageManager.getPackageInfo(this, 0)
true
}.getOrDefault(false)
}
private fun String.describeWireGuardConfig(): String {
val lines = lineSequence().map { it.trim() }.filter { it.isNotEmpty() }.toList()
val hasInterface = lines.any { it.equals("[Interface]", ignoreCase = true) }
@@ -1,4 +1,4 @@
package com.wdtt.client.ui
package com.wdtt.plus.ui
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
@@ -1,4 +1,4 @@
package com.wdtt.client.ui
package com.wdtt.plus.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
@@ -27,8 +28,8 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.wdtt.client.AppReleaseInfo
import com.wdtt.client.RemoteVersionSource
import com.wdtt.plus.AppReleaseInfo
import com.wdtt.plus.RemoteVersionSource
@Composable
fun AppUpdateDialog(
@@ -106,7 +107,7 @@ fun AppUpdateDialog(
onClick = onPostpone,
modifier = Modifier
.weight(1f)
.height(50.dp),
.heightIn(min = 50.dp),
shape = RoundedCornerShape(22.dp)
) {
Text("Позже", fontWeight = FontWeight.SemiBold)
@@ -116,7 +117,7 @@ fun AppUpdateDialog(
onClick = onUpdate,
modifier = Modifier
.weight(1f)
.height(50.dp),
.heightIn(min = 50.dp),
shape = RoundedCornerShape(22.dp)
) {
Text("Обновить", fontWeight = FontWeight.Bold)
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,4 @@
package com.wdtt.client.ui
package com.wdtt.plus.ui
import android.content.pm.PackageManager
import androidx.compose.foundation.Image
@@ -13,6 +13,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
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.draw.clip
@@ -26,8 +27,11 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.graphics.drawable.toBitmap
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.client.SettingsStore
import androidx.lifecycle.compose.LifecycleResumeEffect
import com.wdtt.plus.isAlwaysBypassedVpnPackage
import com.wdtt.plus.SettingsStore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -46,6 +50,76 @@ object AppCache {
var cachedList: List<AppItem>? = null
}
private val VpnDetectionExactPackages = setOf(
"ru.sberbankmobile",
"ru.tinkoff.mb",
"ru.vtb24.mobilebanking.android",
"ru.alfabank.mobile.android",
"ru.ozon.app.android",
"com.wildberries.ru",
"ru.beru.android",
"ru.megamarket",
"ru.sbermarket",
"ru.samokat.android",
"com.avito.android",
"ru.yandex.searchplugin",
"ru.yandex.yandexmaps",
"ru.yandex.music",
"ru.kinopoisk",
"com.yandex.browser",
"ru.yandex.taxi",
"com.vkontakte.android",
"com.vk.vkvideo",
"ru.vk.music",
"ru.ok.android",
"ru.rutube.app",
"ru.mail.mailapp",
"ru.mail.cloud",
"ru.mts",
"ru.beeline.services",
"ru.tele2.mytele2",
"ru.megafon.mlk",
"ru.rostel",
"ru.gosuslugi.mobile",
"ru.vk.store",
"ru.dublgis.dgismobile",
"ru.maximoff.max"
)
private val VpnDetectionKeywords = listOf(
"sber", "сбер",
"tinkoff", "t-bank", "tbank", "тинькофф", "тбанк",
"vtb", "втб",
"alfa", "alpha", "альфа",
"ozon", "озон",
"wildberries", "вайлдберриз",
"yandex", "яндекс",
"vkontakte", "вконтакте",
"rutube", "рутуб",
"gosuslugi", "госуслуг",
"dublgis", "2gis", "dgis", "дубльгис",
"avito", "авито",
"mts", "мтс",
"beeline", "билайн",
"megafon", "мегафон",
"tele2", "теле2",
"mail.ru", "mailapp",
"ok.ru", "odnoklassniki",
"kinopoisk", "кинопоиск",
"samokat", "самокат",
"megamarket", "sbermarket",
"rostel", "ростел",
"maximoff"
)
private fun AppItem.matchesVpnDetectionApp(): Boolean {
val packageLower = packageName.lowercase()
if (packageLower in VpnDetectionExactPackages) return true
val titleLower = name.lowercase()
val haystack = "$packageLower $titleLower"
return VpnDetectionKeywords.any { keyword -> haystack.contains(keyword) }
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ExceptionsTab() {
@@ -53,50 +127,62 @@ fun ExceptionsTab() {
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
val savedExcluded by settingsStore.excludedApps.collectAsStateWithLifecycle(initialValue = "")
val selectedPackages = remember(savedExcluded) {
savedExcluded.split(",").filter { it.isNotEmpty() }.toSet()
val savedPackages by settingsStore.vpnAppPackages.collectAsStateWithLifecycle(initialValue = "")
val selectedPackages = remember(savedPackages) {
savedPackages.split(",").map { it.trim() }.filter { it.isNotEmpty() }.toSet()
}
var appsList by remember { mutableStateOf<List<AppItem>>(AppCache.cachedList ?: emptyList()) }
var isLoading by remember { mutableStateOf(AppCache.cachedList == null) }
var searchQuery by remember { mutableStateOf("") }
var quickExcludeStatus by rememberSaveable { mutableStateOf("") }
var reloadJob by remember { mutableStateOf<Job?>(null) }
fun scheduleWireGuardReload() {
reloadJob?.cancel()
reloadJob = scope.launch {
delay(250)
com.wdtt.plus.TunnelManager.reloadWireGuard()
}
}
val showSystemAppsOpt by settingsStore.showSystemApps.collectAsStateWithLifecycle(initialValue = null)
val isWhitelist by settingsStore.isWhitelist.collectAsStateWithLifecycle(initialValue = false)
// Load Apps
LaunchedEffect(Unit) {
if (AppCache.cachedList != null) return@LaunchedEffect
isLoading = true
withContext(Dispatchers.IO) {
val list = mutableListOf<AppItem>()
val pm = context.packageManager
val installedApps = pm.getInstalledApplications(PackageManager.GET_META_DATA)
// Обновляем список при каждом возвращении в приложение, а кэш используем только
// для мгновенного первого отображения.
LifecycleResumeEffect(Unit) {
val refreshJob = scope.launch {
if (appsList.isEmpty()) isLoading = true
val list = withContext(Dispatchers.IO) {
val loadedApps = mutableListOf<AppItem>()
val pm = context.packageManager
val installedApps = pm.getInstalledApplications(PackageManager.GET_META_DATA)
installedApps.forEach { app ->
if (app.packageName != context.packageName &&
!app.packageName.contains("vkontakte") &&
!app.packageName.contains("vk.calls")) {
val isSys = (app.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) != 0
list.add(AppItem(
name = app.loadLabel(pm).toString(),
packageName = app.packageName,
icon = app.loadIcon(pm)?.toBitmap()?.asImageBitmap(),
isSystem = isSys
))
installedApps.forEach { app ->
if (!isAlwaysBypassedVpnPackage(app.packageName, context.packageName)) {
val isSys = (app.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) != 0
loadedApps.add(AppItem(
name = app.loadLabel(pm).toString(),
packageName = app.packageName,
icon = app.loadIcon(pm)?.toBitmap()?.asImageBitmap(),
isSystem = isSys
))
}
}
loadedApps.sortedBy { it.name.lowercase() }
}
appsList = list.sortedBy { it.name.lowercase() }
appsList = list
AppCache.cachedList = appsList
isLoading = false
}
isLoading = false
onPauseOrDispose { refreshJob.cancel() }
}
val filteredApps by remember {
derivedStateOf {
val showSystemApps = showSystemAppsOpt ?: true
val showSystemApps = showSystemAppsOpt ?: false
val list = if (showSystemApps) {
appsList
} else {
@@ -116,7 +202,7 @@ fun ExceptionsTab() {
Column(modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp)) {
// Header
Text(
"Исключения приложений",
"Маршрутизация приложений",
style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold),
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.padding(top = 16.dp, bottom = 4.dp)
@@ -148,15 +234,15 @@ fun ExceptionsTab() {
) {
Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) {
Text(
"Режим исключений",
"Режим списка",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Medium,
fontSize = 14.sp,
color = MaterialTheme.colorScheme.onSurface
)
Text(
if (isWhitelist) "БС: Неотмеченные приложения добавляются в туннель"
else "ЧС: Выбранные приложения исключаются из туннеля",
if (isWhitelist) "БС: только отмеченные — через VPN"
else "ЧС: отмеченные — без VPN",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 11.sp,
@@ -167,22 +253,16 @@ fun ExceptionsTab() {
ModeChip("ЧС", !isWhitelist) {
if (isWhitelist) {
scope.launch {
val all = appsList.map { it.packageName }.toSet()
val inverted = all - selectedPackages
settingsStore.saveExceptionsMode(inverted.joinToString(","), false)
delay(300)
com.wdtt.client.TunnelManager.reloadWireGuard()
settingsStore.saveIsWhitelist(false)
scheduleWireGuardReload()
}
}
}
ModeChip("БС", isWhitelist) {
if (!isWhitelist) {
scope.launch {
val all = appsList.map { it.packageName }.toSet()
val inverted = all - selectedPackages
settingsStore.saveExceptionsMode(inverted.joinToString(","), true)
delay(300)
com.wdtt.client.TunnelManager.reloadWireGuard()
settingsStore.saveIsWhitelist(true)
scheduleWireGuardReload()
}
}
}
@@ -200,14 +280,14 @@ fun ExceptionsTab() {
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
"Системные приложения",
"Показывать системные",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.Medium,
fontSize = 14.sp,
color = MaterialTheme.colorScheme.onSurface
)
Switch(
checked = showSystemAppsOpt ?: true,
checked = showSystemAppsOpt ?: false,
onCheckedChange = { enabled ->
scope.launch {
settingsStore.saveShowSystemApps(enabled)
@@ -215,6 +295,53 @@ fun ExceptionsTab() {
}
)
}
if (!isWhitelist) {
Spacer(modifier = Modifier.height(12.dp))
OutlinedButton(
onClick = {
val detectedPackages = appsList
.filter { it.matchesVpnDetectionApp() }
.map { it.packageName }
.toSet()
if (detectedPackages.isEmpty()) {
quickExcludeStatus = "Подходящие приложения не найдены."
} else {
scope.launch {
val addedCount = settingsStore.addBlacklistPackages(detectedPackages)
quickExcludeStatus = "Исключено: ${detectedPackages.size}, добавлено: $addedCount."
scheduleWireGuardReload()
}
}
},
enabled = !isLoading && appsList.isNotEmpty(),
modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp),
shape = RoundedCornerShape(16.dp)
) {
Icon(Icons.Default.Search, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(Modifier.width(8.dp))
Text(
"Быстрые исключения",
fontWeight = FontWeight.SemiBold,
textAlign = TextAlign.Center,
modifier = Modifier.weight(1f)
)
}
Text(
"Банки, маркетплейсы и другие приложения, чувствительные к VPN. Поиск выполняется по известным названиям.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 6.dp)
)
if (quickExcludeStatus.isNotBlank()) {
Text(
quickExcludeStatus,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(top = 6.dp)
)
}
}
}
// List
@@ -224,31 +351,35 @@ fun ExceptionsTab() {
}
} else {
val listState = rememberLazyListState()
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(filteredApps, key = { it.packageName }) { app ->
val isSelected = selectedPackages.contains(app.packageName)
AppRow(
app = app,
isSelected = isSelected,
onClick = {
val newList = if (isSelected) {
selectedPackages - app.packageName
} else {
selectedPackages + app.packageName
}
scope.launch {
settingsStore.saveExcludedApps(newList.joinToString(","))
com.wdtt.client.TunnelManager.reloadWireGuard()
}
}
if (filteredApps.isEmpty()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
if (searchQuery.isBlank()) "Приложения не найдены" else "По запросу ничего не найдено",
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
} else {
LazyColumn(
state = listState,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(bottom = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(filteredApps, key = { it.packageName }) { app ->
val isSelected = selectedPackages.contains(app.packageName)
AppRow(
app = app,
isSelected = isSelected,
onClick = {
scope.launch {
settingsStore.toggleVpnAppSelected(app.packageName, isWhitelist)
scheduleWireGuardReload()
}
}
)
}
}
}
}
}
@@ -1,4 +1,4 @@
package com.wdtt.client.ui
package com.wdtt.plus.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Spring
@@ -12,6 +12,8 @@ import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import kotlinx.coroutines.launch
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
@@ -29,13 +31,13 @@ import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.client.SettingsStore
import com.wdtt.plus.SettingsStore
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.wdtt.client.R
import com.wdtt.plus.R
import android.os.Build
import androidx.compose.ui.graphics.Color
import kotlin.math.roundToInt
@@ -46,10 +48,13 @@ import androidx.compose.material.icons.filled.Close
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun FloatingToolbar(
activeProfile: Int,
onActiveProfileChange: (Int) -> Unit,
interfaceRole: String,
onInterfaceRoleChange: (String) -> Unit,
currentTheme: String,
onThemeChange: (String) -> Unit,
isDynamicColor: Boolean,
@@ -83,6 +88,7 @@ fun FloatingToolbar(
val tabWidthDp = 42.dp
val tabHeightDp = 52.dp
val panelWidthDp = 220.dp
val isAdminRole = interfaceRole != "user"
val tabWidthPx = remember(density) { with(density) { tabWidthDp.toPx() } }
val fallbackTabHeightPx = remember(density) { with(density) { tabHeightDp.toPx() } }
@@ -165,15 +171,21 @@ fun FloatingToolbar(
onDismissRequest = { isExpanded = false },
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
val dialogMaxHeight = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)
Surface(
shape = RoundedCornerShape(32.dp),
color = MaterialTheme.colorScheme.surface,
shadowElevation = 8.dp,
tonalElevation = 8.dp,
modifier = Modifier.fillMaxWidth(0.9f)
modifier = Modifier
.fillMaxWidth(0.9f)
.heightIn(max = dialogMaxHeight)
) {
Column(
modifier = Modifier.padding(16.dp),
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Row(
@@ -199,24 +211,26 @@ fun FloatingToolbar(
}
}
Row(
FlowRow(
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
listOf(0, 1, 2).forEach { profile ->
val selected = profile == activeProfile
val profileLabel = "VPN ${profile + 1}"
Surface(
onClick = { onActiveProfileChange(profile) },
shape = RoundedCornerShape(12.dp),
color = if (selected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
modifier = Modifier.weight(1f)
modifier = Modifier.weight(1f).widthIn(min = 62.dp)
) {
Box(
modifier = Modifier.padding(vertical = 8.dp),
contentAlignment = Alignment.Center
) {
Text(
text = "Пр. $profile",
text = profileLabel,
style = MaterialTheme.typography.bodyMedium,
fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface,
@@ -232,6 +246,37 @@ fun FloatingToolbar(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) {
Text(
if (isAdminRole) "Режим: Админ" else "Режим: Юзер",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
if (isAdminRole) "VPN и настройка своего сервера" else "Подключение и работа VPN",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 15.sp
)
}
Switch(
checked = isAdminRole,
onCheckedChange = { checked -> onInterfaceRoleChange(if (checked) "admin" else "user") },
modifier = Modifier.scale(0.85f)
)
}
HorizontalDivider(
modifier = Modifier.padding(vertical = 4.dp),
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
Text(
"Тема",
style = MaterialTheme.typography.labelMedium,
@@ -240,24 +285,32 @@ fun FloatingToolbar(
modifier = Modifier.padding(start = 4.dp, bottom = 4.dp)
)
ThemeOption(
icon = R.drawable.ic_auto,
label = "Системная",
selected = currentTheme == "system",
onClick = { onThemeChange("system"); isExpanded = false }
)
ThemeOption(
icon = R.drawable.ic_light_mode,
label = "Светлая",
selected = currentTheme == "light",
onClick = { onThemeChange("light"); isExpanded = false }
)
ThemeOption(
icon = R.drawable.ic_dark_mode,
label = "Тёмная",
selected = currentTheme == "dark",
onClick = { onThemeChange("dark"); isExpanded = false }
)
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
ThemeOption(
icon = R.drawable.ic_auto,
contentDescription = "Системная тема",
selected = currentTheme == "system",
onClick = { onThemeChange("system") },
modifier = Modifier.weight(1f)
)
ThemeOption(
icon = R.drawable.ic_light_mode,
contentDescription = "Светлая тема",
selected = currentTheme == "light",
onClick = { onThemeChange("light") },
modifier = Modifier.weight(1f)
)
ThemeOption(
icon = R.drawable.ic_dark_mode,
contentDescription = "Тёмная тема",
selected = currentTheme == "dark",
onClick = { onThemeChange("dark") },
modifier = Modifier.weight(1f)
)
}
val supportsDynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val showDynamicColorOn = isDynamicColor && supportsDynamicColor
@@ -323,7 +376,7 @@ fun FloatingToolbar(
modifier = Modifier.padding(start = 4.dp, bottom = 4.dp)
)
val fingerprints = listOf("chrome", "safari", "firefox")
val fingerprints = listOf("firefox", "chrome", "safari")
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp)
@@ -343,8 +396,8 @@ fun FloatingToolbar(
val fpName = when(fp) {
"chrome" -> "Chrome"
"safari" -> "Safari"
"firefox" -> "FireFox"
else -> fp.capitalize()
"firefox" -> "Firefox"
else -> fp.replaceFirstChar { it.uppercaseChar() }
}
Text(
text = fpName,
@@ -492,36 +545,29 @@ private fun checkVkClientId(appId: String): Boolean {
@Composable
private fun ThemeOption(
icon: Int,
label: String,
contentDescription: String,
selected: Boolean,
onClick: () -> Unit
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Surface(
onClick = onClick,
shape = RoundedCornerShape(24.dp),
color = if (selected) MaterialTheme.colorScheme.primaryContainer
else MaterialTheme.colorScheme.surface,
modifier = modifier.height(42.dp)
) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Icon(
painter = painterResource(id = icon),
contentDescription = null,
modifier = Modifier.size(18.dp),
contentDescription = contentDescription,
modifier = Modifier.size(20.dp),
tint = if (selected) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
text = label,
style = MaterialTheme.typography.bodyMedium,
fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
color = if (selected) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurface,
fontSize = 13.sp
)
}
}
}
@@ -1,4 +1,4 @@
package com.wdtt.client.ui
package com.wdtt.plus.ui
import androidx.compose.runtime.MutableState
@@ -20,6 +20,7 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.PaddingValues
@@ -73,7 +74,10 @@ import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
@@ -82,25 +86,26 @@ import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.client.BuildConfig
import com.wdtt.client.R
import com.wdtt.client.SettingsStore
import com.wdtt.client.UPDATE_DIALOG_ACTION_POSTPONED
import com.wdtt.client.UPDATE_DIALOG_ACTION_UPDATE
import com.wdtt.client.WDTTColors
import com.wdtt.client.fetchLatestReleaseInfo
import com.wdtt.client.isNewerVersion
import com.wdtt.plus.BuildConfig
import com.wdtt.plus.R
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED
import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE
import com.wdtt.plus.WDTTColors
import com.wdtt.plus.fetchLatestReleaseInfo
import com.wdtt.plus.isNewerVersion
import kotlinx.coroutines.launch
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.min
import kotlin.math.sin
private const val ReleasesUrl = "https://github.com/amurcanov/proxy-turn-vk-android/releases"
private const val IssuesUrl = "https://github.com/amurcanov/proxy-turn-vk-android/issues/new"
private const val DeveloperProfileUrl = "https://github.com/amurcanov"
private const val RepositoryUrl = "https://github.com/amurcanov/proxy-turn-vk-android"
private const val DonateUrl = ""
private const val ReleasesUrl = "https://github.com/Ivan4537/WDTT-Plus/releases"
private const val IssuesUrl = "https://github.com/Ivan4537/WDTT-Plus/issues/new"
private const val DeveloperProfileUrl = "https://github.com/Ivan4537"
private const val RepositoryUrl = "https://github.com/Ivan4537/WDTT-Plus"
private const val DonateUrl = "https://yoomoney.ru/to/410012216336438"
private const val OriginalDonateUrl = "https://yoomoney.ru/to/4100119505530465/"
private val DonateActionButtonColor = Color(0xFF00AEA5)
private val browserPackages = listOf(
@@ -165,13 +170,18 @@ fun InfoTab(
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
val infoScrollState = rememberScrollState()
val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() }
var actionsSectionY by remember { mutableStateOf(0f) }
var projectSectionY by remember { mutableStateOf(0f) }
val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" }
var isCheckingUpdates by remember { mutableStateOf(false) }
var pendingManualRelease by remember { mutableStateOf<com.wdtt.client.AppReleaseInfo?>(null) }
var showHelpDialog by remember { mutableStateOf(false) }
var showDonateDialog by remember { mutableStateOf(false) }
var actionsExpanded by actionsExpandedState
var projectExpanded by projectExpandedState
val releaseDate = remember { BuildConfig.MOD_RELEASE_DATE }
var isCheckingUpdates by remember { mutableStateOf(false) }
var pendingManualRelease by remember { mutableStateOf<com.wdtt.plus.AppReleaseInfo?>(null) }
var showHelpDialog by remember { mutableStateOf(false) }
var showSupportDialog by remember { mutableStateOf(false) }
var actionsExpanded by actionsExpandedState
var projectExpanded by projectExpandedState
val updateLatestVersion by settingsStore.updateLatestVersion.collectAsStateWithLifecycle(initialValue = "")
val updateLastError by settingsStore.updateLastError.collectAsStateWithLifecycle(initialValue = "")
val updateStatus = remember(isCheckingUpdates, updateLatestVersion, updateLastError, currentVersion) {
@@ -190,7 +200,7 @@ fun InfoTab(
.fillMaxSize()
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp, top = 0.dp, bottom = 28.dp)
.verticalScroll(rememberScrollState()),
.verticalScroll(infoScrollState),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Row(
@@ -206,13 +216,27 @@ fun InfoTab(
)
}
InfoHeroCard(currentVersion = currentVersion, onSupportClick = { showDonateDialog = true })
InfoHeroCard(
currentVersion = currentVersion,
releaseDate = releaseDate,
onSupportClick = { showSupportDialog = true }
)
ExpandableSectionCard(
title = "Действия",
itemCount = "4 пункта",
expanded = actionsExpanded,
onToggle = { actionsExpanded = !actionsExpanded },
modifier = Modifier.onGloballyPositioned { actionsSectionY = it.positionInParent().y },
onToggle = {
val willExpand = !actionsExpanded
actionsExpanded = willExpand
if (willExpand) {
scope.launch {
kotlinx.coroutines.delay(80)
infoScrollState.animateScrollTo((actionsSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0))
}
}
},
icon = {
Icon(
imageVector = Icons.Default.Info,
@@ -222,44 +246,37 @@ fun InfoTab(
)
}
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp)
) {
InfoActionTile(
title = "Поднять вопрос",
subtitle = "Открыть GitHub issue",
modifier = Modifier.weight(1f),
onClick = { openUrlInBrowser(context, IssuesUrl) },
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_github),
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer
)
}
)
WideActionTile(
title = "Поднять вопрос",
subtitle = "Открыть GitHub issue",
onClick = { openUrlInBrowser(context, IssuesUrl) },
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_github),
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer
)
}
)
InfoActionTile(
title = "Собрать отчёт",
subtitle = "Android, ABI, версия, устройство",
modifier = Modifier.weight(1f),
onClick = {
val clipboard = context.getSystemService(ClipboardManager::class.java)
clipboard?.setPrimaryClip(ClipData.newPlainText("WDTT Report", buildSupportReport()))
Toast.makeText(context, "Отчёт сформирован и скопирован", Toast.LENGTH_SHORT).show()
},
icon = {
Icon(
imageVector = Icons.Default.ContentCopy,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer
)
}
)
}
WideActionTile(
title = "Собрать отчёт",
subtitle = "Android, ABI, версия, устройство",
onClick = {
val clipboard = context.getSystemService(ClipboardManager::class.java)
clipboard?.setPrimaryClip(ClipData.newPlainText("WDTT Report", buildSupportReport()))
Toast.makeText(context, "Отчёт сформирован и скопирован", Toast.LENGTH_SHORT).show()
},
icon = {
Icon(
imageVector = Icons.Default.ContentCopy,
contentDescription = null,
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onPrimaryContainer
)
}
)
WideActionTile(
title = "Справка",
@@ -362,7 +379,17 @@ fun InfoTab(
title = "О проекте",
itemCount = "3 ссылки",
expanded = projectExpanded,
onToggle = { projectExpanded = !projectExpanded },
modifier = Modifier.onGloballyPositioned { projectSectionY = it.positionInParent().y },
onToggle = {
val willExpand = !projectExpanded
projectExpanded = willExpand
if (willExpand) {
scope.launch {
kotlinx.coroutines.delay(80)
infoScrollState.animateScrollTo((projectSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0))
}
}
},
icon = {
Icon(
imageVector = Icons.Default.Code,
@@ -372,25 +399,25 @@ fun InfoTab(
)
}
) {
ProjectLinkRow(
title = "Автор Android-версии",
subtitle = "GitHub профиль amurcanov",
onClick = { openUrlInBrowser(context, DeveloperProfileUrl) },
icon = {
Icon(
imageVector = Icons.Default.Person,
ProjectLinkRow(
title = "Разработка модификации",
subtitle = "GitHub профиль Ivan4537",
onClick = { openUrlInBrowser(context, DeveloperProfileUrl) },
icon = {
Icon(
imageVector = Icons.Default.Person,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(18.dp)
)
}
)
)
ProjectLinkRow(
title = "Репозиторий WDTT",
subtitle = "Исходники и релизы приложения",
onClick = { openUrlInBrowser(context, RepositoryUrl) },
icon = {
ProjectLinkRow(
title = "Репозиторий WDTT Plus",
subtitle = "Исходники и релизы приложения",
onClick = { openUrlInBrowser(context, RepositoryUrl) },
icon = {
Icon(
painter = painterResource(id = R.drawable.ic_github),
contentDescription = null,
@@ -416,14 +443,167 @@ fun InfoTab(
}
Spacer(modifier = Modifier.height(20.dp))
}
}
if (showHelpDialog) ImportantInfoDialog(onDismiss = { showHelpDialog = false })
if (showDonateDialog) DonateDialog(onDismiss = { showDonateDialog = false })
if (showHelpDialog) ImportantInfoDialog(onDismiss = { showHelpDialog = false })
if (showSupportDialog) {
SupportProjectDialog(
onDismiss = { showSupportDialog = false },
onDonateModClick = { openUrlInBrowser(context, DonateUrl) },
onDonateOriginalClick = { openUrlInBrowser(context, OriginalDonateUrl) }
)
}
}
@Composable
private fun InfoHeroCard(currentVersion: String, onSupportClick: () -> Unit) {
private fun SupportProjectDialog(
onDismiss: () -> Unit,
onDonateModClick: () -> Unit,
onDonateOriginalClick: () -> Unit
) {
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
BoxWithConstraints(
modifier = Modifier.fillMaxSize().padding(8.dp),
contentAlignment = Alignment.Center
) {
Surface(
shape = RoundedCornerShape(28.dp),
color = MaterialTheme.colorScheme.surface,
tonalElevation = 8.dp,
shadowElevation = 18.dp,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp)
.heightIn(max = maxHeight * 0.92f)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalAlignment = Alignment.CenterVertically
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Box(modifier = Modifier.size(42.dp), contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.Favorite,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(20.dp)
)
}
}
Column(modifier = Modifier.weight(1f)) {
Text(
"Поддержать проект",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface
)
}
FilledTonalIconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = null)
}
}
SupportDonateBlock(
title = "WDTT Plus",
body = "Поддержка этой версии помогает развивать доработки приложения, серверной части, Telegram-бота и удобство для пользователей.",
buttonText = "ЮMoney",
onClick = onDonateModClick,
emphasized = true
)
SupportDonateBlock(
title = "Автор оригинального приложения",
body = "Оригинальная основа проекта создана amurcanov. Можно отдельно поддержать автора исходного приложения.",
buttonText = "ЮMoney",
onClick = onDonateOriginalClick,
emphasized = false
)
Spacer(Modifier.height(4.dp))
}
}
}
}
}
@Composable
private fun SupportDonateBlock(
title: String,
body: String,
buttonText: String,
onClick: () -> Unit,
emphasized: Boolean
) {
val containerColor = if (emphasized) {
DonateActionButtonColor.copy(alpha = 0.12f)
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
}
val borderColor = if (emphasized) {
DonateActionButtonColor.copy(alpha = 0.38f)
} else {
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)
}
Surface(
shape = RoundedCornerShape(22.dp),
color = containerColor,
border = BorderStroke(1.dp, borderColor)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Text(
title,
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
body,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 18.sp
)
Button(
onClick = onClick,
shape = RoundedCornerShape(18.dp),
colors = ButtonDefaults.buttonColors(
containerColor = if (emphasized) DonateActionButtonColor else MaterialTheme.colorScheme.primary,
contentColor = Color.White
),
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 46.dp)
) {
Text(buttonText, fontWeight = FontWeight.Bold)
}
}
}
}
@Composable
private fun InfoHeroCard(
currentVersion: String,
releaseDate: String,
onSupportClick: () -> Unit
) {
val colors = MaterialTheme.colorScheme
val isDark = colors.background.luminance() < 0.22f
val heroBrush = remember(colors.primaryContainer, colors.secondaryContainer, colors.surfaceVariant) {
@@ -479,13 +659,14 @@ private fun InfoHeroCard(currentVersion: String, onSupportClick: () -> Unit) {
verticalAlignment = Alignment.CenterVertically
) {
HeroMetaPill(
text = "WDTT",
text = "WDTT Plus",
containerColor = glassColor,
borderColor = glassBorder,
modifier = Modifier.weight(1f)
)
HeroMetaPill(
text = currentVersion,
HeroVersionPill(
version = currentVersion,
releaseDate = releaseDate,
containerColor = colors.primary.copy(alpha = if (isDark) 0.18f else 0.10f),
borderColor = colors.primary.copy(alpha = if (isDark) 0.22f else 0.14f),
modifier = Modifier.weight(1f)
@@ -494,7 +675,7 @@ private fun InfoHeroCard(currentVersion: String, onSupportClick: () -> Unit) {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = "WDTT VPN Tunnel",
text = "WDTT Plus",
style = MaterialTheme.typography.headlineSmall.copy(
fontWeight = FontWeight.Black,
fontSize = 30.sp,
@@ -502,32 +683,32 @@ private fun InfoHeroCard(currentVersion: String, onSupportClick: () -> Unit) {
),
color = colors.onSurface
)
Text(
text = "Android-клиент для TURN/VK туннеля с WireGuard, капчей и управлением сервером.",
style = MaterialTheme.typography.bodyMedium,
color = colors.onSurfaceVariant,
lineHeight = 21.sp
)
}
Text(
text = "Модифицированная версия оригинального проекта amurcanov: Android-клиент для TURN/VK туннеля с WireGuard, капчей и управлением сервером.",
style = MaterialTheme.typography.bodyMedium,
color = colors.onSurfaceVariant,
lineHeight = 21.sp
)
}
Button(
onClick = onSupportClick,
shape = RoundedCornerShape(22.dp),
colors = ButtonDefaults.buttonColors(
containerColor = DonateActionButtonColor,
contentColor = Color.White
),
modifier = Modifier
.fillMaxWidth()
.height(54.dp)
) {
Icon(Icons.Default.Favorite, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(8.dp))
Text("Поддержать проект", fontWeight = FontWeight.Bold, fontSize = 15.sp)
}
}
}
}
Button(
onClick = onSupportClick,
shape = RoundedCornerShape(22.dp),
colors = ButtonDefaults.buttonColors(
containerColor = DonateActionButtonColor,
contentColor = Color.White
),
modifier = Modifier
.fillMaxWidth()
.heightIn(min = 54.dp)
) {
Icon(Icons.Default.Favorite, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(8.dp))
Text("Поддержать проект", fontWeight = FontWeight.Bold, fontSize = 15.sp)
}
}
}
}
}
@Composable
@@ -541,16 +722,56 @@ private fun HeroMetaPill(
shape = RoundedCornerShape(18.dp),
color = containerColor,
border = BorderStroke(1.dp, borderColor),
modifier = modifier
modifier = modifier.height(52.dp)
) {
Text(
text = text,
modifier = Modifier.padding(horizontal = 12.dp, vertical = 9.dp),
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center
)
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
Text(
text = text,
modifier = Modifier.padding(horizontal = 12.dp),
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center
)
}
}
}
@Composable
private fun HeroVersionPill(
version: String,
releaseDate: String,
containerColor: Color,
borderColor: Color,
modifier: Modifier = Modifier
) {
Surface(
shape = RoundedCornerShape(18.dp),
color = containerColor,
border = BorderStroke(1.dp, borderColor),
modifier = modifier.height(52.dp)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 12.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = "Версия ${version.removePrefix("v")}",
style = MaterialTheme.typography.labelLarge,
fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onSurface,
textAlign = TextAlign.Center
)
Text(
text = "от $releaseDate",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
}
}
}
@@ -559,6 +780,7 @@ private fun ExpandableSectionCard(
title: String,
itemCount: String,
expanded: Boolean,
modifier: Modifier = Modifier,
onToggle: () -> Unit,
icon: @Composable () -> Unit,
content: @Composable ColumnScope.() -> Unit
@@ -569,8 +791,9 @@ private fun ExpandableSectionCard(
)
AppSectionCard(
modifier = modifier,
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 18.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
verticalArrangement = Arrangement.spacedBy(0.dp)
) {
Row(
modifier = Modifier
@@ -611,7 +834,10 @@ private fun ExpandableSectionCard(
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut()
) {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
Column(
modifier = Modifier.padding(top = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f))
content()
}
@@ -790,77 +1016,6 @@ private fun ProjectLinkRow(
}
}
@Composable
private fun DonateDialog(onDismiss: () -> Unit) {
val context = LocalContext.current
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Surface(
shape = RoundedCornerShape(32.dp),
color = MaterialTheme.colorScheme.surface,
contentColor = MaterialTheme.colorScheme.onSurface,
tonalElevation = 10.dp,
shadowElevation = 14.dp,
modifier = Modifier.fillMaxWidth(0.92f)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 24.dp, vertical = 22.dp),
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Text(
text = "Поддержка проекта",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Black,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.weight(1f)
)
FilledTonalIconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
Text(
text = "Если приложение реально помогает, можно поддержать Android-версию проекта.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
lineHeight = 20.sp
)
Button(
onClick = { openUrlInBrowser(context, DonateUrl) },
modifier = Modifier
.fillMaxWidth()
.height(62.dp),
shape = RoundedCornerShape(22.dp),
colors = ButtonDefaults.buttonColors(
containerColor = WDTTColors.donate,
contentColor = Color.White
)
) {
Icon(
painter = painterResource(id = R.drawable.ic_yoomoney),
contentDescription = "ЮMoney",
tint = Color.Unspecified,
modifier = Modifier
.width(126.dp)
.height(28.dp)
)
}
}
}
}
}
private fun buildSupportReport(): String {
val androidVersion = Build.VERSION.RELEASE ?: "?"
val sdkInt = Build.VERSION.SDK_INT
@@ -890,6 +1045,7 @@ private fun buildSupportReport(): String {
return buildString {
appendLine("Версия приложения: ${BuildConfig.VERSION_NAME}")
appendLine("Дата релиза: ${BuildConfig.MOD_RELEASE_DATE}")
appendLine("Андроид: $androidVersion (SDK $sdkInt)")
appendLine("Устройство: $manufacturer / $brand / $model")
appendLine("Код устройства: $device")
@@ -1,4 +1,4 @@
package com.wdtt.client.ui
package com.wdtt.plus.ui
import android.content.ClipData
import android.content.ClipboardManager
@@ -26,10 +26,10 @@ import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.client.LogEntry
import com.wdtt.client.TunnelManager
import com.wdtt.client.WDTTColors
import com.wdtt.client.SettingsStore
import com.wdtt.plus.LogEntry
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.WDTTColors
import com.wdtt.plus.SettingsStore
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
File diff suppressed because it is too large. Load diff