From b3aad32990ec1a7786f5d5d41672c7ea879e53bf Mon Sep 17 00:00:00 2001 From: Ivan4537 Date: Tue, 7 Jul 2026 22:55:52 +0300 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=8B=D0=BF=D1=83=D1=81=D0=BA=20WDTT=20P?= =?UTF-8?q?lus=20v11?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 12 + README.md | 4 +- app/build.gradle.kts | 4 +- app/src/main/AndroidManifest.xml | 3 + .../java/com/wdtt/plus/DeviceCompatibility.kt | 41 +- .../main/java/com/wdtt/plus/MainActivity.kt | 10 +- .../com/wdtt/plus/QuickToggleTileService.kt | 33 +- .../main/java/com/wdtt/plus/SettingsStore.kt | 79 +++ .../main/java/com/wdtt/plus/TrustedWifi.kt | 175 ++++++ .../main/java/com/wdtt/plus/TunnelManager.kt | 9 +- .../main/java/com/wdtt/plus/TunnelService.kt | 489 +++++++++++++++- .../com/wdtt/plus/VpnCompactWidgetProvider.kt | 8 +- .../java/com/wdtt/plus/VpnWidgetProvider.kt | 12 +- .../java/com/wdtt/plus/WdttApplication.kt | 3 +- .../wdtt/plus/ui/DeviceCompatibilityDialog.kt | 2 +- .../java/com/wdtt/plus/ui/FloatingToolbar.kt | 54 +- app/src/main/java/com/wdtt/plus/ui/InfoTab.kt | 76 +-- app/src/main/java/com/wdtt/plus/ui/LogsTab.kt | 3 +- .../main/java/com/wdtt/plus/ui/SettingsTab.kt | 148 +++-- .../wdtt/plus/ui/TrustedWifiSettingsDialog.kt | 522 ++++++++++++++++++ .../java/com/wdtt/plus/TrustedWifiTest.kt | 126 +++++ .../com/wdtt/plus/TunnelStopReasonTest.kt | 14 + go_client/dispatcher.go | 6 +- go_client/session.go | 23 +- go_client/stats.go | 12 +- 25 files changed, 1722 insertions(+), 146 deletions(-) create mode 100644 app/src/main/java/com/wdtt/plus/TrustedWifi.kt create mode 100644 app/src/main/java/com/wdtt/plus/ui/TrustedWifiSettingsDialog.kt create mode 100644 app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index b98e01e..ab260c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ Здесь фиксируются заметные пользовательские изменения WDTT Plus. +## v11 — 07.07.2026 + +### Туннель + +- Добавлены доверенные сети Wi-Fi: после запуска VPN он переходит в ожидание только при фактическом подключении к выбранному SSID и автоматически восстанавливает прежний профиль после выхода из сети. Ручное отключение отменяет восстановление, а плитка, виджеты и уведомление показывают состояние ожидания. +- Исправлена остановка транспорта на части 32-битных ARMv7-устройств из-за некорректной работы внутренних счётчиков. +- Исправлено сохранение мощности на вкладке «Туннель»: выбранное значение выше 27 не сбрасывается при переключении вкладок. + +### Диагностика + +- Проверка устройства и диагностический отчёт объединены в одно действие; рекомендации для маломощных устройств учитывают минимальную мощность 9 потоков. + ## v10 — 07.07.2026 ### SSH-ключи diff --git a/README.md b/README.md index 97a5975..38228f8 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ - **Проверка VK-хешей:** приложение проверяет каждый слот звонка, при необходимости проходит капчу и показывает отдельный результат. Хеши можно копировать по одному или все заполненные сразу в порядке слотов. Настройка мощности сопровождается пояснением о потоках, нагрузке и частоте проверок VK. - **Настраиваемый выходной IP:** из Android и Telegram-бота управляются прямой выход, прокси VPS, внешний TCP-прокси, бесплатный WARP, готовый VPN/WireGuard-файл и WireGuard-выход через другой сервер. Приложение показывает состояние режимов на сервере, проверяет конфликтные маршруты перед включением и откатывается при ошибке. - **Маршрутизация приложений:** ЧС и БС являются отдельными списками: в ЧС отмеченные приложения обходят VPN, в БС только отмеченные идут через VPN. Есть быстрый подбор приложений, чувствительных к VPN; смена режима перезапускает только WireGuard-слой. +- **Доверенные сети Wi-Fi:** VPN может автоматически переходить в ожидание в выбранных домашних или рабочих сетях и восстанавливать прежнее подключение после выхода из них. Ручное отключение отменяет автовосстановление, а неопределённая сеть никогда не отключает VPN. - **Captcha и устойчивость транспорта:** перед captcha-цепочкой можно использовать VKCalls preflight; временный flood не создаёт повторный шквал запросов. Авто-режим начинает с Auto WebView и переходит к Go v2 и ручному WebView только при необходимости. Расширены восстановление после смены сети и пробуждения, контроль зависшего трафика и fail-open отключение неработающего VPN. - **Самостоятельная сборка WDTT Plus:** приложение использует пакет `com.wdtt.plus`, собственный канал обновлений и отдельное оформление. Gradle пересобирает Android `libclient.so` и сервер для деплоя из исходников, а release APK получает понятные имена для каждой ABI. @@ -60,6 +61,7 @@ - **Полноценный VPN-режим:** приложение использует `VpnService` и WireGuard GoBackend, поэтому трафик выбранных приложений проходит через системный VPN-интерфейс без ручного импорта конфигов. - **Три профиля подключения:** VPN 1, VPN 2 и VPN 3 хранят отдельные настройки туннеля и деплоя; профиль можно переименовать долгим нажатием в боковых настройках. Название активного профиля видно в заголовках вкладок, передаче подключения, плитке быстрых настроек и активном уведомлении туннеля. - **Корректная передача VPN-слота:** если Android отключает WDTT Plus VPN или другой VPN забирает системный VPN-слот, WDTT Plus останавливает транспорт и переводит плитку/виджет в неактивное состояние. Плитка запускает VPN как с обычными настройками, так и в режиме ссылки, а при активном подключении показывает выбранный профиль вместе с уведомлением туннеля. +- **Доверенные сети Wi-Fi:** в боковых настройках можно добавить текущую сеть или точный SSID вручную. В доверенной сети системный VPN-интерфейс снимается и интернет работает напрямую, а тихое уведомление сохраняет режим ожидания. После перехода на мобильную или другую Wi-Fi сеть прежний VPN-профиль восстанавливается. Android запрашивает доступ к местоположению только потому, что относит имя Wi-Fi к чувствительным данным; координаты приложение не получает. - **TURN/DTLS-транспорт:** нативный Go-клиент получает временные TURN-учётные данные VK-звонка и поднимает DTLS-соединения к relay-серверу, через который передаётся трафик до вашего сервера. - **Импорт VK-ссылок через «Поделиться»:** ссылку VK-звонка можно отправить прямо в WDTT Plus. Приложение извлечёт хеш после `/call/join/`, заполнит следующий слот VK-хеша и покажет, какой номер был обновлён. - **Передача между устройствами:** текущий VPN-профиль отправляется как `wdtt://`-ссылка, файл или QR-код. Приложение принимает эти данные через Android, камеру, галерею и выбор файла, сохраняя совместимость со старыми ссылками. @@ -217,7 +219,7 @@ Telegram-бот умеет посмотреть статус и диагност #### Отчёт для issue -В разделе **«Информация»** есть кнопки **«Собрать отчёт»** и **«Проверить устройство»**. Отчёт копирует версию приложения, Android SDK, ABI и разрядность, размер страницы памяти, модель устройства, SoC, ROM, память, состояние сети, WebView и безопасные параметры запуска. Проверка устройства отдельно показывает текущую версию WDTT Plus, дату релиза, актуальна ли версия на момент копирования, совместимость, предупреждения, текущее состояние VPN и переходы в нужные настройки Android. Адреса, пароли, токены и значения VK-хешей в отчёт не включаются. +В разделе **«Информация»** действие **«Проверить устройство»** одновременно проверяет совместимость и формирует полный диагностический отчёт: версию приложения, Android SDK, ABI и разрядность, размер страницы памяти, модель устройства, SoC, ROM, память, сеть, WebView и безопасные параметры запуска. Отчёт можно скопировать из окна проверки; адреса, пароли, токены и значения VK-хешей в него не включаются. > [!NOTE] > ### Отчёты об ошибках diff --git a/app/build.gradle.kts b/app/build.gradle.kts index de287ca..76cb62f 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -5,7 +5,7 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") } -val appVersionName = "10" +val appVersionName = "11" val releaseApkBaseName = "WDTT-Plus" val localProperties = Properties() @@ -22,7 +22,7 @@ android { applicationId = "com.wdtt.plus" minSdk = 28 targetSdk = 35 - versionCode = 10 + versionCode = 11 versionName = appVersionName buildConfigField("String", "MOD_RELEASE_DATE", "\"07.07.2026\"") diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a7853bc..d3a570b 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -8,6 +8,9 @@ + + + diff --git a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt index bfca787..3554e3c 100644 --- a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt +++ b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt @@ -49,7 +49,8 @@ data class DeviceCheckItem( data class DeviceCompatibilityReport( val checkedAt: Long, - val items: List + val items: List, + val summaryLines: List = emptyList() ) { val problemItems: List get() = items.filter { it.severity == DeviceCheckSeverity.Warning || it.severity == DeviceCheckSeverity.Error } @@ -79,6 +80,11 @@ data class DeviceCompatibilityReport( appendLine("Проверка устройства WDTT Plus") appendLine("Проверено: ${formatter.format(Date(checkedAt))}") appendLine("Итог: $overallStatus") + if (summaryLines.isNotEmpty()) { + appendLine() + appendLine("Сводка") + summaryLines.forEach { line -> appendLine(line) } + } items.forEach { item -> appendLine() appendLine("[${item.severity.label()}] ${item.title}: ${item.status}") @@ -107,6 +113,7 @@ object DeviceCompatibility { add(androidVersionItem()) add(abiItem()) add(nativeClientItem(appContext)) + nativeRuntimeSafetyItem()?.let(::add) add(pageSizeItem()) add(memoryClassItem(appContext, workersPerHash)) add(webViewItem(includeRuntimeChecks)) @@ -198,7 +205,7 @@ object DeviceCompatibility { title = "Архитектура CPU", status = "32-bit ARM / armeabi-v7a", details = "Эта ABI поддерживается, но на старых 32-битных устройствах запас по памяти и потокам обычно ниже, чем на arm64.", - recommendation = "Если туннель нестабилен, уменьшите мощность до 4–8 потоков и приложите отчёт из Инфо.", + recommendation = "Если туннель нестабилен, уменьшите мощность до минимальных 9 потоков и скопируйте отчёт через «Проверить устройство».", severity = DeviceCheckSeverity.Info, firstLaunchRelevant = false ) @@ -212,6 +219,18 @@ object DeviceCompatibility { } } + private fun nativeRuntimeSafetyItem(): DeviceCheckItem? { + val primary = Build.SUPPORTED_ABIS.firstOrNull().orEmpty() + if (primary != "armeabi-v7a") return null + return DeviceCheckItem( + title = "32-bit нативный режим", + status = "безопасные atomic-счётчики", + details = "В этой сборке Android Go-клиент использует выровненные typed atomics для трафика, активных каналов и health-monitor. Это защищает старые ARMv7-устройства от остановки транспорта из-за 64-bit atomic-доступов.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = true + ) + } + private fun nativeClientItem(context: Context): DeviceCheckItem { val nativeLibraryDir = context.applicationInfo.nativeLibraryDir.orEmpty() val nativeClient = File(nativeLibraryDir, "libclient.so") @@ -249,7 +268,7 @@ object DeviceCompatibility { title = "Страница памяти", status = "не удалось определить", details = "Android не вернул размер страницы памяти.", - recommendation = "Если VPN не стартует на новом устройстве, приложите отчёт из Инфо.", + recommendation = "Если VPN не стартует на новом устройстве, скопируйте отчёт через «Проверить устройство».", severity = DeviceCheckSeverity.Info, firstLaunchRelevant = false ) @@ -257,7 +276,7 @@ object DeviceCompatibility { title = "Страница памяти", status = "$pageSize байт", details = "Устройство использует страницу памяти больше 4 KB. Для новых Android-устройств с 16 KB page size нужна отдельная проверка нативной библиотеки.", - recommendation = "Запуск не блокируется. Если туннель не стартует, отправьте отчёт из Инфо — это важный сценарий для будущей совместимости.", + recommendation = "Запуск не блокируется. Если туннель не стартует, отправьте отчёт из «Проверить устройство» — это важный сценарий для будущей совместимости.", severity = DeviceCheckSeverity.Warning, firstLaunchRelevant = true ) @@ -284,7 +303,7 @@ object DeviceCompatibility { title = "Память устройства", status = "low-RAM, мощность $workersPerHash", details = "Android помечает устройство как low-RAM. Большое число потоков может не успевать стабильно подняться.", - recommendation = "Для таких устройств начните с 4–8 потоков. Это не ошибка подключения к профилю VPN.", + recommendation = "Для таких устройств начните с минимальных 9 потоков. Это не ошибка подключения к профилю VPN.", severity = DeviceCheckSeverity.Warning, firstLaunchRelevant = true ) @@ -292,7 +311,7 @@ object DeviceCompatibility { title = "Память устройства", status = "low-RAM / Android Go возможен", details = "Устройство относится к классу с ограниченной памятью. Приложение может работать, но высокая мощность будет менее предсказуемой.", - recommendation = "Если активные потоки не появляются, уменьшите мощность до 4–8 и проверьте логи.", + recommendation = "Если активные потоки не появляются, уменьшите мощность до минимальных 9 потоков и проверьте логи.", severity = DeviceCheckSeverity.Warning, firstLaunchRelevant = true ) @@ -433,9 +452,17 @@ object DeviceCompatibility { private fun tunnelStateItem(): DeviceCheckItem { val running = TunnelManager.running.value + val trustedWifi = TrustedWifiManager.state.value val activeWorkers = TunnelManager.activeWorkers.value val issue = TunnelManager.connectionIssue.value - return if (running) { + return if (trustedWifi.waiting) { + DeviceCheckItem( + title = "Текущее подключение VPN", + status = "ожидание доверенной Wi-Fi сети", + details = "VPN сейчас выключен автоматикой доверенных сетей и восстановится после выхода из Wi-Fi.", + severity = DeviceCheckSeverity.Ok + ) + } else if (running) { DeviceCheckItem( title = "Текущее подключение VPN", status = "активно", diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt index 0b013f5..04aa179 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -20,6 +20,7 @@ import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedContent import androidx.compose.animation.core.Animatable +import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.CubicBezierEasing import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn @@ -1032,6 +1033,11 @@ fun MainScreen( ) { val deployVisible = selectedTab == 1 && !wdttLinkMode val deployAvailable = activeNavItems.any { it.id == 1 } && !wdttLinkMode + val deployAlpha by animateFloatAsState( + targetValue = if (deployVisible) 1f else 0f, + animationSpec = tween(durationMillis = if (deployVisible) 300 else 225), + label = "deploy_tab_fade" + ) if (deployAvailable) { tabStateHolder.SaveableStateProvider("deploy_persistent") { DeployTab( @@ -1040,8 +1046,8 @@ fun MainScreen( modifier = Modifier .fillMaxSize() .padding(bottom = navOverlayReserve) - .graphicsLayer { alpha = if (deployVisible) 1f else 0f } - .zIndex(if (deployVisible) 1f else -1f) + .graphicsLayer { alpha = deployAlpha } + .zIndex(if (deployVisible || deployAlpha > 0f) 1f else -1f) ) } } diff --git a/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt b/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt index 6bb11cb..7302bd6 100644 --- a/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt +++ b/app/src/main/java/com/wdtt/plus/QuickToggleTileService.kt @@ -31,12 +31,13 @@ class QuickToggleTileService : TileService() { val settingsStore = SettingsStore(this@QuickToggleTileService) combine( TunnelManager.running, + TrustedWifiManager.state, settingsStore.activeProfile, settingsStore.profileNames - ) { running, activeProfile, profileNames -> - Triple(running, activeProfile, profileNames) - }.collect { (running, activeProfile, profileNames) -> - updateTile(running, activeProfile, profileNames) + ) { running, trustedWifi, activeProfile, profileNames -> + TileUiState(running, trustedWifi, activeProfile, profileNames) + }.collect { uiState -> + updateTile(uiState) } } catch (e: Exception) { Log.e("QuickToggleTile", "Error collecting running state", e) @@ -52,7 +53,7 @@ class QuickToggleTileService : TileService() { override fun onClick() { super.onClick() runCatching { - if (TunnelManager.running.value) { + if (TunnelManager.running.value || TrustedWifiManager.state.value.waiting) { // Если запущен — останавливаем. Состояние плитки изменится автоматически, // когда TunnelManager остановит процессы и обновит статус running в false. val stopIntent = Intent(this, TunnelService::class.java).apply { action = "STOP" } @@ -97,22 +98,31 @@ class QuickToggleTileService : TileService() { super.onDestroy() } - private fun updateTile(running: Boolean, activeProfile: Int, profileNames: List) { + private fun updateTile(uiState: TileUiState) { runCatching { + val running = uiState.running + val waiting = uiState.trustedWifi.waiting + val activeProfile = uiState.activeProfile + val profileNames = uiState.profileNames val profile = activeProfile.coerceIn(0, 2) val profileLabel = vpnProfileDisplayName(profile, profileNames) val defaultProfileLabel = vpnProfileDefaultName(profile) val profileIsDefault = profileLabel == defaultProfileLabel qsTile?.apply { label = when { + waiting -> "Ожидание" !running -> "WDTT Plus" profileIsDefault -> "WDTT Plus $profileLabel" else -> profileLabel } icon = Icon.createWithResource(this@QuickToggleTileService, R.drawable.ic_tile_logo) - state = if (running) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE + state = if (running && !waiting) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE if (Build.VERSION.SDK_INT >= 29) { - subtitle = if (running) "" else "Отключено" + subtitle = when { + waiting -> uiState.trustedWifi.ssid.ifBlank { "Wi-Fi" } + running -> "" + else -> "Отключено" + } } updateTile() } @@ -121,6 +131,13 @@ class QuickToggleTileService : TileService() { } } + private data class TileUiState( + val running: Boolean, + val trustedWifi: TrustedWifiRuntimeState, + val activeProfile: Int, + val profileNames: List + ) + private fun openMainActivity() { runCatching { val intent = Intent(this, MainActivity::class.java).apply { diff --git a/app/src/main/java/com/wdtt/plus/SettingsStore.kt b/app/src/main/java/com/wdtt/plus/SettingsStore.kt index 7964168..4212516 100644 --- a/app/src/main/java/com/wdtt/plus/SettingsStore.kt +++ b/app/src/main/java/com/wdtt/plus/SettingsStore.kt @@ -258,6 +258,10 @@ class SettingsStore(context: Context) { private val PROFILE_NAME = stringPreferencesKey("profile_name") private val SHOW_SYSTEM_APPS = booleanPreferencesKey("show_system_apps") private val LOGGING_ENABLED = booleanPreferencesKey("logging_enabled") + private val TRUSTED_WIFI_ENABLED = booleanPreferencesKey("trusted_wifi_enabled") + private val TRUSTED_WIFI_SSIDS = stringPreferencesKey("trusted_wifi_ssids") + private val TRUSTED_WIFI_WAITING = booleanPreferencesKey("trusted_wifi_waiting") + private val TRUSTED_WIFI_WAITING_SSID = stringPreferencesKey("trusted_wifi_waiting_ssid") private val WDTT_LINK = stringPreferencesKey("wdtt_link") private val WDTT_LINK_MODE = booleanPreferencesKey("wdtt_link_mode") @@ -394,6 +398,14 @@ class SettingsStore(context: Context) { } val showSystemApps: Flow = preferencesFlow.map { it[SHOW_SYSTEM_APPS] ?: false } val loggingEnabled: Flow = preferencesFlow.map { it[LOGGING_ENABLED] ?: true } + val trustedWifiEnabled: Flow = preferencesFlow.map { it[TRUSTED_WIFI_ENABLED] ?: false } + val trustedWifiSsids: Flow> = preferencesFlow.map { prefs -> + parseTrustedWifiSsids(prefs[TRUSTED_WIFI_SSIDS].orEmpty()) + } + val trustedWifiWaiting: Flow = preferencesFlow.map { it[TRUSTED_WIFI_WAITING] ?: false } + val trustedWifiWaitingSsid: Flow = preferencesFlow.map { + sanitizeTrustedWifiSsid(it[TRUSTED_WIFI_WAITING_SSID].orEmpty()) + } val wdttLink: Flow = preferencesFlow.map { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(WDTT_LINK, profile)] ?: "" @@ -821,6 +833,53 @@ class SettingsStore(context: Context) { } } + suspend fun saveTrustedWifiEnabled(enabled: Boolean) { + dataStore.edit { prefs -> + prefs[TRUSTED_WIFI_ENABLED] = enabled + if (!enabled) { + prefs.remove(TRUSTED_WIFI_WAITING) + prefs.remove(TRUSTED_WIFI_WAITING_SSID) + } + } + } + + suspend fun addTrustedWifiSsid(ssid: String): Boolean { + val clean = sanitizeTrustedWifiSsid(ssid) + if (clean.isBlank()) return false + var added = false + dataStore.edit { prefs -> + val values = parseTrustedWifiSsids(prefs[TRUSTED_WIFI_SSIDS].orEmpty()).toMutableList() + if (clean !in values) { + values.add(clean) + added = true + } + prefs[TRUSTED_WIFI_SSIDS] = JSONArray(values).toString() + } + return added + } + + suspend fun removeTrustedWifiSsid(ssid: String) { + val clean = sanitizeTrustedWifiSsid(ssid) + dataStore.edit { prefs -> + val values = parseTrustedWifiSsids(prefs[TRUSTED_WIFI_SSIDS].orEmpty()) + .filterNot { it == clean } + if (values.isEmpty()) prefs.remove(TRUSTED_WIFI_SSIDS) + else prefs[TRUSTED_WIFI_SSIDS] = JSONArray(values).toString() + } + } + + suspend fun saveTrustedWifiWaiting(waiting: Boolean, ssid: String = "") { + dataStore.edit { prefs -> + if (waiting) { + prefs[TRUSTED_WIFI_WAITING] = true + prefs[TRUSTED_WIFI_WAITING_SSID] = sanitizeTrustedWifiSsid(ssid) + } else { + prefs.remove(TRUSTED_WIFI_WAITING) + prefs.remove(TRUSTED_WIFI_WAITING_SSID) + } + } + } + suspend fun saveWdttLink(link: String) { dataStore.edit { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 @@ -1092,6 +1151,13 @@ class SettingsStore(context: Context) { } } + suspend fun saveWorkersPerHash(workersPerHash: Int) { + dataStore.edit { prefs -> + val profile = prefs[ACTIVE_PROFILE] ?: 0 + prefs[getProfileKey(WORKERS_PER_HASH, profile)] = workersPerHash.coerceIn(1, 128) + } + } + suspend fun insertVkHashFromShare(hash: String): VkHashInsertResult { val cleanedHash = VkJoinLink.extractHash(hash) require(cleanedHash.length >= 16) { "VK-хеш слишком короткий" } @@ -1483,6 +1549,19 @@ class SettingsStore(context: Context) { fun vpnProfileDefaultName(profile: Int): String = "VPN ${profile.coerceIn(0, 2) + 1}" +private fun parseTrustedWifiSsids(raw: String): List { + if (raw.isBlank()) return emptyList() + return runCatching { + val json = JSONArray(raw) + buildList { + for (index in 0 until json.length()) { + val ssid = sanitizeTrustedWifiSsid(json.optString(index)) + if (ssid.isNotBlank() && ssid !in this) add(ssid) + } + } + }.getOrDefault(emptyList()) +} + fun sanitizeVpnProfileNameInput(name: String): String { val safe = buildString { name.forEach { character -> diff --git a/app/src/main/java/com/wdtt/plus/TrustedWifi.kt b/app/src/main/java/com/wdtt/plus/TrustedWifi.kt new file mode 100644 index 0000000..58822bd --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/TrustedWifi.kt @@ -0,0 +1,175 @@ +package com.wdtt.plus + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.location.LocationManager +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.wifi.WifiInfo +import android.net.wifi.WifiManager +import android.os.Build +import android.provider.Settings +import androidx.core.content.ContextCompat +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow + +private const val UNKNOWN_WIFI_SSID = "" +private const val BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION" + +data class TrustedWifiRuntimeState( + val waiting: Boolean = false, + val ssid: String = "", + val status: String = "" +) + +object TrustedWifiManager { + private val _state = MutableStateFlow(TrustedWifiRuntimeState()) + val state = _state.asStateFlow() + + fun setWaiting(ssid: String, status: String = "VPN ожидает выхода из доверенной сети") { + _state.value = TrustedWifiRuntimeState(waiting = true, ssid = ssid, status = status) + } + + fun setStatus(status: String) { + _state.value = _state.value.copy(status = status) + } + + fun clear() { + _state.value = TrustedWifiRuntimeState() + } +} + +enum class TrustedWifiAccessProblem { + ForegroundPermission, + BackgroundPermission, + LocationDisabled +} + +data class ConnectedWifiState( + val connected: Boolean, + val ssid: String = "", + val accessProblem: TrustedWifiAccessProblem? = null +) { + val ssidAvailable: Boolean get() = connected && ssid.isNotBlank() && accessProblem == null +} + +enum class TrustedWifiTransition { + None, + EnterWaiting, + ResumeVpn +} + +internal fun decideTrustedWifiTransition( + enabled: Boolean, + tunnelRunning: Boolean, + waiting: Boolean, + wifi: ConnectedWifiState, + trustedSsids: Set +): TrustedWifiTransition { + if (!enabled) return TrustedWifiTransition.None + if (trustedSsids.isEmpty()) { + return if (waiting) TrustedWifiTransition.ResumeVpn else TrustedWifiTransition.None + } + if (waiting) { + if (!wifi.connected) return TrustedWifiTransition.ResumeVpn + if (!wifi.ssidAvailable) return TrustedWifiTransition.ResumeVpn + return if (wifi.ssid in trustedSsids) TrustedWifiTransition.None else TrustedWifiTransition.ResumeVpn + } + if (!tunnelRunning || !wifi.ssidAvailable) return TrustedWifiTransition.None + return if (wifi.ssid in trustedSsids) TrustedWifiTransition.EnterWaiting else TrustedWifiTransition.None +} + +internal fun shouldKeepTunnelServiceAlive( + tunnelRunning: Boolean, + tunnelPaused: Boolean, + trustedWifiWaiting: Boolean, + trustedWifiResumeInProgress: Boolean +): Boolean = tunnelRunning || tunnelPaused || trustedWifiWaiting || trustedWifiResumeInProgress + +fun sanitizeTrustedWifiSsid(value: String): String { + val clean = value + .filterNot { Character.isISOControl(it) } + .trim() + .removeSurrounding("\"") + .trim() + if (clean.isEmpty()) return "" + + val result = StringBuilder() + var byteCount = 0 + clean.forEach { character -> + val characterBytes = character.toString().toByteArray(Charsets.UTF_8).size + if (byteCount + characterBytes <= 32) { + result.append(character) + byteCount += characterBytes + } + } + return result.toString() +} + +fun hasTrustedWifiForegroundPermission(context: Context): Boolean = + ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == + PackageManager.PERMISSION_GRANTED + +fun hasTrustedWifiBackgroundPermission(context: Context): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || + ContextCompat.checkSelfPermission(context, BACKGROUND_LOCATION_PERMISSION) == + PackageManager.PERMISSION_GRANTED + +fun trustedWifiAccessProblem(context: Context): TrustedWifiAccessProblem? { + if (!hasTrustedWifiForegroundPermission(context)) return TrustedWifiAccessProblem.ForegroundPermission + if (!hasTrustedWifiBackgroundPermission(context)) return TrustedWifiAccessProblem.BackgroundPermission + val locationManager = context.getSystemService(LocationManager::class.java) + if (locationManager?.isLocationEnabled != true) return TrustedWifiAccessProblem.LocationDisabled + return null +} + +fun isWdttAlwaysOnVpn(context: Context): Boolean = runCatching { + Settings.Secure.getString(context.contentResolver, "always_on_vpn_app") == context.packageName +}.getOrDefault(false) + +@Suppress("DEPRECATION") +fun readConnectedWifiState(context: Context): ConnectedWifiState { + val appContext = context.applicationContext + val connectivityManager = appContext.getSystemService(ConnectivityManager::class.java) + val wifiConnected = runCatching { + connectivityManager?.allNetworks?.any { network -> + connectivityManager.getNetworkCapabilities(network)?.let { capabilities -> + capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && + capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) + } == true + } == true + }.getOrDefault(false) + if (!wifiConnected) return ConnectedWifiState(connected = false) + + val accessProblem = trustedWifiAccessProblem(appContext) + if (accessProblem != null) { + return ConnectedWifiState(connected = true, accessProblem = accessProblem) + } + + val capabilitiesSsid = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + runCatching { + connectivityManager?.allNetworks + ?.asSequence() + ?.mapNotNull { network -> connectivityManager.getNetworkCapabilities(network) } + ?.firstOrNull { + it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && + it.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) + } + ?.transportInfo + ?.let { it as? WifiInfo } + ?.ssid + }.getOrNull() + } else { + null + } + val fallbackSsid = runCatching { + appContext.getSystemService(WifiManager::class.java)?.connectionInfo?.ssid + }.getOrNull() + val ssid = sanitizeTrustedWifiSsid( + listOf(capabilitiesSsid, fallbackSsid) + .firstOrNull { !it.isNullOrBlank() && !it.equals(UNKNOWN_WIFI_SSID, ignoreCase = true) } + .orEmpty() + ) + return ConnectedWifiState(connected = true, ssid = ssid) +} diff --git a/app/src/main/java/com/wdtt/plus/TunnelManager.kt b/app/src/main/java/com/wdtt/plus/TunnelManager.kt index b2ba667..4986462 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelManager.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelManager.kt @@ -62,6 +62,7 @@ enum class TunnelStopReason(val displayText: String) { WakeRecoveryFailed("VPN не восстановился после пробуждения"), CriticalError("критическая ошибка подключения"), CaptchaCancelled("проверка отменена пользователем"), + TrustedWifi("подключена доверенная сеть Wi-Fi"), RestoreFailed("не удалось восстановить VPN"), ServiceDestroyed("служба VPN остановлена системой") } @@ -73,7 +74,13 @@ private val stoppedStatsTrafficPairRegex = Regex( internal fun buildStoppedSessionStats(previousStats: String, reason: TunnelStopReason): String { val traffic = stoppedStatsTrafficPairRegex.find(previousStats)?.value return buildString { - append("VPN отключён · Причина: ") + append( + if (reason == TunnelStopReason.TrustedWifi) { + "VPN в ожидании · Причина: " + } else { + "VPN отключён · Причина: " + } + ) append(reason.displayText) append(" · Активных: 0") if (!traffic.isNullOrBlank()) { diff --git a/app/src/main/java/com/wdtt/plus/TunnelService.kt b/app/src/main/java/com/wdtt/plus/TunnelService.kt index 63a9238..0ceb5f0 100644 --- a/app/src/main/java/com/wdtt/plus/TunnelService.kt +++ b/app/src/main/java/com/wdtt/plus/TunnelService.kt @@ -25,8 +25,12 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.first import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext private const val TUNNEL_NOTIFICATION_CHANNEL_ID = "wdtt_tunnel_v4" private const val TUNNEL_ALERT_CHANNEL_ID = "wdtt_tunnel_alert_v1" @@ -40,6 +44,11 @@ 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 +private const val TRUSTED_WIFI_ENTER_DELAY_MS = 2_000L +private const val TRUSTED_WIFI_EXIT_DELAY_MS = 5_000L +private const val TRUSTED_WIFI_FAST_RESUME_RETRY_COUNT = 12 +private const val TRUSTED_WIFI_SLOW_RESUME_RETRY_MS = 30_000L +private const val TRUSTED_WIFI_RESUME_START_TIMEOUT_MS = 30_000L class TunnelService : Service() { private var wakeLock: PowerManager.WakeLock? = null @@ -62,7 +71,21 @@ class TunnelService : Service() { private var lastStableNetworkReconnectAt = 0L private var stableNetworkWasLost = false private var screenStateReceiver: BroadcastReceiver? = null + private var trustedWifiStateReceiver: BroadcastReceiver? = null private var wakeRescueJob: Job? = null + private var trustedWifiNetworkCallback: ConnectivityManager.NetworkCallback? = null + private var trustedWifiSettingsJob: Job? = null + private var trustedWifiEvaluationJob: Job? = null + private val trustedWifiEvaluationScheduleLock = Any() + private var trustedWifiPendingEvaluationDelayMs: Long? = null + private var trustedWifiResumeRetryJob: Job? = null + private var trustedWifiResumeRetryCount = 0 + private var trustedWifiResumeInProgress = false + private var trustedWifiResumeStartedAt = 0L + private val trustedWifiTransitionMutex = Mutex() + private var trustedWifiWaiting = false + private var trustedWifiWaitingSsid = "" + private var lastStartParams: TunnelParams? = null override fun onCreate() { super.onCreate() @@ -70,7 +93,9 @@ class TunnelService : Service() { // Сразу берем лок при создании acquireWakeLock() setupNetworkCallback() + setupTrustedWifiMonitoring() registerScreenStateReceiver() + registerTrustedWifiStateReceiver() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { @@ -99,7 +124,10 @@ class TunnelService : Service() { fingerprint = intent.getStringExtra("fingerprint") ?: "firefox", clientIds = intent.getStringExtra("client_ids") ?: "6287487,8202606" ) - startTunnel(params) + lastStartParams = params + TunnelManager.scope.launch(Dispatchers.Main) { + startOrWaitForTrustedWifi(params) + } } "STOP" -> stopTunnel(TunnelStopReason.User) "DEPLOY_START" -> { @@ -110,14 +138,31 @@ class TunnelService : Service() { "DEPLOY_CANCEL" -> { com.wdtt.plus.DeployManager.writeError("[!] ❌ Установка отменена пользователем") com.wdtt.plus.DeployManager.stopDeploy("error: Отменена пользователем") - stopForeground(STOP_FOREGROUND_REMOVE) + if (trustedWifiWaiting) updateTrustedWifiNotification() + else if (TunnelManager.running.value) updateNotification("Туннель активен") + else stopForeground(STOP_FOREGROUND_REMOVE) + scheduleTrustedWifiEvaluation(delayMs = 0L) } "DEPLOY_STOP" -> { - if (!TunnelManager.running.value) { + if (trustedWifiWaiting) { + updateTrustedWifiNotification() + } else if (!TunnelManager.running.value) { stopTunnel() } else { updateNotification("Туннель активен") } + scheduleTrustedWifiEvaluation(delayMs = 0L) + } + "TRUSTED_WIFI_RECHECK" -> { + val restoredState = TrustedWifiManager.state.value + if (!trustedWifiWaiting && restoredState.waiting) { + trustedWifiWaiting = true + trustedWifiWaitingSsid = restoredState.ssid + startPersistentForeground(createNotification("Проверка доверенной Wi-Fi сети...")) + startNotificationProfileWatcher() + startStatsUpdater() + } + scheduleTrustedWifiEvaluation(delayMs = 0L) } } return START_STICKY @@ -130,10 +175,22 @@ class TunnelService : Service() { val appContext = applicationContext TunnelManager.scope.launch { try { + val store = SettingsStore(appContext) val params = buildTunnelParamsFromSettings(appContext) if (params != null) { launch(Dispatchers.Main) { - startTunnel(params) + lastStartParams = params + val restoreWaiting = store.trustedWifiEnabled.first() && store.trustedWifiWaiting.first() + if (restoreWaiting) { + trustedWifiWaiting = true + trustedWifiWaitingSsid = store.trustedWifiWaitingSsid.first() + TrustedWifiManager.setWaiting(trustedWifiWaitingSsid) + startNotificationProfileWatcher() + startStatsUpdater() + scheduleTrustedWifiEvaluation(delayMs = 0L) + } else { + startOrWaitForTrustedWifi(params) + } } } else { launch(Dispatchers.Main) { @@ -148,7 +205,19 @@ class TunnelService : Service() { } } - private fun startTunnel(params: TunnelParams) { + private fun startTunnel(params: TunnelParams, fromTrustedWifiResume: Boolean = false) { + trustedWifiResumeRetryJob?.cancel() + trustedWifiResumeRetryJob = null + trustedWifiResumeRetryCount = 0 + trustedWifiResumeInProgress = fromTrustedWifiResume + trustedWifiResumeStartedAt = if (fromTrustedWifiResume) System.currentTimeMillis() else 0L + trustedWifiWaiting = false + trustedWifiWaitingSsid = "" + lastStartParams = params + TrustedWifiManager.clear() + TunnelManager.scope.launch { + SettingsStore(applicationContext).saveTrustedWifiWaiting(false) + } requestedStopReason = null updateNotification("Подключение...") acquireWakeLock() @@ -170,9 +239,22 @@ class TunnelService : Service() { profileNameJob?.cancel() networkChangeJob?.cancel() wakeRescueJob?.cancel() + trustedWifiResumeRetryJob?.cancel() profileNameJob = null networkChangeJob = null wakeRescueJob = null + trustedWifiResumeRetryJob = null + trustedWifiResumeRetryCount = 0 + trustedWifiResumeInProgress = false + trustedWifiResumeStartedAt = 0L + cancelTrustedWifiEvaluations() + trustedWifiWaiting = false + trustedWifiWaitingSsid = "" + lastStartParams = null + TrustedWifiManager.clear() + TunnelManager.scope.launch { + SettingsStore(applicationContext).saveTrustedWifiWaiting(false) + } // Уничтожаем текущий WebView (если капча решается) и чистим контекст CaptchaWebViewManager.onTunnelStop() @@ -201,7 +283,9 @@ class TunnelService : Service() { "WDTT Plus · $profileLabel" }.collect { prefix -> notificationProfileTitle = prefix - if (TunnelManager.running.value && !isTunnelPaused) { + if (trustedWifiWaiting) { + updateTrustedWifiNotification() + } else if (TunnelManager.running.value && !isTunnelPaused) { updateNotification(buildTunnelNotificationText()) } } @@ -213,7 +297,10 @@ class TunnelService : Service() { screenStateReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { - Intent.ACTION_SCREEN_ON -> scheduleWakeRescueCheck() + Intent.ACTION_SCREEN_ON -> { + scheduleWakeRescueCheck() + scheduleTrustedWifiEvaluation(delayMs = 0L) + } Intent.ACTION_SCREEN_OFF -> { wakeRescueJob?.cancel() wakeRescueJob = null @@ -233,6 +320,52 @@ class TunnelService : Service() { } } + private fun registerTrustedWifiStateReceiver() { + if (trustedWifiStateReceiver != null) return + trustedWifiStateReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + val runtimeState = TrustedWifiManager.state.value + if (!trustedWifiWaiting && runtimeState.waiting) { + trustedWifiWaiting = true + trustedWifiWaitingSsid = runtimeState.ssid + } + if (!trustedWifiWaiting) return + when (intent?.action) { + WifiManager.WIFI_STATE_CHANGED_ACTION -> { + val state = intent.getIntExtra( + WifiManager.EXTRA_WIFI_STATE, + WifiManager.WIFI_STATE_UNKNOWN + ) + when (state) { + WifiManager.WIFI_STATE_DISABLING, + WifiManager.WIFI_STATE_DISABLED, + WifiManager.WIFI_STATE_UNKNOWN -> { + keepTrustedWifiForeground("Ожидание рабочей сети") + scheduleTrustedWifiEvaluation(delayMs = 0L) + scheduleTrustedWifiResumeRetry() + } + else -> scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS) + } + } + WifiManager.NETWORK_STATE_CHANGED_ACTION -> { + keepTrustedWifiForeground() + scheduleTrustedWifiEvaluation(delayMs = 0L) + } + } + } + } + val filter = IntentFilter().apply { + addAction(WifiManager.WIFI_STATE_CHANGED_ACTION) + addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + registerReceiver(trustedWifiStateReceiver, filter, RECEIVER_NOT_EXPORTED) + } else { + @Suppress("DEPRECATION") + registerReceiver(trustedWifiStateReceiver, filter) + } + } + private fun scheduleWakeRescueCheck() { if (!AMNEZIA_STYLE_RECOVERY || !TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return val wakeAt = System.currentTimeMillis() @@ -274,6 +407,269 @@ class TunnelService : Service() { } } + private suspend fun startOrWaitForTrustedWifi(params: TunnelParams) { + val store = SettingsStore(applicationContext) + val enabled = store.trustedWifiEnabled.first() + val trustedSsids = store.trustedWifiSsids.first().toSet() + val wifi = readConnectedWifiState(applicationContext) + if (isWdttAlwaysOnVpn(applicationContext) && wifi.ssidAvailable && wifi.ssid in trustedSsids) { + startTunnel(params) + TunnelManager.scope.launch { + delay(300L) + TunnelManager.reportConnectionIssue( + "Доверенная сеть не применена", + "Для WDTT Plus включён системный режим «Всегда включённый VPN». Отключите его в настройках Android, если хотите использовать сети без VPN.", + isError = false + ) + } + return + } + if ( + decideTrustedWifiTransition( + enabled = enabled, + tunnelRunning = true, + waiting = false, + wifi = wifi, + trustedSsids = trustedSsids + ) == TrustedWifiTransition.EnterWaiting + ) { + lastStartParams = params + enterTrustedWifiWaiting(wifi.ssid) + } else { + startTunnel(params) + } + } + + private fun setupTrustedWifiMonitoring() { + val manager = connectivityManager + ?: (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).also { + connectivityManager = it + } + trustedWifiNetworkCallback = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_ENTER_DELAY_MS) + } + + override fun onLost(network: Network) { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) + } + + override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) { + scheduleTrustedWifiEvaluation( + if (trustedWifiWaiting) TRUSTED_WIFI_EXIT_DELAY_MS else TRUSTED_WIFI_ENTER_DELAY_MS + ) + } + } + val request = NetworkRequest.Builder() + .addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) + .build() + runCatching { manager.registerNetworkCallback(request, trustedWifiNetworkCallback!!) } + .onFailure { Log.w("TunnelService", "Не удалось включить наблюдение доверенных Wi-Fi: ${it.message}") } + + val store = SettingsStore(applicationContext) + trustedWifiSettingsJob = TunnelManager.scope.launch { + combine(store.trustedWifiEnabled, store.trustedWifiSsids) { enabled, ssids -> + enabled to ssids + }.collect { (enabled, _) -> + if (!enabled && trustedWifiWaiting) { + withContext(Dispatchers.Main) { + stopTunnel(TunnelStopReason.User) + } + } else { + scheduleTrustedWifiEvaluation(delayMs = 0L) + } + } + } + } + + private fun scheduleTrustedWifiEvaluation(delayMs: Long) { + val safeDelayMs = delayMs.coerceAtLeast(0L) + synchronized(trustedWifiEvaluationScheduleLock) { + trustedWifiPendingEvaluationDelayMs = trustedWifiPendingEvaluationDelayMs + ?.let { current -> minOf(current, safeDelayMs) } + ?: safeDelayMs + if (trustedWifiEvaluationJob?.isActive == true) return + trustedWifiEvaluationJob = TunnelManager.scope.launch { + runTrustedWifiEvaluationLoop() + } + } + } + + private suspend fun runTrustedWifiEvaluationLoop() { + while (true) { + val delayMs = synchronized(trustedWifiEvaluationScheduleLock) { + val pending = trustedWifiPendingEvaluationDelayMs + if (pending == null) { + trustedWifiEvaluationJob = null + return + } + trustedWifiPendingEvaluationDelayMs = null + pending + } + if (delayMs > 0L) delay(delayMs) + evaluateTrustedWifiState() + } + } + + private fun cancelTrustedWifiEvaluations() { + synchronized(trustedWifiEvaluationScheduleLock) { + trustedWifiPendingEvaluationDelayMs = null + trustedWifiEvaluationJob?.cancel() + trustedWifiEvaluationJob = null + } + } + + private fun scheduleTrustedWifiResumeRetry() { + trustedWifiResumeRetryJob?.cancel() + val delayMs = if (trustedWifiResumeRetryCount < TRUSTED_WIFI_FAST_RESUME_RETRY_COUNT) { + TRUSTED_WIFI_EXIT_DELAY_MS + } else { + TRUSTED_WIFI_SLOW_RESUME_RETRY_MS + } + trustedWifiResumeRetryCount += 1 + trustedWifiResumeRetryJob = TunnelManager.scope.launch { + delay(delayMs) + if (trustedWifiWaiting) { + evaluateTrustedWifiState() + } + } + } + + private suspend fun evaluateTrustedWifiState() { + if (DeployManager.isDeploying.value) return + val store = SettingsStore(applicationContext) + val enabled = store.trustedWifiEnabled.first() + val trustedSsids = store.trustedWifiSsids.first().toSet() + if (!enabled) return + + val wifi = readConnectedWifiState(applicationContext) + if (isWdttAlwaysOnVpn(applicationContext) && !trustedWifiWaiting) { + if (wifi.ssidAvailable && wifi.ssid in trustedSsids && TunnelManager.running.value) { + TunnelManager.reportConnectionIssue( + "Доверенная сеть не применена", + "Системный режим «Всегда включённый VPN» несовместим с автоматическим отключением VPN.", + isError = false + ) + } + return + } + when ( + decideTrustedWifiTransition( + enabled = enabled, + tunnelRunning = TunnelManager.running.value, + waiting = trustedWifiWaiting, + wifi = wifi, + trustedSsids = trustedSsids + ) + ) { + TrustedWifiTransition.EnterWaiting -> enterTrustedWifiWaiting(wifi.ssid) + TrustedWifiTransition.ResumeVpn -> resumeFromTrustedWifiWaiting() + TrustedWifiTransition.None -> { + if (trustedWifiWaiting && wifi.accessProblem != null) { + val status = when (wifi.accessProblem) { + TrustedWifiAccessProblem.ForegroundPermission, + TrustedWifiAccessProblem.BackgroundPermission -> + "Нужен доступ к имени Wi-Fi. Откройте настройки доверенных сетей." + TrustedWifiAccessProblem.LocationDisabled -> + "Включите определение местоположения, чтобы распознать Wi-Fi." + } + TrustedWifiManager.setStatus(status) + withContext(Dispatchers.Main) { updateNotification(status) } + } else if (trustedWifiWaiting && wifi.ssidAvailable && wifi.ssid in trustedSsids) { + trustedWifiWaitingSsid = wifi.ssid + TrustedWifiManager.setWaiting(wifi.ssid) + store.saveTrustedWifiWaiting(true, wifi.ssid) + withContext(Dispatchers.Main) { updateTrustedWifiNotification() } + } + } + } + } + + private suspend fun enterTrustedWifiWaiting(ssid: String) { + trustedWifiTransitionMutex.withLock { + if (trustedWifiWaiting) return + val cleanSsid = sanitizeTrustedWifiSsid(ssid) + if (cleanSsid.isBlank()) return + + val params = lastStartParams ?: buildTunnelParamsFromSettings(applicationContext) ?: return + lastStartParams = params + trustedWifiWaiting = true + trustedWifiWaitingSsid = cleanSsid + isTunnelPaused = false + trustedWifiResumeRetryCount = 0 + networkChangeJob?.cancel() + wakeRescueJob?.cancel() + trustedWifiResumeRetryJob?.cancel() + trustedWifiResumeRetryJob = null + + TunnelManager.stopAndWait(TunnelStopReason.TrustedWifi) + WireGuardHelper(applicationContext).stopTunnel() + TrustedWifiManager.setWaiting(cleanSsid) + SettingsStore(applicationContext).saveTrustedWifiWaiting(true, cleanSsid) + withContext(Dispatchers.Main) { + releaseWakeLock() + releaseWifiLock() + startNotificationProfileWatcher() + startStatsUpdater() + updateTrustedWifiNotification() + VpnWidgetProvider.updateAllWidgets(applicationContext) + } + } + } + + private suspend fun resumeFromTrustedWifiWaiting() { + trustedWifiTransitionMutex.withLock { + if (!trustedWifiWaiting) return + if (!hasUsableRealNetworkForTrustedWifiResume()) { + val status = "Ожидание рабочей сети" + TrustedWifiManager.setStatus(status) + withContext(Dispatchers.Main) { + keepTrustedWifiForeground(status) + VpnWidgetProvider.updateAllWidgets(applicationContext) + } + scheduleTrustedWifiResumeRetry() + return + } + if (android.net.VpnService.prepare(applicationContext) != null) { + val status = "VPN-разрешение недоступно. Откройте WDTT Plus для восстановления." + TrustedWifiManager.setStatus(status) + withContext(Dispatchers.Main) { updateNotification(status) } + return + } + + val params = lastStartParams ?: buildTunnelParamsFromSettings(applicationContext) + if (params == null) { + val status = "Не удалось прочитать профиль VPN. Откройте WDTT Plus." + TrustedWifiManager.setStatus(status) + withContext(Dispatchers.Main) { updateNotification(status) } + return + } + + withContext(Dispatchers.Main) { + Log.i("TunnelService", "Доверенная Wi-Fi покинута, запускаем VPN на рабочей сети") + // startTunnel синхронно включает защитный resumeInProgress до снятия waiting. + // Поэтому очередной сетевой callback уже не может оставить сервис между + // состояниями: без VPN, без ожидания и с удалённым уведомлением. + startTunnel(params, fromTrustedWifiResume = true) + VpnWidgetProvider.updateAllWidgets(applicationContext) + } + } + } + + private fun updateTrustedWifiNotification() { + keepTrustedWifiForeground() + } + + private fun keepTrustedWifiForeground(statusOverride: String? = null) { + val networkName = trustedWifiWaitingSsid.ifBlank { "доверенная Wi-Fi" } + val text = statusOverride ?: "VPN выключен в сети «$networkName» · ожидание выхода" + val title = notificationProfileTitle + lastNotificationTitle = title + lastNotificationText = text + startPersistentForeground(createNotification(text)) + } + private fun setupNetworkCallback() { connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager activeNetworks.clear() @@ -281,6 +677,9 @@ class TunnelService : Service() { networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { super.onAvailable(network) + if (trustedWifiWaiting) { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) + } val wasEmpty = activeNetworks.isEmpty() activeNetworks.add(network) if (AMNEZIA_STYLE_RECOVERY) { @@ -299,6 +698,9 @@ class TunnelService : Service() { override fun onLost(network: Network) { super.onLost(network) + if (trustedWifiWaiting) { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) + } activeNetworks.remove(network) if (AMNEZIA_STYLE_RECOVERY) { if (lastValidatedNetwork == network) { @@ -324,6 +726,9 @@ class TunnelService : Service() { override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) { super.onCapabilitiesChanged(network, networkCapabilities) + if (trustedWifiWaiting) { + scheduleTrustedWifiEvaluation(TRUSTED_WIFI_EXIT_DELAY_MS) + } if (AMNEZIA_STYLE_RECOVERY) { handleStableNetworkCapabilities(network, networkCapabilities) return @@ -420,6 +825,20 @@ class TunnelService : Service() { } } + @Suppress("DEPRECATION") + private fun hasUsableRealNetworkForTrustedWifiResume(): Boolean { + val cm = connectivityManager + ?: (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).also { + connectivityManager = it + } + 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) && + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) + } + } + private fun scheduleNetworkSettleCheck( reason: String, settleMs: Long, @@ -544,7 +963,35 @@ class TunnelService : Service() { updateJob = TunnelManager.scope.launch(Dispatchers.Main) { delay(1000) while (isActive) { - if (!TunnelManager.running.value && !isTunnelPaused) { + if (trustedWifiResumeInProgress) { + when { + TunnelManager.running.value -> { + trustedWifiResumeInProgress = false + trustedWifiResumeStartedAt = 0L + } + trustedWifiResumeStartedAt > 0L && + System.currentTimeMillis() - trustedWifiResumeStartedAt >= + TRUSTED_WIFI_RESUME_START_TIMEOUT_MS -> { + trustedWifiResumeInProgress = false + trustedWifiResumeStartedAt = 0L + trustedWifiWaiting = true + val status = "VPN не запустился, повторяем восстановление" + Log.w("TunnelService", status) + TrustedWifiManager.setWaiting("", status) + SettingsStore(applicationContext).saveTrustedWifiWaiting(true) + keepTrustedWifiForeground(status) + scheduleTrustedWifiResumeRetry() + } + } + } + if ( + !shouldKeepTunnelServiceAlive( + tunnelRunning = TunnelManager.running.value, + tunnelPaused = isTunnelPaused, + trustedWifiWaiting = trustedWifiWaiting, + trustedWifiResumeInProgress = trustedWifiResumeInProgress + ) + ) { // Туннель полностью остановлен (не на паузе) — убиваем сервис stopSelf() break @@ -591,7 +1038,7 @@ class TunnelService : Service() { } } } - if (!isTunnelPaused) { + if (!isTunnelPaused && !trustedWifiWaiting) { updateNotification(buildTunnelNotificationText()) } delay(2000) @@ -684,7 +1131,11 @@ class TunnelService : Service() { .setOngoing(true) .setLocalOnly(true) .setContentIntent(openIntent) - .addAction(R.drawable.ic_stop, actionTitle, stopIntent) + .addAction( + R.drawable.ic_stop, + if (trustedWifiWaiting && actionName == "STOP") "Отменить ожидание" else actionTitle, + stopIntent + ) .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_DEFAULT) // ВАЖНО: Делаем уведомление публичным (видимым на локскрине) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) @@ -724,10 +1175,26 @@ class TunnelService : Service() { runCatching { unregisterReceiver(it) } } screenStateReceiver = null + trustedWifiStateReceiver?.let { + runCatching { unregisterReceiver(it) } + } + trustedWifiStateReceiver = null networkCallback?.let { connectivityManager?.unregisterNetworkCallback(it) } - stopTunnel(TunnelStopReason.ServiceDestroyed) + trustedWifiNetworkCallback?.let { + runCatching { connectivityManager?.unregisterNetworkCallback(it) } + } + trustedWifiSettingsJob?.cancel() + cancelTrustedWifiEvaluations() + trustedWifiResumeRetryJob?.cancel() + if (trustedWifiWaiting || trustedWifiResumeInProgress) { + releaseWakeLock() + releaseWifiLock() + TrustedWifiManager.setStatus("Служба ожидания будет восстановлена Android") + } else { + stopTunnel(TunnelStopReason.ServiceDestroyed) + } } override fun onBind(intent: Intent?): IBinder? = null diff --git a/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt b/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt index 0e3e2b5..1489a35 100644 --- a/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt +++ b/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt @@ -40,6 +40,7 @@ class VpnCompactWidgetProvider : AppWidgetProvider() { appWidgetIds: IntArray ) { val running = TunnelManager.running.value + val waiting = TrustedWifiManager.state.value.waiting scope.launch { val settingsStore = SettingsStore(context) val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2) @@ -51,9 +52,12 @@ class VpnCompactWidgetProvider : AppWidgetProvider() { views.setInt( R.id.compact_widget_toggle, "setBackgroundResource", - if (running) R.drawable.bg_widget_button_active else R.drawable.bg_widget_button_inactive + if (running && !waiting) R.drawable.bg_widget_button_active else R.drawable.bg_widget_button_inactive + ) + views.setTextViewText( + R.id.compact_widget_profile, + if (waiting) "Ожидание" else profileName ) - views.setTextViewText(R.id.compact_widget_profile, profileName) val toggleIntent = Intent(context, VpnWidgetProvider::class.java).apply { action = VpnWidgetProvider.ACTION_WIDGET_TOGGLE diff --git a/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt b/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt index 6934569..8cf0577 100644 --- a/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt +++ b/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt @@ -42,6 +42,7 @@ class VpnWidgetProvider : AppWidgetProvider() { override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { val running = TunnelManager.running.value + val trustedWifi = TrustedWifiManager.state.value scope.launch { val settingsStore = SettingsStore(context) val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2) @@ -52,6 +53,7 @@ class VpnWidgetProvider : AppWidgetProvider() { appWidgetManager = appWidgetManager, appWidgetId = appWidgetId, running = running, + trustedWifi = trustedWifi, activeProfile = activeProfile, profileNames = profileNames ) @@ -63,7 +65,7 @@ class VpnWidgetProvider : AppWidgetProvider() { super.onReceive(context, intent) if (intent.action == ACTION_WIDGET_TOGGLE) { runCatching { - if (TunnelManager.running.value) { + if (TunnelManager.running.value || TrustedWifiManager.state.value.waiting) { // Останавливаем туннель val stopIntent = Intent(context, TunnelService::class.java).apply { action = "STOP" } context.startService(stopIntent) @@ -108,13 +110,19 @@ class VpnWidgetProvider : AppWidgetProvider() { appWidgetManager: AppWidgetManager, appWidgetId: Int, running: Boolean, + trustedWifi: TrustedWifiRuntimeState, activeProfile: Int, profileNames: List ) { val views = RemoteViews(context.packageName, R.layout.vpn_widget) // Обновляем текст статуса и неоновую иконку кнопки - if (running) { + if (trustedWifi.waiting) { + val networkName = trustedWifi.ssid.ifBlank { "Wi-Fi" } + views.setTextViewText(R.id.widget_status, "Ожидание: $networkName") + views.setTextColor(R.id.widget_status, 0xFFFFB74D.toInt()) + views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_inactive) + } else if (running) { val profileName = vpnProfileDisplayName(activeProfile, profileNames) val status = "Подключено к $profileName" views.setTextViewText(R.id.widget_status, status) diff --git a/app/src/main/java/com/wdtt/plus/WdttApplication.kt b/app/src/main/java/com/wdtt/plus/WdttApplication.kt index c60c93b..a0e50ea 100644 --- a/app/src/main/java/com/wdtt/plus/WdttApplication.kt +++ b/app/src/main/java/com/wdtt/plus/WdttApplication.kt @@ -43,9 +43,10 @@ class WdttApplication : Application() { try { combine( TunnelManager.running, + TrustedWifiManager.state, settingsStore.activeProfile, settingsStore.profileNames - ) { _, _, _ -> Unit }.collect { + ) { _, _, _, _ -> Unit }.collect { VpnWidgetProvider.updateAllWidgets(this@WdttApplication) } } catch (e: Exception) { diff --git a/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt b/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt index 79773b6..88d3507 100644 --- a/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt @@ -191,7 +191,7 @@ fun DeviceCompatibilityDialog( ) { Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) Spacer(modifier = Modifier.size(8.dp)) - Text("Скопировать") + Text("Скопировать отчёт") } } Button( diff --git a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt index e548f16..4eb27ab 100644 --- a/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt +++ b/app/src/main/java/com/wdtt/plus/ui/FloatingToolbar.kt @@ -79,6 +79,11 @@ fun FloatingToolbar( onTransferRequested: () -> Unit, modifier: Modifier = Modifier ) { + val context = LocalContext.current + val settingsStore = remember { SettingsStore(context) } + val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false) + val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList()) + val trustedWifiRuntime by com.wdtt.plus.TrustedWifiManager.state.collectAsStateWithLifecycle() val configuration = LocalConfiguration.current val density = LocalDensity.current val screenHeightPx = remember(configuration.screenHeightDp, density) { @@ -98,6 +103,7 @@ fun FloatingToolbar( var panelHeightPx by remember { mutableFloatStateOf(0f) } var renamingProfile by remember { mutableStateOf(null) } var profileNameInput by rememberSaveable { mutableStateOf("") } + var showTrustedWifiSettings by rememberSaveable { mutableStateOf(false) } val tabWidthDp = 42.dp val tabHeightDp = 52.dp @@ -282,6 +288,45 @@ fun FloatingToolbar( color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) ) + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { showTrustedWifiSettings = true } + .padding(horizontal = 4.dp, vertical = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) { + Text( + "Доверенные сети Wi‑Fi", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + when { + trustedWifiRuntime.waiting -> "VPN ожидает выхода из сети" + !trustedWifiEnabled -> "Выключено" + trustedWifiSsids.isEmpty() -> "Сети не добавлены" + else -> "Добавлено: ${trustedWifiSsids.size}" + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 15.sp + ) + } + Switch( + checked = trustedWifiEnabled, + onCheckedChange = null, + modifier = Modifier.scale(0.85f) + ) + } + + HorizontalDivider( + modifier = Modifier.padding(vertical = 4.dp), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) + ) + Row( modifier = Modifier.fillMaxWidth().padding(horizontal = 4.dp, vertical = 4.dp), horizontalArrangement = Arrangement.SpaceBetween, @@ -467,8 +512,6 @@ fun FloatingToolbar( val scope = rememberCoroutineScope() val clientIdsList = activeClientIds.split(",").map { it.trim() }.filter { it.isNotEmpty() } - val context = LocalContext.current - val settingsStore = remember { SettingsStore(context) } val checkResultsJson by settingsStore.clientIdCheckResults.collectAsStateWithLifecycle(initialValue = "{}") var checkResults by remember(checkResultsJson) { @@ -588,6 +631,13 @@ fun FloatingToolbar( } ) } + + if (showTrustedWifiSettings) { + TrustedWifiSettingsDialog( + settingsStore = settingsStore, + onDismiss = { showTrustedWifiSettings = false } + ) + } } } diff --git a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt index 1101b9a..5689247 100644 --- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt @@ -58,7 +58,6 @@ import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material.icons.automirrored.filled.HelpOutline import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Code -import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.KeyboardArrowDown @@ -107,6 +106,8 @@ import com.wdtt.plus.DeviceCompatibility import com.wdtt.plus.R import com.wdtt.plus.SettingsStore import com.wdtt.plus.TunnelManager +import com.wdtt.plus.TrustedWifiManager +import com.wdtt.plus.trustedWifiAccessProblem import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE import com.wdtt.plus.WDTTColors @@ -118,7 +119,6 @@ import com.wdtt.plus.downloadUpdateApk import com.wdtt.plus.fetchLatestReleaseInfo import com.wdtt.plus.installUpdateApk import com.wdtt.plus.isNewerVersion -import com.wdtt.plus.label import com.wdtt.plus.resolveAppUpdateCandidate import com.wdtt.plus.selectUpdateApkAsset import com.wdtt.plus.deviceCheckActionIntent @@ -314,6 +314,9 @@ fun InfoTab( latestRelease = latestRelease ) val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull() + val diagnosticsSummary = withContext(Dispatchers.Default) { + buildSupportReportSummary(context.applicationContext, settingsStore) + } val report = withContext(Dispatchers.Default) { DeviceCompatibility.check( context = context.applicationContext, @@ -322,6 +325,7 @@ fun InfoTab( ) } return report.copy( + summaryLines = diagnosticsSummary, items = listOf(versionItem) + report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE } ) @@ -356,7 +360,7 @@ fun InfoTab( ExpandableSectionCard( title = "Действия", - itemCount = "5 пунктов", + itemCount = "4 пункта", expanded = actionsExpanded, modifier = Modifier.onGloballyPositioned { actionsSectionY = it.positionInParent().y }, onToggle = { @@ -392,35 +396,12 @@ fun InfoTab( } ) - WideActionTile( - title = "Собрать отчёт", - subtitle = "Android, ABI, память, сеть и компоненты", - onClick = { - scope.launch { - val report = withContext(Dispatchers.Default) { - buildSupportReport(context.applicationContext, settingsStore) - } - val clipboard = context.getSystemService(ClipboardManager::class.java) - clipboard?.setPrimaryClip(ClipData.newPlainText("WDTT Report", report)) - 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 = if (isCheckingDevice) { - "Проверяем версию, Android, ABI и системные условия..." + "Проверяем версию, Android, ABI, сеть и системные условия..." } else { - "Версия, совместимость, ABI, native, WebView и настройки" + "Проверка совместимости и полный отчёт для диагностики" }, onClick = { if (isCheckingDevice) return@WideActionTile @@ -695,8 +676,8 @@ fun InfoTab( DeviceCompatibilityDialog( report = report, title = "Проверка устройства", - subtitle = "Расширенная проверка не запускает VPN, но показывает совместимость устройства, настройки Android и текущее состояние туннеля.", - note = "Здесь проверяется всё, что можно проверить без тестового подключения: VPN-разрешение, активен ли туннель сейчас, сеть, WebView, батарея, установка APK и базовая совместимость устройства.", + subtitle = "Расширенная проверка не запускает VPN, но показывает совместимость устройства, настройки Android и статус подключения.", + note = "Кнопка «Скопировать отчёт» добавит в буфер версию приложения, Android, ABI, память, сеть, WebView, native-клиент и текущие настройки без секретных значений.", onDismiss = { deviceCheckReport = null }, onCopy = { scope.launch { @@ -708,7 +689,7 @@ fun InfoTab( deviceCheckReport = freshReport val clipboard = context.getSystemService(ClipboardManager::class.java) clipboard?.setPrimaryClip(ClipData.newPlainText("WDTT Device Check", freshReport.toPlainText())) - Toast.makeText(context, "Проверка устройства скопирована", Toast.LENGTH_SHORT).show() + Toast.makeText(context, "Отчёт проверки скопирован", Toast.LENGTH_SHORT).show() } }, onAction = { action -> openDeviceCheckAction(context, action) } @@ -1290,7 +1271,7 @@ private fun diagnosticText(block: () -> Any?): String = private fun formatMiB(bytes: Long): String = "${bytes.coerceAtLeast(0L) / (1024L * 1024L)} МБ" -private suspend fun buildSupportReport(context: Context, settingsStore: SettingsStore): String { +private suspend fun buildSupportReportSummary(context: Context, settingsStore: SettingsStore): List { val androidVersion = Build.VERSION.RELEASE ?: "?" val sdkInt = Build.VERSION.SDK_INT val primaryAbi = Build.SUPPORTED_ABIS.firstOrNull().orEmpty().ifBlank { "unknown" } @@ -1440,11 +1421,6 @@ private suspend fun buildSupportReport(context: Context, settingsStore: Settings val activeProfile = runCatching { settingsStore.activeProfile.first() + 1 }.getOrNull() val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull() - val deviceCompatibility = DeviceCompatibility.check( - context = context, - includeRuntimeChecks = true, - workersPerHash = workers - ) val vkHashes = runCatching { settingsStore.vkHashes.first() }.getOrDefault("") val hashCount = vkHashes .split(Regex("[,\\s\\n]+")) @@ -1459,10 +1435,21 @@ private suspend fun buildSupportReport(context: Context, settingsStore: Settings val themeMode = runCatching { settingsStore.themeMode.first() }.getOrNull() val dynamicColor = runCatching { settingsStore.isDynamicColor.first() }.getOrNull() val loggingEnabled = runCatching { settingsStore.loggingEnabled.first() }.getOrNull() + val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrNull() + val trustedWifiCount = runCatching { settingsStore.trustedWifiSsids.first().size }.getOrNull() + val trustedWifiAccess = if (trustedWifiEnabled == true) { + when (trustedWifiAccessProblem(context)) { + com.wdtt.plus.TrustedWifiAccessProblem.ForegroundPermission -> "нет доступа к имени Wi-Fi" + com.wdtt.plus.TrustedWifiAccessProblem.BackgroundPermission -> "нет фонового доступа" + com.wdtt.plus.TrustedWifiAccessProblem.LocationDisabled -> "определение местоположения выключено" + null -> "доступ выдан" + } + } else { + "не требуется" + } val tunnelIssue = TunnelManager.connectionIssue.value?.title.orEmpty().ifBlank { "нет" } return buildString { - appendLine("Отчёт создан: ${diagnosticText { dateFormat.format(Date()) }}") appendLine("Версия приложения: ${BuildConfig.VERSION_NAME}") appendLine("Дата релиза: ${BuildConfig.MOD_RELEASE_DATE}") appendLine("Версия пакета: code ${packageInfo?.longVersionCode ?: "?"}") @@ -1500,13 +1487,10 @@ private suspend fun buildSupportReport(context: Context, settingsStore: Settings appendLine("Разрешение уведомлений: $notificationPermission") appendLine("Установка обновлений APK: $updateInstallPermission") appendLine("VPN-разрешение: $vpnPermission") - appendLine("Совместимость устройства: ${deviceCompatibility.overallStatus}") - deviceCompatibility.items.forEach { item -> - appendLine(" - [${item.severity.label()}] ${item.title}: ${item.status}") - if (item.recommendation.isNotBlank()) { - appendLine(" Рекомендация: ${item.recommendation}") - } - } + appendLine( + "Доверенные Wi-Fi: включено=${trustedWifiEnabled ?: "недоступно"}, " + + "сетей=${trustedWifiCount ?: "недоступно"}, ожидание=${TrustedWifiManager.state.value.waiting}, доступ=$trustedWifiAccess" + ) appendLine("Локаль: ${diagnosticText { Locale.getDefault().toLanguageTag() }}") appendLine("Часовой пояс: ${diagnosticText { TimeZone.getDefault().id }}") appendLine("Туннель: запущен=${TunnelManager.running.value}, активных=${TunnelManager.activeWorkers.value}") @@ -1521,5 +1505,5 @@ private suspend fun buildSupportReport(context: Context, settingsStore: Settings appendLine("Роль интерфейса: ${interfaceRole?.ifBlank { "не выбрана" } ?: "недоступно"}") appendLine("Тема: ${themeMode ?: "недоступно"}, Dynamic Colors=${dynamicColor ?: "недоступно"}") appendLine("Логирование: ${loggingEnabled ?: "недоступно"}") - }.trim() + }.trim().lines() } diff --git a/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt b/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt index 313a0f9..e6b10ed 100644 --- a/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt @@ -147,7 +147,8 @@ fun LogLine(entry: LogEntry, sessionActive: Boolean) { entry.priority == 3 -> if (isDark) WDTTColors.terminalBlue else MaterialTheme.colorScheme.primary else -> if (isDark) WDTTColors.terminalText else MaterialTheme.colorScheme.onSurface } - val isStoppedStats = entry.key == "stats" && entry.message.contains("VPN отключён") + val isStoppedStats = entry.key == "stats" && + (entry.message.contains("VPN отключён") || entry.message.contains("VPN в ожидании")) val color = when { sessionActive -> activeColor isStoppedStats -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.9f) diff --git a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt index c5a2bb8..c372343 100644 --- a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt @@ -54,6 +54,7 @@ import com.wdtt.plus.ManlCaptchaWebViewManager import com.wdtt.plus.SettingsStore import com.wdtt.plus.TunnelManager import com.wdtt.plus.TunnelService +import com.wdtt.plus.TrustedWifiManager import com.wdtt.plus.VkJoinLink import com.wdtt.plus.WDTTColors import com.wdtt.plus.WdttDeepLink @@ -63,6 +64,7 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext import kotlinx.coroutines.CancellationException import android.content.Intent @@ -127,13 +129,17 @@ fun SettingsTabContent( val profileNames by settingsStore.profileNames.collectAsStateWithLifecycle(initialValue = emptyList()) val wdttLinkMode by settingsStore.wdttLinkMode.collectAsStateWithLifecycle(initialValue = false) val wdttLink by settingsStore.wdttLink.collectAsStateWithLifecycle(initialValue = "") - val savedVkHashes by settingsStore.vkHashes.collectAsStateWithLifecycle(initialValue = "") + val savedVkHashesState by remember(settingsStore) { + settingsStore.vkHashes.map { hashes -> hashes } + }.collectAsStateWithLifecycle(initialValue = null) val activeFingerprint by settingsStore.selectedFingerprint.collectAsStateWithLifecycle(initialValue = "firefox") val activeClientIds by settingsStore.activeClientIds.collectAsStateWithLifecycle(initialValue = "6287487,8202606") val vkCallsPreflight by settingsStore.vkCallsPreflight.collectAsStateWithLifecycle(initialValue = true) val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle() + val trustedWifiState by TrustedWifiManager.state.collectAsStateWithLifecycle() + val trustedWifiWaiting = trustedWifiState.waiting val connectionIssue by TunnelManager.connectionIssue.collectAsStateWithLifecycle() val cooldownActive by TunnelManager.cooldownActive.collectAsStateWithLifecycle() @@ -160,6 +166,7 @@ fun SettingsTabContent( var showAutoCaptchaHelp by rememberSaveable { mutableStateOf(false) } var serverDtlsPortInput by rememberSaveable { mutableStateOf("56000") } var serverWgPortInput by rememberSaveable { mutableStateOf("56001") } + var initialized by remember { mutableStateOf(false) } val allHashes = remember(vkHash1, vkHash2, vkHash3, vkHash4) { listOf(vkHash1, vkHash2, vkHash3, vkHash4).map { stripVkUrlStatic(it) } @@ -176,16 +183,10 @@ fun SettingsTabContent( val hashSlotsForStorage = remember(vkHash1, vkHash2, vkHash3, vkHash4) { encodeVkHashSlots(vkHash1, vkHash2, vkHash3, vkHash4) } - val dynamicMaxWorkers = remember(filledHashCount) { (filledHashCount.coerceAtLeast(1) * 27).toFloat() } + val dynamicMaxWorkers = remember(filledHashCount) { maxWorkersForHashCount(filledHashCount) } var portInput by rememberSaveable { mutableStateOf("9000") } var sniInput by rememberSaveable { mutableStateOf("") } - LaunchedEffect(dynamicMaxWorkers) { - if (workersInput > dynamicMaxWorkers) { - workersInput = dynamicMaxWorkers - } - } - val currentWorkers = workersInput.coerceIn(WORKERS_PER_GROUP.toFloat(), dynamicMaxWorkers) val hashErrors = remember(vkHash1, vkHash2, vkHash3, vkHash4) { @@ -200,26 +201,11 @@ fun SettingsTabContent( val hasInputHashErrors = remember(vkHash1, vkHash2, vkHash3, vkHash4) { hashErrors.isNotEmpty() } var showSecretsDialog by rememberSaveable { mutableStateOf(false) } - var initialized by remember { mutableStateOf(false) } - - fun parseHashes(raw: String) { - val parts = parseVkHashSlots(raw) - vkHash1 = parts.getOrElse(0) { "" } - vkHash2 = parts.getOrElse(1) { "" } - vkHash3 = parts.getOrElse(2) { "" } - vkHash4 = parts.getOrElse(3) { "" } - } - - fun normalizeHashes(vararg hashes: String): String { - return hashes - .map { stripVkUrlStatic(it) } - .filter { it.isNotBlank() && it.length >= 16 } - .distinct() - .joinToString(",") - } LaunchedEffect(activeProfile) { + initialized = false val peer = settingsStore.peer.first() + val hashes = settingsStore.vkHashes.first() val workers = settingsStore.workersPerHash.first() val port = settingsStore.listenPort.first() val manualPorts = settingsStore.manualPortsEnabled.first() @@ -228,10 +214,17 @@ fun SettingsTabContent( val sni = settingsStore.sni.first() val captchaMode = settingsStore.captchaMode.first() val captchaMethod = settingsStore.captchaSolveMethod.first() + val hashSlots = parseVkHashSlots(hashes) peerInput = peer - parseHashes(savedVkHashes) - workersInput = roundToGroup(workers.toFloat(), (listOf(vkHash1, vkHash2, vkHash3, vkHash4).count { it.isNotBlank() }.coerceAtLeast(1) * 27).toFloat()) + vkHash1 = hashSlots.getOrElse(0) { "" } + vkHash2 = hashSlots.getOrElse(1) { "" } + vkHash3 = hashSlots.getOrElse(2) { "" } + vkHash4 = hashSlots.getOrElse(3) { "" } + workersInput = roundToGroup( + workers.toFloat(), + maxWorkersForHashSlots(hashSlots) + ) portInput = port.toString() manualPortsEnabled = manualPorts serverDtlsPortInput = serverDtlsPort.toString() @@ -245,9 +238,20 @@ fun SettingsTabContent( initialized = true } - LaunchedEffect(savedVkHashes) { - if (initialized && savedVkHashes != hashSlotsForStorage) { - parseHashes(savedVkHashes) + LaunchedEffect(savedVkHashesState) { + val savedVkHashes = savedVkHashesState ?: return@LaunchedEffect + if (initialized && normalizeVkHashSlots(savedVkHashes) != hashSlotsForStorage) { + val hashSlots = parseVkHashSlots(savedVkHashes) + vkHash1 = hashSlots.getOrElse(0) { "" } + vkHash2 = hashSlots.getOrElse(1) { "" } + vkHash3 = hashSlots.getOrElse(2) { "" } + vkHash4 = hashSlots.getOrElse(3) { "" } + val maxWorkers = maxWorkersForHashSlots(hashSlots) + if (workersInput > maxWorkers) { + val clamped = roundToGroup(workersInput, maxWorkers) + workersInput = clamped + settingsStore.saveWorkersPerHash(clamped.toInt()) + } } } @@ -276,18 +280,28 @@ fun SettingsTabContent( var saveJob by remember { mutableStateOf(null) } - fun saveTunnelSettingsNow(hashes: String = hashSlotsForStorage, onSaved: (() -> Unit)? = null) { + fun saveTunnelSettingsNow( + hashes: String = hashSlotsForStorage, + workers: Float = workersInput, + onSaved: (() -> Unit)? = null + ) { saveJob?.cancel() scope.launch { val savedLocalPort = if (manualPortsEnabled) portInput.toIntOrNull()?.coerceIn(1, 65535) ?: 9000 else 9000 settingsStore.save( peerInput, hashes, "", - workersInput.toInt(), "udp", savedLocalPort, sniInput, false + workers.toInt(), "udp", savedLocalPort, sniInput, false ) onSaved?.invoke() } } + fun saveWorkersNow(workers: Float) { + scope.launch { + settingsStore.saveWorkersPerHash(workers.toInt()) + } + } + fun scheduleSave() { saveJob?.cancel() saveJob = scope.launch { @@ -425,7 +439,16 @@ fun SettingsTabContent( vkHash2 = cleaned2 vkHash3 = cleaned3 vkHash4 = cleaned4 - saveTunnelSettingsNow(encodeVkHashSlots(cleaned1, cleaned2, cleaned3, cleaned4)) { + val maxWorkers = maxWorkersForHashSlots(listOf(cleaned1, cleaned2, cleaned3, cleaned4)) + val savedWorkers = if (workersInput > maxWorkers) { + roundToGroup(workersInput, maxWorkers).also { workersInput = it } + } else { + workersInput + } + saveTunnelSettingsNow( + hashes = encodeVkHashSlots(cleaned1, cleaned2, cleaned3, cleaned4), + workers = savedWorkers + ) { showHashesDialog = false } }, @@ -554,8 +577,9 @@ fun SettingsTabContent( CompactSteppedSlider( value = currentWorkersVal, onValueChange = { raw -> - workersInput = roundToGroup(raw, maxWorkers) - scheduleSave() + val rounded = roundToGroup(raw, maxWorkers) + workersInput = rounded + saveWorkersNow(rounded) }, valueRange = minWorkers..maxWorkers, stepSize = WORKERS_PER_GROUP.toFloat(), @@ -751,14 +775,14 @@ fun SettingsTabContent( } val buttonColor by animateColorAsState( - targetValue = if (tunnelRunning) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, + targetValue = if (tunnelRunning || trustedWifiWaiting) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary, animationSpec = tween(400), label = "btn_color" ) Button( onClick = { - if (tunnelRunning) { + if (tunnelRunning || trustedWifiWaiting) { context.startService( Intent(context, TunnelService::class.java).apply { action = "STOP" } ) @@ -767,7 +791,7 @@ fun SettingsTabContent( requestVpnAndStart() } }, - enabled = (isValid && !cooldownActive) || tunnelRunning, + enabled = (isValid && !cooldownActive) || tunnelRunning || trustedWifiWaiting, modifier = Modifier .weight(1f) .fillMaxHeight() @@ -780,7 +804,7 @@ fun SettingsTabContent( ) ) { Icon( - imageVector = if (tunnelRunning) Icons.Default.Stop else Icons.Default.PowerSettingsNew, + imageVector = if (tunnelRunning || trustedWifiWaiting) Icons.Default.Stop else Icons.Default.PowerSettingsNew, contentDescription = null, modifier = Modifier.size(20.dp) ) @@ -788,6 +812,7 @@ fun SettingsTabContent( FlexibleButtonText( text = when { tunnelRunning -> "Остановить" + trustedWifiWaiting -> "Отменить ожидание" cooldownActive -> "Подождите..." else -> "Подключить" }, @@ -796,6 +821,34 @@ fun SettingsTabContent( } } + if (trustedWifiWaiting) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.72f), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.secondary.copy(alpha = 0.35f)) + ) { + Column( + modifier = Modifier.fillMaxWidth().padding(14.dp), + verticalArrangement = Arrangement.spacedBy(5.dp) + ) { + Text( + "Ожидание доверенной сети", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSecondaryContainer + ) + Text( + trustedWifiState.status.ifBlank { + "VPN выключен в сети «${trustedWifiState.ssid}» и восстановится после выхода из неё." + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSecondaryContainer + ) + } + } + } + connectionIssue?.let { issue -> Surface( modifier = Modifier.fillMaxWidth(), @@ -1238,6 +1291,19 @@ private fun roundToGroup(value: Float, maxW: Float = 96f): Float { return rounded.coerceIn(WORKERS_PER_GROUP.toFloat(), maxW) } +private fun maxWorkersForHashCount(hashCount: Int): Float { + return (hashCount.coerceAtLeast(1) * 27).toFloat() +} + +private fun maxWorkersForHashSlots(hashSlots: List): Float { + return maxWorkersForHashCount( + hashSlots.count { slot -> + val hash = stripVkUrlStatic(slot) + hash.isNotBlank() && hash.length >= 16 + } + ) +} + /** Извлекает хеш из VK ссылки */ private fun stripVkUrlStatic(input: String): String { return VkJoinLink.extractHash(input) @@ -1263,6 +1329,10 @@ private fun encodeVkHashSlots(vararg hashes: String): String { return slots.joinToString(",") } +private fun normalizeVkHashSlots(raw: String): String { + return encodeVkHashSlots(*parseVkHashSlots(raw).toTypedArray()) +} + private fun copyVkHashesToClipboard(context: android.content.Context, label: String, value: String) { if (value.isBlank()) return val clipboard = context.getSystemService(android.content.Context.CLIPBOARD_SERVICE) as ClipboardManager diff --git a/app/src/main/java/com/wdtt/plus/ui/TrustedWifiSettingsDialog.kt b/app/src/main/java/com/wdtt/plus/ui/TrustedWifiSettingsDialog.kt new file mode 100644 index 0000000..07e2ee2 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/TrustedWifiSettingsDialog.kt @@ -0,0 +1,522 @@ +package com.wdtt.plus.ui + +import android.Manifest +import android.content.Context +import android.content.Intent +import android.os.Build +import android.provider.Settings +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +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.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.DeleteOutline +import androidx.compose.material.icons.filled.LocationOn +import androidx.compose.material.icons.filled.Wifi +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.core.net.toUri +import com.wdtt.plus.ConnectedWifiState +import com.wdtt.plus.SettingsStore +import com.wdtt.plus.TrustedWifiAccessProblem +import com.wdtt.plus.TrustedWifiManager +import com.wdtt.plus.TunnelManager +import com.wdtt.plus.TunnelService +import com.wdtt.plus.readConnectedWifiState +import com.wdtt.plus.isWdttAlwaysOnVpn +import com.wdtt.plus.sanitizeTrustedWifiSsid +import com.wdtt.plus.trustedWifiAccessProblem +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +private enum class TrustedWifiUiAction { + Enable, + AddCurrent +} + +private const val BACKGROUND_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION" + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun TrustedWifiSettingsDialog( + settingsStore: SettingsStore, + onDismiss: () -> Unit +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val configuration = LocalConfiguration.current + val enabledState by remember(settingsStore) { + settingsStore.trustedWifiEnabled.map { value: Boolean -> value as Boolean? } + }.collectAsStateWithLifecycle(initialValue = null) + val trustedSsidsState by remember(settingsStore) { + settingsStore.trustedWifiSsids.map { value: List -> value as List? } + }.collectAsStateWithLifecycle(initialValue = null) + val enabled = enabledState == true + val trustedSsids = trustedSsidsState.orEmpty() + val settingsReady = enabledState != null && trustedSsidsState != null + val runtimeState by TrustedWifiManager.state.collectAsStateWithLifecycle() + var currentWifi by remember { mutableStateOf(ConnectedWifiState(connected = false)) } + var pendingAction by remember { mutableStateOf(null) } + var showForegroundExplanation by rememberSaveable { mutableStateOf(false) } + var showBackgroundExplanation by rememberSaveable { mutableStateOf(false) } + var showLocationExplanation by rememberSaveable { mutableStateOf(false) } + var showManualInput by rememberSaveable { mutableStateOf(false) } + var manualInput by rememberSaveable { mutableStateOf("") } + + fun recheckService() { + if (!TunnelManager.running.value && !TrustedWifiManager.state.value.waiting) return + runCatching { + context.startService(Intent(context, TunnelService::class.java).apply { + action = "TRUSTED_WIFI_RECHECK" + }) + } + } + + val performAction: (TrustedWifiUiAction) -> Unit = { action -> + scope.launch { + when (action) { + TrustedWifiUiAction.Enable -> settingsStore.saveTrustedWifiEnabled(true) + TrustedWifiUiAction.AddCurrent -> { + val wifi = withContext(Dispatchers.Default) { readConnectedWifiState(context) } + currentWifi = wifi + if (wifi.ssidAvailable) { + val added = settingsStore.addTrustedWifiSsid(wifi.ssid) + val message = if (added) { + "Сеть «${wifi.ssid}» добавлена" + } else { + "Сеть «${wifi.ssid}» уже есть в списке" + } + Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + } else { + Toast.makeText(context, "Не удалось определить имя текущей Wi-Fi сети", Toast.LENGTH_LONG).show() + } + } + } + pendingAction = null + recheckService() + } + } + + fun continuePendingAction() { + val action = pendingAction ?: return + when (trustedWifiAccessProblem(context)) { + TrustedWifiAccessProblem.ForegroundPermission -> showForegroundExplanation = true + TrustedWifiAccessProblem.BackgroundPermission -> showBackgroundExplanation = true + TrustedWifiAccessProblem.LocationDisabled -> showLocationExplanation = true + null -> performAction(action) + } + } + + val foregroundPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestMultiplePermissions() + ) { grants -> + if (grants[Manifest.permission.ACCESS_FINE_LOCATION] == true) continuePendingAction() + else { + pendingAction = null + Toast.makeText(context, "Без доступа к имени Wi-Fi функция не включена", Toast.LENGTH_LONG).show() + } + } + val backgroundPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission() + ) { granted -> + if (granted) continuePendingAction() + else { + pendingAction = null + Toast.makeText(context, "Для работы при закрытом приложении нужен постоянный доступ", Toast.LENGTH_LONG).show() + } + } + val appSettingsLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { + continuePendingAction() + } + val locationSettingsLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { + continuePendingAction() + } + + fun requestAction(action: TrustedWifiUiAction) { + pendingAction = action + continuePendingAction() + } + + LaunchedEffect(Unit) { + currentWifi = withContext(Dispatchers.Default) { readConnectedWifiState(context) } + } + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + Box( + modifier = Modifier.fillMaxSize(), + contentAlignment = Alignment.Center + ) { + Surface( + modifier = Modifier + .fillMaxWidth(0.92f) + .fillMaxHeight(0.9f) + .heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)), + shape = RoundedCornerShape(30.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 8.dp, + shadowElevation = 8.dp + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .padding(18.dp), + verticalArrangement = Arrangement.spacedBy(14.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + Surface( + shape = RoundedCornerShape(16.dp), + color = MaterialTheme.colorScheme.primaryContainer + ) { + Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) { + Icon(Icons.Default.Wifi, contentDescription = null, modifier = Modifier.size(25.dp)) + } + } + Column(modifier = Modifier.weight(1f)) { + Text( + "Доверенные сети Wi-Fi", + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold + ) + Text( + "Общая настройка для всех VPN-профилей", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + + if (!settingsReady) { + Box( + modifier = Modifier + .fillMaxWidth() + .height(180.dp), + contentAlignment = Alignment.Center + ) { + CircularProgressIndicator() + } + } else { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(18.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f) + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp) + ) { + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text("Автоматическое ожидание", fontWeight = FontWeight.SemiBold) + Text( + "VPN выключается в выбранных сетях и восстанавливается после выхода из них.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + Switch( + checked = enabled, + onCheckedChange = { checked -> + if (checked) requestAction(TrustedWifiUiAction.Enable) + else scope.launch { + settingsStore.saveTrustedWifiEnabled(false) + recheckService() + } + } + ) + } + } + + val currentStatus = when { + runtimeState.waiting -> "Ожидание в сети «${runtimeState.ssid.ifBlank { "Wi-Fi" }}»" + currentWifi.ssidAvailable && currentWifi.ssid in trustedSsids -> "Сейчас подключена доверенная сеть «${currentWifi.ssid}»" + currentWifi.ssidAvailable -> "Текущая сеть: ${currentWifi.ssid}" + !currentWifi.connected -> "Wi-Fi сейчас не подключён" + else -> "Имя текущей Wi-Fi сети недоступно" + } + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + color = if (runtimeState.waiting) { + MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.7f) + } else { + MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f) + }, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.2f)) + ) { + Text( + currentStatus, + modifier = Modifier.padding(14.dp), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium + ) + } + + Text( + "Сети без VPN", + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.Bold + ) + if (trustedSsids.isEmpty()) { + Text( + "Список пуст. Добавьте текущую сеть или введите её точное имя вручную.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } else { + trustedSsids.forEach { ssid -> + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(14.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.42f) + ) { + Row( + modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 4.dp, top = 5.dp, bottom = 5.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon(Icons.Default.Wifi, contentDescription = null, modifier = Modifier.size(19.dp)) + Text(ssid, modifier = Modifier.weight(1f).padding(horizontal = 10.dp)) + IconButton(onClick = { + scope.launch { + settingsStore.removeTrustedWifiSsid(ssid) + recheckService() + } + }) { + Icon(Icons.Default.DeleteOutline, contentDescription = "Удалить сеть") + } + } + } + } + } + + Button( + onClick = { requestAction(TrustedWifiUiAction.AddCurrent) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), + shape = RoundedCornerShape(16.dp) + ) { + Icon(Icons.Default.Add, contentDescription = null) + Text(" Добавить текущую сеть") + } + OutlinedButton( + onClick = { showManualInput = true }, + modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), + shape = RoundedCornerShape(16.dp) + ) { + Text("Добавить вручную") + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.55f)) + Text( + "Во время ожидания интернет работает напрямую, а WDTT Plus сохраняет тихое уведомление, чтобы заметить выход из Wi-Fi. Ручное отключение отменяет автоматическое восстановление.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = MaterialTheme.typography.bodyMedium.lineHeight + ) + Text( + "Android считает имя Wi-Fi данными о местоположении. WDTT Plus не получает координаты и использует разрешение только для точного имени подключённой сети.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + if (isWdttAlwaysOnVpn(context)) { + Text( + "Системный режим «Всегда включённый VPN» сейчас активен. Android не позволит использовать прямой интернет в доверенной сети, пока этот режим не будет отключён.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } + } + } + } + } + } + + if (showManualInput) { + AlertDialog( + onDismissRequest = { showManualInput = false }, + title = { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text("Добавить сеть") + IconButton(onClick = { showManualInput = false }) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + }, + text = { + OutlinedTextField( + value = manualInput, + onValueChange = { manualInput = sanitizeTrustedWifiSsid(it) }, + label = { Text("Точное имя сети (SSID)") }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + }, + confirmButton = { + Button( + enabled = sanitizeTrustedWifiSsid(manualInput).isNotBlank(), + onClick = { + scope.launch { + val clean = sanitizeTrustedWifiSsid(manualInput) + val added = settingsStore.addTrustedWifiSsid(clean) + if (added) { + Toast.makeText(context, "Сеть «$clean» добавлена", Toast.LENGTH_SHORT).show() + manualInput = "" + showManualInput = false + recheckService() + } else { + Toast.makeText(context, "Сеть «$clean» уже есть в списке", Toast.LENGTH_SHORT).show() + } + } + } + ) { Text("Добавить") } + } + ) + } + + if (showForegroundExplanation) { + PermissionExplanationDialog( + title = "Доступ к имени Wi-Fi", + text = "Android относит имя подключённой Wi-Fi сети к данным о местоположении. WDTT Plus не читает координаты: доступ нужен только для сравнения SSID со списком доверенных сетей.", + button = "Продолжить", + onDismiss = { + showForegroundExplanation = false + pendingAction = null + }, + onConfirm = { + showForegroundExplanation = false + foregroundPermissionLauncher.launch( + arrayOf( + Manifest.permission.ACCESS_COARSE_LOCATION, + Manifest.permission.ACCESS_FINE_LOCATION + ) + ) + } + ) + } + if (showBackgroundExplanation) { + PermissionExplanationDialog( + title = "Работа при закрытом приложении", + text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + "Чтобы VPN восстановился после выхода из доверенной сети при выключенном экране, разрешите доступ к местоположению «Всегда» на системной странице приложения. Координаты не используются." + } else { + "Чтобы отслеживать выход из доверенной сети при выключенном экране, Android требует отдельное разрешение на фоновый доступ. Координаты не используются." + }, + button = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) "Открыть настройки" else "Разрешить", + onDismiss = { + showBackgroundExplanation = false + pendingAction = null + }, + onConfirm = { + showBackgroundExplanation = false + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + appSettingsLauncher.launch( + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { + data = "package:${context.packageName}".toUri() + } + ) + } else { + backgroundPermissionLauncher.launch(BACKGROUND_LOCATION_PERMISSION) + } + } + ) + } + if (showLocationExplanation) { + PermissionExplanationDialog( + title = "Включите определение местоположения", + text = "Android не раскрывает имя Wi-Fi, когда системное определение местоположения выключено. WDTT Plus нужны только названия сетей, координаты не считываются.", + button = "Открыть настройки", + onDismiss = { + showLocationExplanation = false + pendingAction = null + }, + onConfirm = { + showLocationExplanation = false + locationSettingsLauncher.launch(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) + } + ) + } +} + +@Composable +private fun PermissionExplanationDialog( + title: String, + text: String, + button: String, + onDismiss: () -> Unit, + onConfirm: () -> Unit +) { + AlertDialog( + onDismissRequest = onDismiss, + icon = { Icon(Icons.Default.LocationOn, contentDescription = null) }, + title = { Text(title, textAlign = TextAlign.Center) }, + text = { Text(text) }, + confirmButton = { Button(onClick = onConfirm) { Text(button) } }, + dismissButton = { OutlinedButton(onClick = onDismiss) { Text("Не сейчас") } } + ) +} diff --git a/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt b/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt new file mode 100644 index 0000000..0e23bec --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/TrustedWifiTest.kt @@ -0,0 +1,126 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TrustedWifiTest { + @Test + fun `running tunnel enters waiting only on exact trusted ssid`() { + assertEquals( + TrustedWifiTransition.EnterWaiting, + decideTrustedWifiTransition( + enabled = true, + tunnelRunning = true, + waiting = false, + wifi = ConnectedWifiState(connected = true, ssid = "Home Wi-Fi"), + trustedSsids = setOf("Home Wi-Fi") + ) + ) + assertEquals( + TrustedWifiTransition.None, + decideTrustedWifiTransition( + enabled = true, + tunnelRunning = true, + waiting = false, + wifi = ConnectedWifiState(connected = true, ssid = "home wi-fi"), + trustedSsids = setOf("Home Wi-Fi") + ) + ) + } + + @Test + fun `waiting resumes after wifi disconnect or untrusted wifi`() { + assertEquals( + TrustedWifiTransition.ResumeVpn, + decideTrustedWifiTransition( + enabled = true, + tunnelRunning = false, + waiting = true, + wifi = ConnectedWifiState(connected = false), + trustedSsids = setOf("Home") + ) + ) + assertEquals( + TrustedWifiTransition.ResumeVpn, + decideTrustedWifiTransition( + enabled = true, + tunnelRunning = false, + waiting = true, + wifi = ConnectedWifiState(connected = true, ssid = "Office"), + trustedSsids = setOf("Home") + ) + ) + } + + @Test + fun `unknown ssid never disables running vpn and restores waiting vpn`() { + val unknown = ConnectedWifiState( + connected = true, + accessProblem = TrustedWifiAccessProblem.ForegroundPermission + ) + assertEquals( + TrustedWifiTransition.None, + decideTrustedWifiTransition(true, true, false, unknown, setOf("Home")) + ) + assertEquals( + TrustedWifiTransition.ResumeVpn, + decideTrustedWifiTransition(true, false, true, unknown, setOf("Home")) + ) + } + + @Test + fun `ssid is unquoted and limited to wifi byte limit`() { + assertEquals("Home Wi-Fi", sanitizeTrustedWifiSsid("\"Home Wi-Fi\"")) + assertEquals(32, sanitizeTrustedWifiSsid("a".repeat(40)).toByteArray().size) + } + + @Test + fun `leaving trusted wifi never starts vpn unless waiting was armed`() { + assertEquals( + TrustedWifiTransition.None, + decideTrustedWifiTransition( + enabled = true, + tunnelRunning = false, + waiting = false, + wifi = ConnectedWifiState(connected = false), + trustedSsids = setOf("Home") + ) + ) + } + + @Test + fun `removing last trusted network resumes armed vpn`() { + assertEquals( + TrustedWifiTransition.ResumeVpn, + decideTrustedWifiTransition( + enabled = true, + tunnelRunning = false, + waiting = true, + wifi = ConnectedWifiState(connected = true, ssid = "Home"), + trustedSsids = emptySet() + ) + ) + } + + @Test + fun `service stays alive while trusted wifi vpn is resuming`() { + assertTrue( + shouldKeepTunnelServiceAlive( + tunnelRunning = false, + tunnelPaused = false, + trustedWifiWaiting = false, + trustedWifiResumeInProgress = true + ) + ) + assertFalse( + shouldKeepTunnelServiceAlive( + tunnelRunning = false, + tunnelPaused = false, + trustedWifiWaiting = false, + trustedWifiResumeInProgress = false + ) + ) + } +} diff --git a/app/src/test/java/com/wdtt/plus/TunnelStopReasonTest.kt b/app/src/test/java/com/wdtt/plus/TunnelStopReasonTest.kt index 7431ee1..273b88d 100644 --- a/app/src/test/java/com/wdtt/plus/TunnelStopReasonTest.kt +++ b/app/src/test/java/com/wdtt/plus/TunnelStopReasonTest.kt @@ -26,4 +26,18 @@ class TunnelStopReasonTest { assertEquals("VPN отключён · Причина: отключено пользователем · Активных: 0", result) assertFalse(result.contains("↓")) } + + @Test + fun trustedWifiSessionUsesWaitingText() { + val result = buildStoppedSessionStats( + "Активных: 2 | ↓1.00 МБ / ↑0.50 МБ", + TunnelStopReason.TrustedWifi + ) + + assertEquals( + "VPN в ожидании · Причина: подключена доверенная сеть Wi-Fi · " + + "Активных: 0 · ↓1.00 МБ / ↑0.50 МБ", + result + ) + } } diff --git a/go_client/dispatcher.go b/go_client/dispatcher.go index 3924e40..f86de82 100644 --- a/go_client/dispatcher.go +++ b/go_client/dispatcher.go @@ -79,7 +79,7 @@ func NewDispatcher(ctx context.Context, localConn net.PacketConn, stats *Stats) cancel: dcancel, stats: stats, } - + empty := make([]*WorkerSlot, 0) d.workers.Store(&empty) @@ -149,7 +149,7 @@ func (d *Dispatcher) readLoop() { pkt = pkt[:n] d.clientAddr.Store(&addr) - atomic.AddInt64(&d.stats.TotalBytesUp, int64(n)) + d.stats.TotalBytesUp.Add(int64(n)) workersPtr := d.workers.Load() if workersPtr == nil || len(*workersPtr) == 0 { @@ -219,7 +219,7 @@ func (d *Dispatcher) writeLoop() { return } } - atomic.AddInt64(&d.stats.TotalBytesDown, int64(len(pkt))) + d.stats.TotalBytesDown.Add(int64(len(pkt))) putPktBuf(pkt) } } diff --git a/go_client/session.go b/go_client/session.go index 117507d..8d8e2d2 100644 --- a/go_client/session.go +++ b/go_client/session.go @@ -296,10 +296,10 @@ func RunSession( } log.Printf("[ВОРКЕР #%d] [DTLS] Соединение установлено ✓", sessionID) - atomic.AddInt32(&stats.ActiveConnections, 1) + stats.ActiveConnections.Add(1) globalActiveConnections.Add(1) defer func() { - atomic.AddInt32(&stats.ActiveConnections, -1) + stats.ActiveConnections.Add(-1) globalActiveConnections.Add(-1) }() @@ -336,9 +336,10 @@ func RunSession( d.Register(slot) defer d.Unregister(slot) - lastServerRxAt := time.Now().UnixNano() - var lastUserTrafficAt int64 - var keepalivePongSeen int32 + var lastServerRxAt atomic.Int64 + lastServerRxAt.Store(time.Now().UnixNano()) + var lastUserTrafficAt atomic.Int64 + var keepalivePongSeen atomic.Int32 // Proxy DTLS ↔ Dispatcher var proxyWg sync.WaitGroup @@ -380,16 +381,16 @@ func RunSession( return case <-t.C: now := time.Now() - lastRxUnix := atomic.LoadInt64(&lastServerRxAt) + lastRxUnix := lastServerRxAt.Load() lastRx := time.Unix(0, lastRxUnix) - if atomic.LoadInt32(&keepalivePongSeen) != 0 && now.Sub(lastRx) > keepalivePongTimeout { + if keepalivePongSeen.Load() != 0 && now.Sub(lastRx) > keepalivePongTimeout { log.Printf("[ВОРКЕР #%d] [HEALTH] сервер не отвечает на keepalive %.0f сек, перезапуск воркера", sessionID, now.Sub(lastRx).Seconds()) sessCancel() return } - lastTxUnix := atomic.LoadInt64(&lastUserTrafficAt) + lastTxUnix := lastUserTrafficAt.Load() if lastTxUnix > lastRxUnix && now.Sub(time.Unix(0, lastTxUnix)) > unansweredUserTrafficTimeout && now.Sub(lastRx) > unansweredUserTrafficTimeout { @@ -420,7 +421,7 @@ func RunSession( log.Printf("[ВОРКЕР #%d] Ошибка Writer: %v", sessionID, writeErr) return } - atomic.StoreInt64(&lastUserTrafficAt, time.Now().UnixNano()) + lastUserTrafficAt.Store(time.Now().UnixNano()) } } }() @@ -445,11 +446,11 @@ func RunSession( return } - atomic.StoreInt64(&lastServerRxAt, time.Now().UnixNano()) + lastServerRxAt.Store(time.Now().UnixNano()) // Skip keepalive pong from server if n == 1 && pkt[0] == keepaliveByte { - atomic.StoreInt32(&keepalivePongSeen, 1) + keepalivePongSeen.Store(1) putPktBuf(pkt) continue } diff --git a/go_client/stats.go b/go_client/stats.go index aa0cb7f..4c74d5f 100644 --- a/go_client/stats.go +++ b/go_client/stats.go @@ -9,9 +9,9 @@ import ( var globalActiveConnections atomic.Int32 type Stats struct { - ActiveConnections int32 - TotalBytesUp int64 - TotalBytesDown int64 + ActiveConnections atomic.Int32 + TotalBytesUp atomic.Int64 + TotalBytesDown atomic.Int64 } func NewStats() *Stats { @@ -27,9 +27,9 @@ func (s *Stats) RunLoop(shutdown <-chan struct{}) { case <-shutdown: return case <-ticker.C: - active := atomic.LoadInt32(&s.ActiveConnections) - up := atomic.LoadInt64(&s.TotalBytesUp) - down := atomic.LoadInt64(&s.TotalBytesDown) + active := s.ActiveConnections.Load() + up := s.TotalBytesUp.Load() + down := s.TotalBytesDown.Load() upMB := float64(up) / (1024.0 * 1024.0) downMB := float64(down) / (1024.0 * 1024.0)