From 1b8aee591ca0f4b0e550c2896c0e5a63f7591294 Mon Sep 17 00:00:00 2001 From: Ivan4537 Date: Sun, 5 Jul 2026 19:11:15 +0300 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=8B=D0=BF=D1=83=D1=81=D0=BA=20WDTT=20P?= =?UTF-8?q?lus=20v6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 12 + README.md | 17 +- admin.go | 25 + admin_test.go | 2 + app/build.gradle.kts | 4 +- app/src/main/AndroidManifest.xml | 12 + .../java/com/wdtt/plus/DeviceCompatibility.kt | 578 ++++++++++++++++++ .../main/java/com/wdtt/plus/MainActivity.kt | 62 ++ .../java/com/wdtt/plus/ServerAdminClient.kt | 5 +- .../main/java/com/wdtt/plus/SettingsStore.kt | 36 +- .../com/wdtt/plus/VpnCompactWidgetProvider.kt | 74 +++ .../java/com/wdtt/plus/VpnWidgetProvider.kt | 26 +- .../java/com/wdtt/plus/WdttApplication.kt | 12 +- .../main/java/com/wdtt/plus/ui/DeployTab.kt | 237 ++++++- .../wdtt/plus/ui/DeviceCompatibilityDialog.kt | 300 +++++++++ .../java/com/wdtt/plus/ui/ExceptionsTab.kt | 324 +++++----- app/src/main/java/com/wdtt/plus/ui/InfoTab.kt | 340 ++++++++++- app/src/main/java/com/wdtt/plus/ui/LogsTab.kt | 33 +- .../main/java/com/wdtt/plus/ui/SettingsTab.kt | 17 +- app/src/main/res/layout/vpn_widget.xml | 19 +- .../main/res/layout/vpn_widget_compact.xml | 34 ++ .../main/res/xml/vpn_widget_compact_info.xml | 8 + app/src/main/res/xml/vpn_widget_info.xml | 2 +- bot.go | 3 +- server.go | 1 + 25 files changed, 1961 insertions(+), 222 deletions(-) create mode 100644 app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt create mode 100644 app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt create mode 100644 app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt create mode 100644 app/src/main/res/layout/vpn_widget_compact.xml create mode 100644 app/src/main/res/xml/vpn_widget_compact_info.xml diff --git a/CHANGELOG.md b/CHANGELOG.md index f14fbe5..62602c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ Здесь фиксируются заметные пользовательские изменения WDTT Plus. +## v6 — 05.07.2026 + +### Интерфейс + +- Журнал событий получил нейтральный фон и более читаемые завершённые сессии в светлой теме. +- Исправлена компоновка виджета: текст больше не перекрывается кнопкой подключения, а при активном VPN отображается название текущего профиля. +- Добавлен компактный виджет 1×1 для переключения VPN с индикатором состояния и названием активного профиля. +- В настройках деплоя добавлена краткая инструкция по созданию и подключению Telegram-бота для управления сервером. +- Переименованное название активного VPN-профиля сохраняется в профиле владельца при установке сервера и восстанавливается при подключении без установки. +- Диагностический отчёт дополнен данными о памяти, сети, WebView, разрядности и состоянии компонентов без включения секретов подключения. +- Добавлена проверка совместимости устройства: при первом запуске приложение предупреждает только о важных архитектурных ограничениях, а в «Инфо» доступна ручная проверка версии WDTT Plus, Android, ABI, нативного клиента, WebView, системных настроек и текущего состояния VPN. + ## v5 — 05.07.2026 > [!IMPORTANT] diff --git a/README.md b/README.md index d8b89d1..9c6e72d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,8 @@ # WDTT Plus — WireGuard over TURN Tunnel
- Android SDK + Android 10+ + Target API 35 Go Version Kotlin License GPLv3 @@ -11,7 +12,7 @@ **WDTT Plus** — это модифицированная версия WDTT для создания защищённого **WireGuard-туннеля поверх TURN/DTLS**. Клиент поднимает локальный VPN-интерфейс на устройстве, получает WireGuard-конфигурацию от вашего сервера и передаёт транспорт через TURN-серверы VK, маскируя соединение под обычный зашифрованный медиатрафик звонка. -image +photo_2026-07-05_14-44-50 ## Содержание @@ -54,6 +55,8 @@ ## Возможности Android-версии +- **Ориентир совместимости:** WDTT Plus смотрит вперёд и ориентируется на Android 10+ с современными требованиями Android SDK. `targetSdk` 35 — это целевой API сборки, а не верхний предел Android: новые версии Android должны поддерживаться по мере тестирования, включая отдельную проверку нативной части на устройствах с 16 KB page size. Android 9 и ниже не являются основной целью поддержки. +- **Проверка устройства:** при первом запуске приложение в фоне проверяет только архитектурные условия — Android, ABI, нативный клиент, память и размер страницы памяти — и предупреждает, если есть риск несовместимости. В **«Инфо»** доступна ручная расширенная проверка версии WDTT Plus, WebView, сети, разрешений Android, текущего состояния VPN и подсказок для настроек. - **Полноценный VPN-режим:** приложение использует `VpnService` и WireGuard GoBackend, поэтому трафик выбранных приложений проходит через системный VPN-интерфейс без ручного импорта конфигов. - **Три профиля подключения:** VPN 1, VPN 2 и VPN 3 хранят отдельные настройки туннеля и деплоя; профиль можно переименовать долгим нажатием в боковых настройках. Название активного профиля видно в заголовках вкладок, передаче подключения, плитке быстрых настроек и активном уведомлении туннеля. - **Корректная передача VPN-слота:** если Android отключает WDTT Plus VPN или другой VPN забирает системный VPN-слот, WDTT Plus останавливает транспорт и переводит плитку/виджет в неактивное состояние. Плитка запускает VPN как с обычными настройками, так и в режиме ссылки, а при активном подключении показывает выбранный профиль вместе с уведомлением туннеля. @@ -65,7 +68,7 @@ - **WRAP без захардкоженного ключа:** внешний RTP AEAD/ChaCha20-Poly1305 слой выводится из пароля подключения через HKDF. Один пароль — один WRAP-ключ, ключ не хранится в APK. - **RTP AEAD обфускация:** транспорт маскируется под RTP/WebRTC аудиотрафик с OPUS payload type, а полезная нагрузка шифруется AEAD-слоем поверх DTLS/WireGuard. - **Деплой с телефона:** вкладка **«Деплой»** подключается к серверу по SSH, загружает `wdtt-server`, создаёт `systemd`-сервис, включает NAT/firewall и открывает рабочие UDP-порты. -- **Подключение к готовому серверу:** если сервер уже установлен, приложение проверяет SSH-доступ и главный пароль, показывает отличия и после подтверждения восстанавливает локальные поля. Этот режим работает только от сервера к приложению и ничего не записывает на сервер. +- **Подключение к готовому серверу:** если сервер уже установлен, приложение проверяет SSH-доступ и главный пароль, показывает отличия и после подтверждения восстанавливает локальные поля. Если серверный профиль владельца был сохранён из переименованного VPN-профиля, это название также вернётся в приложение; стандартные VPN 1/2/3 локальное имя не затирают. Этот режим работает только от сервера к приложению и ничего не записывает на сервер. - **Парольная модель доступа:** сервер поддерживает главный пароль, настраиваемый лимит пользовательских паролей, 16-символьную генерацию, ручное задание пароля с проверками, привязку к устройству и срок действия. Клиентов можно создавать, импортировать, экспортировать, отключать, продлевать, отвязывать, удалять и менять им пароль из приложения или Telegram-бота. - **Горячее обновление WRAP-ключей:** создание, удаление и истечение паролей обновляют набор WRAP-ключей на сервере без перезапуска ядра. - **Исключения приложений:** ЧС и БС хранят независимые наборы. В ЧС отмеченные приложения работают напрямую, в БС только отмеченные направляются в VPN; изменения применяются быстрой перезагрузкой WireGuard. @@ -95,7 +98,7 @@ Android-приложение → VpnService / WireGuard GoBackend → локал ## Быстрый старт 1. Соберите APK по разделу [«Для разработки»](#для-разработки) или скачайте готовую сборку со [страницы релизов WDTT Plus](https://github.com/Ivan4537/WDTT-Plus/releases), когда она опубликована. -2. Установите приложение на Android-смартфон. +2. Установите приложение на Android-смартфон. Основной ориентир совместимости — Android 10+. 3. Подготовьте домен или IP сервера, SSH-логин и SSH-пароль. 4. В VK создайте или откройте групповой звонок и отправьте ссылку вида `vk.com/call/join/xxxxxxxxxxx` в WDTT Plus через **«Поделиться»** либо скопируйте её вручную. 5. Откройте **WDTT Plus** и перейдите во вкладку **«Деплой»**. @@ -213,7 +216,7 @@ Telegram-бот умеет посмотреть статус и диагност #### Отчёт для issue -В разделе **«Информация»** есть кнопка **«Собрать отчёт»**. Она копирует версию приложения, Android SDK, ABI, модель устройства, SoC, ROM и fingerprint — эти данные полезны при разборе крашей и проблем с запуском. +В разделе **«Информация»** есть кнопки **«Собрать отчёт»** и **«Проверить устройство»**. Отчёт копирует версию приложения, Android SDK, ABI и разрядность, размер страницы памяти, модель устройства, SoC, ROM, память, состояние сети, WebView и безопасные параметры запуска. Проверка устройства отдельно показывает текущую версию WDTT Plus, дату релиза, актуальна ли версия на момент копирования, совместимость, предупреждения, текущее состояние VPN и переходы в нужные настройки Android. Адреса, пароли, токены и значения VK-хешей в отчёт не включаются. > [!NOTE] > ### Отчёты об ошибках @@ -231,13 +234,13 @@ Telegram-бот умеет посмотреть статус и диагност ## Для разработки -Для полной сборки нужны Android SDK/NDK и Go 1.26. Каноническая release-сборка: +Для полной сборки нужны актуальные Android SDK/NDK и Go 1.26. Проект собирается с `targetSdk` 35 и отдельными APK для `arm64-v8a`, `armeabi-v7a`, `x86_64` и universal. Каноническая release-сборка: ```bash ./gradlew assembleRelease ``` -Команда пересобирает нативный Android-клиент и Linux-сервер для деплоя, затем помещает подписанные APK в `app/build/outputs/apk/release/named/`. Для большинства современных устройств подходит `WDTT-Plus-v1-arm64-v8a-release.apk`. +Команда пересобирает нативный Android-клиент и Linux-сервер для деплоя, затем помещает подписанные APK в `app/build/outputs/apk/release/named/`. Для большинства современных устройств подходит `WDTT-Plus-vN-arm64-v8a-release.apk`, где `N` — номер выпуска. В `app/src/debug/java/com/wdtt/plus/WDTTPreviews.kt` находятся Compose Preview основных вкладок. Они входят только в debug source set и не попадают в release APK. diff --git a/admin.go b/admin.go index 880ce25..6fd35ea 100644 --- a/admin.go +++ b/admin.go @@ -490,6 +490,7 @@ func normalizeAdminProfileForStorage(profile AdminProfileEntry, defaultPorts str } profile.VkHashes = strings.TrimSpace(profile.VkHashes) profile.SecondaryVkHash = strings.TrimSpace(profile.SecondaryVkHash) + profile.ProfileName = normalizeAdminProfileName(profile.ProfileName) if profile.WorkersPerHash < 1 || profile.WorkersPerHash > 128 { profile.WorkersPerHash = 16 } @@ -542,6 +543,28 @@ func normalizeAdminProfileSNI(value string) string { return value } +func normalizeAdminProfileName(value string) string { + value = strings.Join(strings.Fields(strings.TrimSpace(value)), " ") + if isDefaultAdminProfileName(value) { + return "" + } + runes := []rune(value) + if len(runes) > 48 { + value = string(runes[:48]) + } + return value +} + +func isDefaultAdminProfileName(value string) bool { + normalized := strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(value), " ", "")) + switch normalized { + case "VPN1", "VPN2", "VPN3", "ВПН1", "ВПН2", "ВПН3": + return true + default: + return false + } +} + func normalizeAdminProfileDeviceIDs(values []string) []string { if len(values) == 0 { return nil @@ -1246,6 +1269,7 @@ func adminUpdateAdminProfile(configDir string, loaded *Database, args []string) fs.SetOutput(io.Discard) vkHashes := fs.String("vk-hashes", "", "VK-хеши владельца") secondaryVkHash := fs.String("secondary-vk-hash", "", "резервный VK-хеш владельца") + profileName := fs.String("profile-name", "", "название VPN-профиля владельца") workers := fs.Int("workers", 16, "потоков на хеш") protocol := fs.String("protocol", "udp", "протокол клиента") listenPort := fs.Int("listen-port", 0, "локальный порт клиента") @@ -1273,6 +1297,7 @@ func adminUpdateAdminProfile(configDir string, loaded *Database, args []string) } profile.SecondaryVkHash = normalized } + profile.ProfileName = normalizeAdminProfileName(*profileName) if *workers < 1 || *workers > 128 { return adminResponse{}, errors.New("workers должен быть 1..128") } diff --git a/admin_test.go b/admin_test.go index a756d78..ad7d97e 100644 --- a/admin_test.go +++ b/admin_test.go @@ -90,6 +90,7 @@ func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) { "update-admin-profile", "--vk-hashes", "abcdefghijklmnop,qrstuvwxyzABCDEF", "--secondary-vk-hash", "1234567890abcdef", + "--profile-name", "Домашний телефон", "--workers", "27", "--protocol", "tcp", "--listen-port", "9010", @@ -104,6 +105,7 @@ func TestAdminSocketAppliesClientChangesWithoutRestart(t *testing.T) { profile := listedOwner.Server.AdminProfile if profile.VkHashes != "abcdefghijklmnop,qrstuvwxyzABCDEF" || profile.SecondaryVkHash != "1234567890abcdef" || + profile.ProfileName != "Домашний телефон" || profile.WorkersPerHash != 27 || profile.Protocol != "tcp" || profile.ListenPort != 9010 || diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f648491..c2f1479 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -5,7 +5,7 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") } -val appVersionName = "5" +val appVersionName = "6" val releaseApkBaseName = "WDTT-Plus" val localProperties = Properties() @@ -22,7 +22,7 @@ android { applicationId = "com.wdtt.plus" minSdk = 28 targetSdk = 35 - versionCode = 5 + versionCode = 6 versionName = appVersionName buildConfigField("String", "MOD_RELEASE_DATE", "\"05.07.2026\"") diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6fc072e..a7853bc 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -130,6 +130,18 @@ android:name="android.appwidget.provider" android:resource="@xml/vpn_widget_info" /> + + + + + + + diff --git a/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt new file mode 100644 index 0000000..bfca787 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/DeviceCompatibility.kt @@ -0,0 +1,578 @@ +package com.wdtt.plus + +import android.Manifest +import android.app.ActivityManager +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.Uri +import android.net.VpnService +import android.os.Build +import android.os.PowerManager +import android.os.StatFs +import android.provider.Settings +import android.system.Os +import android.system.OsConstants +import android.webkit.WebView +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +enum class DeviceCheckSeverity { + Ok, + Info, + Warning, + Error +} + +enum class DeviceCheckAction { + AppSettings, + BatterySettings, + NetworkSettings, + VpnSettings, + UnknownAppInstallSettings, + WebViewSettings +} + +data class DeviceCheckItem( + val title: String, + val status: String, + val details: String, + val recommendation: String = "", + val severity: DeviceCheckSeverity = DeviceCheckSeverity.Ok, + val firstLaunchRelevant: Boolean = false, + val action: DeviceCheckAction? = null +) + +data class DeviceCompatibilityReport( + val checkedAt: Long, + val items: List +) { + val problemItems: List + get() = items.filter { it.severity == DeviceCheckSeverity.Warning || it.severity == DeviceCheckSeverity.Error } + + val firstLaunchProblemItems: List + get() = items.filter { + it.firstLaunchRelevant && + (it.severity == DeviceCheckSeverity.Warning || it.severity == DeviceCheckSeverity.Error) + } + + val hasErrors: Boolean + get() = items.any { it.severity == DeviceCheckSeverity.Error } + + val overallStatus: String + get() = when { + items.any { it.severity == DeviceCheckSeverity.Error } -> "есть критичные несовместимости" + items.any { it.severity == DeviceCheckSeverity.Warning } -> "есть предупреждения" + else -> "подходит" + } + + fun firstLaunchReport(): DeviceCompatibilityReport = + copy(items = firstLaunchProblemItems) + + fun toPlainText(): String { + val formatter = SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.ROOT) + return buildString { + appendLine("Проверка устройства WDTT Plus") + appendLine("Проверено: ${formatter.format(Date(checkedAt))}") + appendLine("Итог: $overallStatus") + items.forEach { item -> + appendLine() + appendLine("[${item.severity.label()}] ${item.title}: ${item.status}") + appendLine(item.details) + if (item.recommendation.isNotBlank()) { + appendLine("Рекомендация: ${item.recommendation}") + } + } + }.trim() + } +} + +object DeviceCompatibility { + const val APP_VERSION_ITEM_TITLE = "Версия WDTT Plus" + private const val MIN_RECOMMENDED_SDK = 29 + private const val LOW_STORAGE_WARNING_BYTES = 200L * 1024L * 1024L + private val supportedNativeAbis = setOf("arm64-v8a", "armeabi-v7a", "x86_64") + + fun check( + context: Context, + includeRuntimeChecks: Boolean, + workersPerHash: Int? = null + ): DeviceCompatibilityReport { + val appContext = context.applicationContext + val items = buildList { + add(androidVersionItem()) + add(abiItem()) + add(nativeClientItem(appContext)) + add(pageSizeItem()) + add(memoryClassItem(appContext, workersPerHash)) + add(webViewItem(includeRuntimeChecks)) + add(storageItem(appContext)) + + if (includeRuntimeChecks) { + add(networkItem(appContext)) + add(vpnPermissionItem(appContext)) + add(tunnelStateItem()) + add(notificationPermissionItem(appContext)) + add(batteryItem(appContext)) + add(updateInstallPermissionItem(appContext)) + } + } + return DeviceCompatibilityReport( + checkedAt = System.currentTimeMillis(), + items = items + ) + } + + fun appVersionItem( + currentVersion: String, + releaseDate: String, + latestRelease: AppReleaseInfo? + ): DeviceCheckItem { + val normalizedCurrent = currentVersion.ifBlank { "v${BuildConfig.VERSION_NAME}" } + val currentWithDate = "$normalizedCurrent от $releaseDate" + return when { + latestRelease == null -> DeviceCheckItem( + title = APP_VERSION_ITEM_TITLE, + status = "$currentWithDate · актуальность не проверена", + details = "Не удалось получить последнюю версию WDTT Plus с GitHub на момент проверки.", + recommendation = "Проверьте интернет или нажмите «Проверить обновления» позже.", + severity = DeviceCheckSeverity.Warning + ) + isNewerVersion(normalizedCurrent, latestRelease.versionTag) -> DeviceCheckItem( + title = APP_VERSION_ITEM_TITLE, + status = "$currentWithDate · доступна ${latestRelease.versionTag}", + details = "На GitHub уже есть более новая версия WDTT Plus. Часть исправлений может отсутствовать на этом телефоне.", + recommendation = "Обновите приложение до ${latestRelease.versionTag}.", + severity = DeviceCheckSeverity.Warning + ) + else -> DeviceCheckItem( + title = APP_VERSION_ITEM_TITLE, + status = "$currentWithDate · актуальная", + details = "На момент проверки последняя найденная версия: ${latestRelease.versionTag}.", + severity = DeviceCheckSeverity.Ok + ) + } + } + + private fun androidVersionItem(): DeviceCheckItem { + val version = Build.VERSION.RELEASE ?: "?" + val sdk = Build.VERSION.SDK_INT + return if (sdk < MIN_RECOMMENDED_SDK) { + DeviceCheckItem( + title = "Версия Android", + status = "Android $version / SDK $sdk", + details = "WDTT Plus ориентируется на Android 10+ / SDK 29+. На этой версии работа нативного клиента и сетевого стека не гарантируется.", + recommendation = "Используйте устройство с Android 10 или новее.", + severity = DeviceCheckSeverity.Error, + firstLaunchRelevant = true + ) + } else { + DeviceCheckItem( + title = "Версия Android", + status = "Android $version / SDK $sdk", + details = "Версия Android подходит под основной ориентир совместимости WDTT Plus.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = true + ) + } + } + + private fun abiItem(): DeviceCheckItem { + val allAbis = Build.SUPPORTED_ABIS.toList() + val supported = allAbis.filter { it in supportedNativeAbis } + val primary = allAbis.firstOrNull().orEmpty().ifBlank { "не определён" } + return when { + supported.isEmpty() -> DeviceCheckItem( + title = "Архитектура CPU", + status = "неподдерживаемая ABI", + details = "Устройство сообщает ABI: ${allAbis.joinToString().ifBlank { "не определены" }}. WDTT Plus собирается для ${supportedNativeAbis.joinToString()}.", + recommendation = "Попробуйте universal APK только если устройство действительно поддерживает одну из этих ABI; иначе приложение не сможет запустить нативный клиент.", + severity = DeviceCheckSeverity.Error, + firstLaunchRelevant = true + ) + primary == "armeabi-v7a" -> DeviceCheckItem( + title = "Архитектура CPU", + status = "32-bit ARM / armeabi-v7a", + details = "Эта ABI поддерживается, но на старых 32-битных устройствах запас по памяти и потокам обычно ниже, чем на arm64.", + recommendation = "Если туннель нестабилен, уменьшите мощность до 4–8 потоков и приложите отчёт из Инфо.", + severity = DeviceCheckSeverity.Info, + firstLaunchRelevant = false + ) + else -> DeviceCheckItem( + title = "Архитектура CPU", + status = primary, + details = "Найдена поддерживаемая ABI: ${supported.joinToString()}.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = true + ) + } + } + + private fun nativeClientItem(context: Context): DeviceCheckItem { + val nativeLibraryDir = context.applicationInfo.nativeLibraryDir.orEmpty() + val nativeClient = File(nativeLibraryDir, "libclient.so") + return when { + !nativeClient.isFile -> DeviceCheckItem( + title = "Нативный клиент", + status = "libclient.so не найден", + details = "Android-часть запустилась, но нативный Go-клиент, который поднимает TURN/DTLS транспорт, в установленном APK не найден.", + recommendation = "Переустановите APK нужной ABI или universal APK из официального релиза WDTT Plus.", + severity = DeviceCheckSeverity.Error, + firstLaunchRelevant = true + ) + nativeClient.length() <= 0L -> DeviceCheckItem( + title = "Нативный клиент", + status = "libclient.so пустой", + details = "Файл нативного клиента найден, но его размер равен нулю.", + recommendation = "Переустановите APK; текущая установка выглядит повреждённой.", + severity = DeviceCheckSeverity.Error, + firstLaunchRelevant = true + ) + else -> DeviceCheckItem( + title = "Нативный клиент", + status = "найден", + details = "libclient.so найден в установленном APK, размер: ${formatMiB(nativeClient.length())}.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = true + ) + } + } + + private fun pageSizeItem(): DeviceCheckItem { + val pageSize = runCatching { Os.sysconf(OsConstants._SC_PAGESIZE) }.getOrNull() + return when { + pageSize == null || pageSize <= 0L -> DeviceCheckItem( + title = "Страница памяти", + status = "не удалось определить", + details = "Android не вернул размер страницы памяти.", + recommendation = "Если VPN не стартует на новом устройстве, приложите отчёт из Инфо.", + severity = DeviceCheckSeverity.Info, + firstLaunchRelevant = false + ) + pageSize > 4096L -> DeviceCheckItem( + title = "Страница памяти", + status = "$pageSize байт", + details = "Устройство использует страницу памяти больше 4 KB. Для новых Android-устройств с 16 KB page size нужна отдельная проверка нативной библиотеки.", + recommendation = "Запуск не блокируется. Если туннель не стартует, отправьте отчёт из Инфо — это важный сценарий для будущей совместимости.", + severity = DeviceCheckSeverity.Warning, + firstLaunchRelevant = true + ) + else -> DeviceCheckItem( + title = "Страница памяти", + status = "$pageSize байт", + details = "Обычный размер страницы памяти для текущей нативной сборки.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = true + ) + } + } + + private fun memoryClassItem(context: Context, workersPerHash: Int?): DeviceCheckItem { + val activityManager = runCatching { + context.getSystemService(ActivityManager::class.java) + }.getOrNull() + val lowRam = activityManager?.isLowRamDevice == true + val memoryClass = activityManager?.memoryClass ?: 0 + val largeMemoryClass = activityManager?.largeMemoryClass ?: 0 + val workerWarning = workersPerHash != null && workersPerHash > 8 && lowRam + return when { + workerWarning -> DeviceCheckItem( + title = "Память устройства", + status = "low-RAM, мощность $workersPerHash", + details = "Android помечает устройство как low-RAM. Большое число потоков может не успевать стабильно подняться.", + recommendation = "Для таких устройств начните с 4–8 потоков. Это не ошибка подключения к профилю VPN.", + severity = DeviceCheckSeverity.Warning, + firstLaunchRelevant = true + ) + lowRam -> DeviceCheckItem( + title = "Память устройства", + status = "low-RAM / Android Go возможен", + details = "Устройство относится к классу с ограниченной памятью. Приложение может работать, но высокая мощность будет менее предсказуемой.", + recommendation = "Если активные потоки не появляются, уменьшите мощность до 4–8 и проверьте логи.", + severity = DeviceCheckSeverity.Warning, + firstLaunchRelevant = true + ) + else -> DeviceCheckItem( + title = "Память устройства", + status = "обычный класс памяти", + details = "memoryClass=$memoryClass МБ, largeMemoryClass=$largeMemoryClass МБ.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = false + ) + } + } + + private fun webViewItem(includeRuntimeChecks: Boolean): DeviceCheckItem { + if (!includeRuntimeChecks) { + return DeviceCheckItem( + title = "WebView", + status = "не проверялся", + details = "WebView не нужен для первичной архитектурной проверки.", + severity = DeviceCheckSeverity.Info, + firstLaunchRelevant = false + ) + } + val webView = runCatching { WebView.getCurrentWebViewPackage() }.getOrNull() + return if (webView == null) { + DeviceCheckItem( + title = "WebView", + status = "не найден", + details = "Автоматическая и ручная captcha через WebView могут не работать.", + recommendation = "Проверьте системный Android System WebView или браузер-провайдер WebView.", + severity = DeviceCheckSeverity.Warning, + firstLaunchRelevant = false, + action = DeviceCheckAction.WebViewSettings + ) + } else { + DeviceCheckItem( + title = "WebView", + status = webView.packageName, + details = "Версия: ${webView.versionName}. WebView доступен для captcha-сценариев.", + severity = DeviceCheckSeverity.Ok, + firstLaunchRelevant = false + ) + } + } + + private fun storageItem(context: Context): DeviceCheckItem { + val availableBytes = runCatching { StatFs(context.filesDir.absolutePath).availableBytes }.getOrNull() + return when { + availableBytes == null -> DeviceCheckItem( + title = "Память приложения", + status = "не удалось проверить", + details = "Свободное место в разделе приложения не определено.", + severity = DeviceCheckSeverity.Info + ) + availableBytes < LOW_STORAGE_WARNING_BYTES -> DeviceCheckItem( + title = "Память приложения", + status = "мало свободного места", + details = "Свободно примерно ${formatMiB(availableBytes)}. Для скачивания обновлений, отчётов и временных файлов этого может быть мало.", + recommendation = "Освободите место на устройстве.", + severity = DeviceCheckSeverity.Warning, + action = DeviceCheckAction.AppSettings + ) + else -> DeviceCheckItem( + title = "Память приложения", + status = "достаточно", + details = "Свободно примерно ${formatMiB(availableBytes)}.", + severity = DeviceCheckSeverity.Ok + ) + } + } + + private fun networkItem(context: Context): DeviceCheckItem { + val connectivityManager = runCatching { + context.getSystemService(ConnectivityManager::class.java) + }.getOrNull() + val activeNetwork = runCatching { connectivityManager?.activeNetwork }.getOrNull() + val capabilities = runCatching { + activeNetwork?.let { connectivityManager?.getNetworkCapabilities(it) } + }.getOrNull() + if (capabilities == null) { + return DeviceCheckItem( + title = "Сеть Android", + status = "активная сеть не найдена", + details = "Приложение запустится, но для VKCalls, TURN и обновлений нужна сеть.", + recommendation = "Подключитесь к Wi‑Fi или мобильной сети.", + severity = DeviceCheckSeverity.Warning, + action = DeviceCheckAction.NetworkSettings + ) + } + val transports = buildList { + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) add("Wi‑Fi") + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) add("мобильная") + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) add("Ethernet") + if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) add("VPN") + }.joinToString().ifBlank { "не определён" } + val hasInternet = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + val validated = capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) + return if (!hasInternet || !validated) { + DeviceCheckItem( + title = "Сеть Android", + status = "$transports, интернет не подтверждён", + details = "Android видит сеть, но не подтверждает полноценный доступ в интернет.", + recommendation = "Проверьте сеть, DNS, captive portal или ограничения оператора.", + severity = DeviceCheckSeverity.Warning, + action = DeviceCheckAction.NetworkSettings + ) + } else { + DeviceCheckItem( + title = "Сеть Android", + status = "$transports, интернет подтверждён", + details = "Активная сеть выглядит пригодной для проверки VK/TURN.", + severity = DeviceCheckSeverity.Ok + ) + } + } + + private fun vpnPermissionItem(context: Context): DeviceCheckItem { + val granted = runCatching { VpnService.prepare(context) == null }.getOrDefault(false) + return if (granted) { + DeviceCheckItem( + title = "VPN-разрешение", + status = "выдано", + details = "WDTT Plus уже может поднимать системный VPN-интерфейс.", + severity = DeviceCheckSeverity.Ok, + action = DeviceCheckAction.VpnSettings + ) + } else { + DeviceCheckItem( + title = "VPN-разрешение", + status = "будет запрошено при подключении", + details = "Отсутствие VPN-разрешения сейчас не является ошибкой. Оно понадобится только при первом запуске туннеля.", + recommendation = "Если подключение не стартует после нажатия «Подключить», подтвердите системный запрос VPN.", + severity = DeviceCheckSeverity.Info, + action = DeviceCheckAction.VpnSettings + ) + } + } + + private fun tunnelStateItem(): DeviceCheckItem { + val running = TunnelManager.running.value + val activeWorkers = TunnelManager.activeWorkers.value + val issue = TunnelManager.connectionIssue.value + return if (running) { + DeviceCheckItem( + title = "Текущее подключение VPN", + status = "активно", + details = "VPN подключён. Активных каналов: $activeWorkers.", + recommendation = issue?.let { "${it.title}: ${it.action}" }.orEmpty(), + severity = if (activeWorkers > 0) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning + ) + } else { + DeviceCheckItem( + title = "Текущее подключение VPN", + status = "не активно", + details = "VPN сейчас не подключён. Это не мешает проверке устройства; пункт фиксирует текущее состояние туннеля.", + recommendation = issue?.let { "${it.title}: ${it.action}" }.orEmpty(), + severity = DeviceCheckSeverity.Info + ) + } + } + + private fun notificationPermissionItem(context: Context): DeviceCheckItem { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + return DeviceCheckItem( + title = "Уведомления", + status = "отдельное разрешение не требуется", + details = "На этой версии Android уведомления не требуют отдельного runtime-разрешения.", + severity = DeviceCheckSeverity.Ok + ) + } + val granted = context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + return if (granted) { + DeviceCheckItem( + title = "Уведомления", + status = "разрешены", + details = "Приложение сможет показывать статус VPN и важные события.", + severity = DeviceCheckSeverity.Ok, + action = DeviceCheckAction.AppSettings + ) + } else { + DeviceCheckItem( + title = "Уведомления", + status = "не разрешены", + details = "Это не мешает архитектурной совместимости, но может скрывать статус VPN, ошибки и запросы captcha.", + recommendation = "Разрешите уведомления WDTT Plus в настройках Android.", + severity = DeviceCheckSeverity.Warning, + action = DeviceCheckAction.AppSettings + ) + } + } + + private fun batteryItem(context: Context): DeviceCheckItem { + val powerManager = runCatching { context.getSystemService(PowerManager::class.java) }.getOrNull() + val ignored = runCatching { + powerManager?.isIgnoringBatteryOptimizations(context.packageName) + }.getOrNull() + return when (ignored) { + true -> DeviceCheckItem( + title = "Фоновая работа", + status = "без ограничений батареи", + details = "Android не должен агрессивно останавливать VPN в фоне.", + severity = DeviceCheckSeverity.Ok, + action = DeviceCheckAction.BatterySettings + ) + false -> DeviceCheckItem( + title = "Фоновая работа", + status = "ограничения батареи могут мешать", + details = "Это не архитектурная ошибка, но на некоторых прошивках VPN может засыпать при выключенном экране.", + recommendation = "Отключите ограничения батареи для WDTT Plus, если туннель сам останавливается.", + severity = DeviceCheckSeverity.Warning, + action = DeviceCheckAction.BatterySettings + ) + null -> DeviceCheckItem( + title = "Фоновая работа", + status = "не удалось проверить", + details = "Состояние ограничений батареи не определено.", + severity = DeviceCheckSeverity.Info, + action = DeviceCheckAction.AppSettings + ) + } + } + + private fun updateInstallPermissionItem(context: Context): DeviceCheckItem { + val canInstall = runCatching { context.packageManager.canRequestPackageInstalls() } + .getOrDefault(false) + return if (canInstall) { + DeviceCheckItem( + title = "Установка обновлений", + status = "разрешена", + details = "WDTT Plus сможет скачать APK и передать его системному установщику Android.", + severity = DeviceCheckSeverity.Ok, + action = DeviceCheckAction.UnknownAppInstallSettings + ) + } else { + DeviceCheckItem( + title = "Установка обновлений", + status = "потребуется разрешение", + details = "Это не мешает VPN. Разрешение понадобится только для установки APK, скачанного внутри приложения.", + recommendation = "Когда будете обновляться из приложения, Android попросит разрешить установку из WDTT Plus.", + severity = DeviceCheckSeverity.Info, + action = DeviceCheckAction.UnknownAppInstallSettings + ) + } + } + + private fun formatMiB(bytes: Long): String = + "${bytes.coerceAtLeast(0L) / (1024L * 1024L)} МБ" +} + +fun DeviceCheckSeverity.label(): String = when (this) { + DeviceCheckSeverity.Ok -> "OK" + DeviceCheckSeverity.Info -> "INFO" + DeviceCheckSeverity.Warning -> "WARN" + DeviceCheckSeverity.Error -> "ERROR" +} + +fun DeviceCheckAction.label(): String = when (this) { + DeviceCheckAction.AppSettings -> "Настройки приложения" + DeviceCheckAction.BatterySettings -> "Батарея" + DeviceCheckAction.NetworkSettings -> "Настройки сети" + DeviceCheckAction.VpnSettings -> "VPN" + DeviceCheckAction.UnknownAppInstallSettings -> "Установка APK" + DeviceCheckAction.WebViewSettings -> "WebView" +} + +fun deviceCheckActionIntent(context: Context, action: DeviceCheckAction): Intent { + return when (action) { + DeviceCheckAction.AppSettings -> Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { + data = Uri.parse("package:${context.packageName}") + } + DeviceCheckAction.BatterySettings -> Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { + data = Uri.parse("package:${context.packageName}") + } + DeviceCheckAction.NetworkSettings -> Intent(Settings.ACTION_WIRELESS_SETTINGS) + DeviceCheckAction.VpnSettings -> Intent(Settings.ACTION_VPN_SETTINGS) + DeviceCheckAction.UnknownAppInstallSettings -> Intent( + Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:${context.packageName}") + ) + DeviceCheckAction.WebViewSettings -> Intent(Settings.ACTION_WEBVIEW_SETTINGS) + } +} diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt index 3ff3c10..9157346 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -79,13 +79,16 @@ import com.wdtt.plus.ui.FloatingToolbar import com.wdtt.plus.ui.LogsTab import com.wdtt.plus.ui.SettingsTab import com.wdtt.plus.ui.DeployTab +import com.wdtt.plus.ui.DeviceCompatibilityDialog import com.wdtt.plus.ui.ExceptionsTab import com.wdtt.plus.ui.InfoTab import com.wdtt.plus.ui.AdminImportDialog import com.wdtt.plus.ui.TransferCenterDialog +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext import java.io.File import kotlin.math.PI import kotlin.math.abs @@ -654,6 +657,9 @@ fun MainScreen( val migrationNoticeV2Shown by settingsStore.migrationNoticeV2Shown.collectAsStateWithLifecycle(initialValue = true) val migrationNoticeV3Shown by settingsStore.migrationNoticeV3Shown.collectAsStateWithLifecycle(initialValue = true) val migrationNoticeV5Shown by settingsStore.migrationNoticeV5Shown.collectAsStateWithLifecycle(initialValue = true) + val deviceCompatibilityCheckComplete by settingsStore.deviceCompatibilityCheckComplete.collectAsStateWithLifecycle( + initialValue = true + ) val isAdminInterface = interfaceRole == "admin" val isUpdatedInstall = remember(context) { runCatching { @@ -684,6 +690,8 @@ fun MainScreen( val safeBottomInset = with(density) { WindowInsets.safeDrawing.getBottom(density).toDp() } val navOverlayReserve = safeBottomInset + 96.dp var showTransferCenter by rememberSaveable { mutableStateOf(false) } + var startupDeviceReport by remember { mutableStateOf(null) } + var startupDeviceCheckRunning by remember { mutableStateOf(false) } val updateInstallPermissionLauncher = rememberLauncherForActivityResult( ActivityResultContracts.StartActivityForResult() ) { @@ -727,12 +735,47 @@ fun MainScreen( } } + fun dismissStartupDeviceReport() { + startupDeviceReport = null + scope.launch { + settingsStore.saveDeviceCompatibilityCheckComplete(true) + } + } + + LaunchedEffect(deviceCompatibilityCheckComplete) { + if (!deviceCompatibilityCheckComplete && !startupDeviceCheckRunning) { + startupDeviceCheckRunning = true + val report = withContext(Dispatchers.Default) { + DeviceCompatibility.check( + context = context.applicationContext, + includeRuntimeChecks = false + ) + }.firstLaunchReport() + + if (report.items.isEmpty()) { + settingsStore.saveDeviceCompatibilityCheckComplete(true) + } else { + startupDeviceReport = report + } + startupDeviceCheckRunning = false + } + } + if (interfaceRole.isBlank()) { RoleSelectionScreen( onRoleSelected = { role -> scope.launch { settingsStore.saveInterfaceRole(role) } } ) + startupDeviceReport?.let { report -> + DeviceCompatibilityDialog( + report = report, + title = "Проверка устройства", + subtitle = "WDTT Plus нашёл нюансы совместимости. Запуск не блокируется — это предупреждение, чтобы было понятно, куда смотреть при проблемах.", + note = "Первый запуск проверяет только базовую совместимость устройства: Android, ABI, нативный клиент, память и page size. Активен ли VPN сейчас — на этом этапе не важно.", + onDismiss = ::dismissStartupDeviceReport + ) + } return } @@ -742,6 +785,15 @@ fun MainScreen( scope.launch { settingsStore.savePermissionOnboardingComplete(true) } } ) + startupDeviceReport?.let { report -> + DeviceCompatibilityDialog( + report = report, + title = "Проверка устройства", + subtitle = "WDTT Plus нашёл нюансы совместимости. Запуск не блокируется — это предупреждение, чтобы было понятно, куда смотреть при проблемах.", + note = "Первый запуск проверяет только базовую совместимость устройства: Android, ABI, нативный клиент, память и page size. Активен ли VPN сейчас — на этом этапе не важно.", + onDismiss = ::dismissStartupDeviceReport + ) + } return } @@ -1074,6 +1126,16 @@ fun MainScreen( ) } + startupDeviceReport?.let { report -> + DeviceCompatibilityDialog( + report = report, + title = "Проверка устройства", + subtitle = "WDTT Plus нашёл нюансы совместимости. Запуск не блокируется — это предупреждение, чтобы было понятно, куда смотреть при проблемах.", + note = "Первый запуск проверяет только базовую совместимость устройства: Android, ABI, нативный клиент, память и page size. Активен ли VPN сейчас — на этом этапе не важно.", + onDismiss = ::dismissStartupDeviceReport + ) + } + if (showTransferCenter) { TransferCenterDialog( settingsStore = settingsStore, diff --git a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt index cc278ab..5e5232a 100644 --- a/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt +++ b/app/src/main/java/com/wdtt/plus/ServerAdminClient.kt @@ -19,6 +19,7 @@ data class ServerAdminTarget( data class ServerAdminProfileInfo( val vkHashes: String = "", val secondaryVkHash: String = "", + val profileName: String = "", val workersPerHash: Int = 16, val protocol: String = "udp", val listenPort: Int = 9000, @@ -29,7 +30,7 @@ data class ServerAdminProfileInfo( val updatedAt: Long = 0 ) { val hasSavedFields: Boolean - get() = updatedAt > 0L || vkHashes.isNotBlank() || secondaryVkHash.isNotBlank() + get() = updatedAt > 0L || vkHashes.isNotBlank() || secondaryVkHash.isNotBlank() || vpnProfileRestorableName(profileName).isNotBlank() } data class ServerAdminState( @@ -288,6 +289,7 @@ object ServerAdminClient { "update-admin-profile", "--vk-hashes", profile.vkHashes.trim(), "--secondary-vk-hash", profile.secondaryVkHash.trim(), + "--profile-name", profile.profileName.trim(), "--workers", profile.workersPerHash.coerceIn(1, 128).toString(), "--protocol", profile.protocol.trim().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp", "--listen-port", profile.listenPort.coerceIn(1, 65535).toString(), @@ -430,6 +432,7 @@ object ServerAdminClient { return ServerAdminProfileInfo( vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(), secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(), + profileName = vpnProfileRestorableName(json?.optString("profile_name", "").orEmpty()), workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128), protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp", listenPort = listenPort, diff --git a/app/src/main/java/com/wdtt/plus/SettingsStore.kt b/app/src/main/java/com/wdtt/plus/SettingsStore.kt index f65c302..a4f1660 100644 --- a/app/src/main/java/com/wdtt/plus/SettingsStore.kt +++ b/app/src/main/java/com/wdtt/plus/SettingsStore.kt @@ -314,6 +314,7 @@ class SettingsStore(context: Context) { private val MIGRATION_NOTICE_V2_SHOWN = booleanPreferencesKey("migration_notice_v2_shown") private val MIGRATION_NOTICE_V3_SHOWN = booleanPreferencesKey("migration_notice_v3_shown") private val MIGRATION_NOTICE_V5_SHOWN = booleanPreferencesKey("migration_notice_v5_shown") + private val DEVICE_COMPATIBILITY_CHECK_COMPLETE = booleanPreferencesKey("device_compatibility_check_complete") private val DEPLOY_CLIENTS_SECTION_EXPANDED = booleanPreferencesKey("deploy_clients_section_expanded") private val DEPLOY_OUTBOUND_SECTION_EXPANDED = booleanPreferencesKey("deploy_outbound_section_expanded") private val DEPLOY_MIGRATION_SECTION_EXPANDED = booleanPreferencesKey("deploy_migration_section_expanded") @@ -539,6 +540,9 @@ class SettingsStore(context: Context) { val migrationNoticeV2Shown: Flow = dataStore.data.map { it[MIGRATION_NOTICE_V2_SHOWN] ?: false } val migrationNoticeV3Shown: Flow = dataStore.data.map { it[MIGRATION_NOTICE_V3_SHOWN] ?: false } val migrationNoticeV5Shown: Flow = dataStore.data.map { it[MIGRATION_NOTICE_V5_SHOWN] ?: false } + val deviceCompatibilityCheckComplete: Flow = dataStore.data.map { + it[DEVICE_COMPATIBILITY_CHECK_COMPLETE] ?: false + } val deployClientsSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_CLIENTS_SECTION_EXPANDED] ?: true } val deployOutboundSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_OUTBOUND_SECTION_EXPANDED] ?: false } val deployMigrationSectionExpanded: Flow = dataStore.data.map { it[DEPLOY_MIGRATION_SECTION_EXPANDED] ?: false } @@ -657,6 +661,12 @@ class SettingsStore(context: Context) { } } + suspend fun saveDeviceCompatibilityCheckComplete(complete: Boolean) { + dataStore.edit { prefs -> + prefs[DEVICE_COMPATIBILITY_CHECK_COMPLETE] = complete + } + } + suspend fun saveDeployClientsSectionExpanded(expanded: Boolean) { dataStore.edit { prefs -> prefs[DEPLOY_CLIENTS_SECTION_EXPANDED] = expanded @@ -710,14 +720,10 @@ class SettingsStore(context: Context) { dataStore.edit { prefs -> val profile = prefs[ACTIVE_PROFILE] ?: 0 prefs[getProfileKey(WDTT_LINK, profile)] = link - val importedProfileName = normalizeVpnProfileName(WdttDeepLink.parse(link)?.profileName.orEmpty()) + val importedProfileName = vpnProfileRestorableName(WdttDeepLink.parse(link)?.profileName.orEmpty()) if (importedProfileName.isNotBlank()) { val profileNameKey = getProfileKey(PROFILE_NAME, profile) - if (importedProfileName == vpnProfileDefaultName(profile)) { - prefs.remove(profileNameKey) - } else { - prefs[profileNameKey] = importedProfileName - } + prefs[profileNameKey] = importedProfileName } } } @@ -905,14 +911,10 @@ class SettingsStore(context: Context) { val profile = plan.targetProfile.coerceIn(0, VPN_PROFILE_COUNT - 1) dataStore.edit { prefs -> prefs[ACTIVE_PROFILE] = profile - val importedProfileName = normalizeVpnProfileName(parts.profileName) + val importedProfileName = vpnProfileRestorableName(parts.profileName) if (importedProfileName.isNotBlank()) { val profileNameKey = getProfileKey(PROFILE_NAME, profile) - if (importedProfileName == vpnProfileDefaultName(profile)) { - prefs.remove(profileNameKey) - } else { - prefs[profileNameKey] = importedProfileName - } + prefs[profileNameKey] = importedProfileName } prefs[getProfileKey(WDTT_LINK_MODE, profile)] = plan.storeAsLink if (plan.storeAsLink) { @@ -1306,3 +1308,13 @@ fun vpnProfileTransferName(profile: Int, names: List): String { val displayName = vpnProfileDisplayName(profile, names) return displayName.takeUnless { it == vpnProfileDefaultName(profile) }.orEmpty() } + +fun isStandardVpnProfileName(name: String): Boolean { + val clean = normalizeVpnProfileName(name) + return clean.isNotBlank() && (0..2).any { clean == vpnProfileDefaultName(it) } +} + +fun vpnProfileRestorableName(name: String): String { + val clean = normalizeVpnProfileName(name) + return clean.takeUnless { it.isBlank() || isStandardVpnProfileName(it) }.orEmpty() +} diff --git a/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt b/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt new file mode 100644 index 0000000..0e3e2b5 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/VpnCompactWidgetProvider.kt @@ -0,0 +1,74 @@ +package com.wdtt.plus + +import android.app.PendingIntent +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProvider +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.widget.RemoteViews +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch + +class VpnCompactWidgetProvider : AppWidgetProvider() { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main) + + companion object { + fun updateAllWidgets(context: Context) { + runCatching { + val manager = AppWidgetManager.getInstance(context) + val component = ComponentName(context, VpnCompactWidgetProvider::class.java) + val ids = manager.getAppWidgetIds(component) + if (ids.isNotEmpty()) { + context.sendBroadcast( + Intent(context, VpnCompactWidgetProvider::class.java).apply { + action = AppWidgetManager.ACTION_APPWIDGET_UPDATE + putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids) + } + ) + } + } + } + } + + override fun onUpdate( + context: Context, + appWidgetManager: AppWidgetManager, + appWidgetIds: IntArray + ) { + val running = TunnelManager.running.value + scope.launch { + val settingsStore = SettingsStore(context) + val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2) + val profileNames = settingsStore.profileNames.first() + val profileName = vpnProfileDisplayName(activeProfile, profileNames) + + appWidgetIds.forEach { appWidgetId -> + val views = RemoteViews(context.packageName, R.layout.vpn_widget_compact) + views.setInt( + R.id.compact_widget_toggle, + "setBackgroundResource", + if (running) R.drawable.bg_widget_button_active else R.drawable.bg_widget_button_inactive + ) + views.setTextViewText(R.id.compact_widget_profile, profileName) + + val toggleIntent = Intent(context, VpnWidgetProvider::class.java).apply { + action = VpnWidgetProvider.ACTION_WIDGET_TOGGLE + } + val togglePendingIntent = PendingIntent.getBroadcast( + context, + appWidgetId + 20_000, + toggleIntent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + views.setOnClickPendingIntent(R.id.compact_widget_container, togglePendingIntent) + views.setOnClickPendingIntent(R.id.compact_widget_toggle, togglePendingIntent) + + appWidgetManager.updateAppWidget(appWidgetId, views) + } + } + } +} diff --git a/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt b/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt index aeb0129..6934569 100644 --- a/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt +++ b/app/src/main/java/com/wdtt/plus/VpnWidgetProvider.kt @@ -14,6 +14,7 @@ import android.widget.Toast import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch class VpnWidgetProvider : AppWidgetProvider() { @@ -35,13 +36,26 @@ class VpnWidgetProvider : AppWidgetProvider() { context.sendBroadcast(intent) } } + VpnCompactWidgetProvider.updateAllWidgets(context) } } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { val running = TunnelManager.running.value - for (appWidgetId in appWidgetIds) { - updateWidgetState(context, appWidgetManager, appWidgetId, running) + scope.launch { + val settingsStore = SettingsStore(context) + val activeProfile = settingsStore.activeProfile.first().coerceIn(0, 2) + val profileNames = settingsStore.profileNames.first() + for (appWidgetId in appWidgetIds) { + updateWidgetState( + context = context, + appWidgetManager = appWidgetManager, + appWidgetId = appWidgetId, + running = running, + activeProfile = activeProfile, + profileNames = profileNames + ) + } } } @@ -93,13 +107,17 @@ class VpnWidgetProvider : AppWidgetProvider() { context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int, - running: Boolean + running: Boolean, + activeProfile: Int, + profileNames: List ) { val views = RemoteViews(context.packageName, R.layout.vpn_widget) // Обновляем текст статуса и неоновую иконку кнопки if (running) { - views.setTextViewText(R.id.widget_status, "Подключено") + val profileName = vpnProfileDisplayName(activeProfile, profileNames) + val status = "Подключено к $profileName" + views.setTextViewText(R.id.widget_status, status) views.setTextColor(R.id.widget_status, 0xFF00E5FF.toInt()) // Неоновый голубой views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_active) } else { diff --git a/app/src/main/java/com/wdtt/plus/WdttApplication.kt b/app/src/main/java/com/wdtt/plus/WdttApplication.kt index a080bd8..c60c93b 100644 --- a/app/src/main/java/com/wdtt/plus/WdttApplication.kt +++ b/app/src/main/java/com/wdtt/plus/WdttApplication.kt @@ -8,6 +8,7 @@ import com.wireguard.android.backend.Tunnel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.combine import kotlinx.coroutines.launch class WdttApplication : Application() { @@ -35,10 +36,16 @@ class WdttApplication : Application() { } } - // Реактивно обновляем все виджеты на домашнем экране при изменении состояния туннеля + val settingsStore = SettingsStore(this) + + // Реактивно обновляем виджеты при изменении туннеля, активного профиля или его названия. CoroutineScope(SupervisorJob() + Dispatchers.Main).launch { try { - TunnelManager.running.collect { + combine( + TunnelManager.running, + settingsStore.activeProfile, + settingsStore.profileNames + ) { _, _, _ -> Unit }.collect { VpnWidgetProvider.updateAllWidgets(this@WdttApplication) } } catch (e: Exception) { @@ -47,7 +54,6 @@ class WdttApplication : Application() { } // Реактивно отслеживаем флаг логирования - val settingsStore = SettingsStore(this) CoroutineScope(SupervisorJob() + Dispatchers.Main).launch { try { settingsStore.loggingEnabled.collect { enabled -> diff --git a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt index 757b333..b6550ca 100644 --- a/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/DeployTab.kt @@ -1,9 +1,12 @@ package com.wdtt.plus.ui +import android.content.ClipData +import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build +import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility @@ -21,9 +24,11 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.HelpOutline import androidx.compose.material.icons.filled.CheckCircle import androidx.compose.material.icons.filled.CloudUpload import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.Key @@ -58,6 +63,7 @@ import com.wdtt.plus.ServerAdminTarget import com.wdtt.plus.SettingsStore import com.wdtt.plus.TunnelManager import com.wdtt.plus.WDTTColors +import com.wdtt.plus.vpnProfileRestorableName import com.wdtt.plus.vpnProfileDisplayName import com.wdtt.plus.vpnProfileTransferName import kotlinx.coroutines.Dispatchers @@ -791,7 +797,8 @@ fun DeployTab( sni = savedSni, noDns = savedNoDns, dtlsPort = if (savedManualPorts) savedServerDtlsPort else 56000, - wgPort = if (savedManualPorts) savedServerWgPort else 56001 + wgPort = if (savedManualPorts) savedServerWgPort else 56001, + profileName = vpnProfileTransferName(activeProfile, profileNames) ) fun currentOutboundProfileForms(): OutboundProfileForms = OutboundProfileForms( @@ -864,6 +871,9 @@ fun DeployTab( ) settingsStore.saveDeploy(ip.trim(), effectiveLogin, password, savedSshPort.ifBlank { "22" }, connection.dns1, connection.dns2) settingsStore.saveWdttLinkMode(false) + vpnProfileRestorableName(normalizedProfile.profileName) + .takeIf { it.isNotBlank() } + ?.let { settingsStore.saveProfileName(activeProfile, it) } existingConnectStatus = when (source) { OwnerProfileSource.Server -> "Готово: данные восстановлены с сервера в приложение. Сервер не изменялся. Адрес: ${connection.host}; порты: ${ports.first}, ${ports.second}, ${ports.third}." @@ -1207,18 +1217,11 @@ fun DeployTab( .verticalScroll(deployScrollState), verticalArrangement = Arrangement.spacedBy(12.dp) ) { - Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text( - "Настройки сервера", - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurface - ) - Text( - "(${vpnProfileDisplayName(activeProfile, profileNames)})", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } + Text( + "Настройки сервера (${vpnProfileDisplayName(activeProfile, profileNames)})", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface + ) val importCanProvideMainPassword = selectedImportMode == ServerImportMode.Replace && selectedImportBackup?.mainPassword?.isNotBlank() == true @@ -6200,7 +6203,8 @@ private fun buildOwnerProfile( sni: String, noDns: Boolean, dtlsPort: Int, - wgPort: Int + wgPort: Int, + profileName: String = "" ): ServerAdminProfileInfo { val safeListenPort = listenPort.coerceIn(1, 65535) val ports = Triple( @@ -6211,6 +6215,7 @@ private fun buildOwnerProfile( return ServerAdminProfileInfo( vkHashes = vkHashes.trim(), secondaryVkHash = secondaryVkHash.trim(), + profileName = vpnProfileRestorableName(profileName), workersPerHash = workersPerHash.coerceIn(1, 128), protocol = protocol.trim().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp", listenPort = safeListenPort, @@ -6236,6 +6241,7 @@ private fun parseOwnerProfileFromDb(json: JSONObject?, defaultPorts: String): Se return ServerAdminProfileInfo( vkHashes = json?.optString("vk_hashes", "").orEmpty().trim(), secondaryVkHash = json?.optString("secondary_vk_hash", "").orEmpty().trim(), + profileName = vpnProfileRestorableName(json?.optString("profile_name", "").orEmpty()), workersPerHash = (json?.optInt("workers_per_hash", 16) ?: 16).coerceIn(1, 128), protocol = json?.optString("protocol", "udp").orEmpty().lowercase().takeIf { it == "udp" || it == "tcp" } ?: "udp", listenPort = listenPort, @@ -6256,6 +6262,7 @@ private fun ServerAdminProfileInfo.effectivePorts(fallback: Triple + local.comparableOwnerProfile().let { localComparable -> + serverComparable.copy(profileName = "") != localComparable.copy(profileName = "") || + (serverComparable.profileName.isNotBlank() && serverComparable.profileName != localComparable.profileName) + } + } private fun ownerProfileDiffLines(server: ServerAdminProfileInfo, local: ServerAdminProfileInfo): List { val serverComparable = server.comparableOwnerProfile() @@ -6291,6 +6304,9 @@ private fun ownerProfileDiffLines(server: ServerAdminProfileInfo, local: ServerA if (serverComparable.secondaryVkHash != localComparable.secondaryVkHash) { lines += "Резервный VK-хеш: сервер — ${secretPresenceLabel(serverComparable.secondaryVkHash)}, приложение — ${secretPresenceLabel(localComparable.secondaryVkHash)}" } + if (serverComparable.profileName.isNotBlank() && serverComparable.profileName != localComparable.profileName) { + lines += "Название профиля: сервер — ${serverComparable.profileName.ifBlank { "стандартное" }}, приложение — ${localComparable.profileName.ifBlank { "стандартное" }}" + } if (serverComparable.workersPerHash != localComparable.workersPerHash) { lines += "Потоки на хеш: сервер — ${serverComparable.workersPerHash}, приложение — ${localComparable.workersPerHash}" } @@ -7177,6 +7193,7 @@ fun DeploySecretsDialog( var passInput by rememberSaveable { mutableStateOf(initialMainPass) } var adminIdInput by rememberSaveable { mutableStateOf(initialAdminId) } var botTokenInput by rememberSaveable { mutableStateOf(initialBotToken) } + var showTelegramBotHelp by rememberSaveable { mutableStateOf(false) } var passInputFocused by remember { mutableStateOf(false) } var botTokenFocused by remember { mutableStateOf(false) } var sshPortInput by rememberSaveable { mutableStateOf(if (initialSshPort.isBlank()) "22" else initialSshPort) } @@ -7262,7 +7279,30 @@ fun DeploySecretsDialog( Spacer(Modifier.height(16.dp)) HorizontalDivider() Spacer(Modifier.height(8.dp)) - Text("Телеграм бот для управления", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold) + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Text( + "Telegram-бот для управления", + color = MaterialTheme.colorScheme.primary, + fontWeight = FontWeight.SemiBold, + style = MaterialTheme.typography.titleSmall, + modifier = Modifier.weight(1f) + ) + IconButton( + onClick = { showTelegramBotHelp = true }, + modifier = Modifier.size(36.dp) + ) { + Icon( + Icons.AutoMirrored.Filled.HelpOutline, + contentDescription = "Как создать и подключить Telegram-бота", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp) + ) + } + } Text( "Можно оставить пустым, если бот не нужен. При подключении без установки приложение проверяет SSH-доступ и главный пароль, а Telegram-поля читает с сервера и подставляет автоматически.", style = MaterialTheme.typography.bodySmall, @@ -7274,7 +7314,7 @@ fun DeploySecretsDialog( value = adminIdInput, onValueChange = { adminIdInput = it }, label = { Text("ID Админа (опционально)") }, - placeholder = { Text("ID из @getmyid_bot") }, + placeholder = { Text("ID из @userinfobot") }, singleLine = true, modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp), @@ -7464,6 +7504,169 @@ fun DeploySecretsDialog( } } } + + if (showTelegramBotHelp) { + TelegramBotHelpDialog(onDismiss = { showTelegramBotHelp = false }) + } +} + +@Composable +private fun TelegramBotHelpDialog(onDismiss: () -> Unit) { + val context = LocalContext.current + + fun openTelegramBot(username: String, miniApp: Boolean = false) { + val tgUri = if (miniApp) { + "tg://resolve?domain=$username&startapp=" + } else { + "tg://resolve?domain=$username" + } + val webUri = if (miniApp) { + "https://t.me/$username?startapp" + } else { + "https://t.me/$username" + } + val tgIntent = Intent(Intent.ACTION_VIEW, Uri.parse(tgUri)).apply { + addCategory(Intent.CATEGORY_BROWSABLE) + } + val webIntent = Intent(Intent.ACTION_VIEW, Uri.parse(webUri)).apply { + addCategory(Intent.CATEGORY_BROWSABLE) + } + val intent = if (tgIntent.resolveActivity(context.packageManager) != null) tgIntent else webIntent + runCatching { + context.startActivity(intent) + }.onFailure { + Toast.makeText(context, "Не удалось открыть Telegram", Toast.LENGTH_SHORT).show() + } + } + + fun copyTelegramHandle(handle: String) { + val clipboard = context.getSystemService(ClipboardManager::class.java) + clipboard?.setPrimaryClip(ClipData.newPlainText("Telegram", handle)) + Toast.makeText(context, "$handle скопирован", Toast.LENGTH_SHORT).show() + } + + androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) { + BoxWithConstraints( + modifier = Modifier.fillMaxSize().padding(8.dp), + contentAlignment = Alignment.Center + ) { + Surface( + modifier = Modifier.heightIn(max = maxHeight * 0.92f), + shape = RoundedCornerShape(24.dp), + color = MaterialTheme.colorScheme.surface, + contentColor = MaterialTheme.colorScheme.onSurface, + tonalElevation = 8.dp + ) { + Column( + modifier = Modifier + .padding(22.dp) + .fillMaxWidth() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + "Подключение Telegram-бота", + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.weight(1f) + ) + IconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + + Text( + "1. Откройте мини-приложение BotFather и создайте бота без ручной отправки команд. Если мини-приложение недоступно в вашей версии Telegram, откройте обычный чат @BotFather, нажмите «Запустить» и отправьте /newbot. Задайте имя и username, который заканчивается на bot, затем скопируйте выданный токен.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + TelegramBotActionRow( + buttonText = "Мини-приложение BotFather", + handle = "@BotFather", + onOpen = { openTelegramBot("BotFather", miniApp = true) }, + onCopy = { copyTelegramHandle("@BotFather") } + ) + TelegramBotActionRow( + buttonText = "Обычный чат @BotFather", + handle = "@BotFather", + onOpen = { openTelegramBot("BotFather") }, + onCopy = { copyTelegramHandle("@BotFather") } + ) + + Text( + "2. Откройте @userinfobot, нажмите «Запустить» и скопируйте свой числовой Telegram ID.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + TelegramBotActionRow( + buttonText = "Открыть @userinfobot", + handle = "@userinfobot", + onOpen = { openTelegramBot("userinfobot") }, + onCopy = { copyTelegramHandle("@userinfobot") } + ) + + Text( + "3. Вставьте ID в поле администратора, токен — в поле бота и нажмите «Сохранить». Чтобы передать эти данные серверу, выполните установку во вкладке «Деплой» — при обновлении сервера можно выбрать установку с сохранением данных.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + Text( + "Токен даёт доступ к управлению ботом. Не отправляйте его другим людям и не публикуйте; при утечке перевыпустите токен через @BotFather.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + + Button( + onClick = onDismiss, + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + Text("Понятно", fontWeight = FontWeight.Bold) + } + } + } + } + } +} + +@Composable +private fun TelegramBotActionRow( + buttonText: String, + handle: String, + onOpen: () -> Unit, + onCopy: () -> Unit +) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + OutlinedButton( + onClick = onOpen, + modifier = Modifier + .weight(1f) + .heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + Text(buttonText, textAlign = TextAlign.Center) + } + FilledTonalIconButton( + onClick = onCopy, + modifier = Modifier.size(48.dp) + ) { + Icon( + Icons.Default.ContentCopy, + contentDescription = "Скопировать $handle", + modifier = Modifier.size(20.dp) + ) + } + } } @OptIn(ExperimentalMaterial3Api::class) diff --git a/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt b/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt new file mode 100644 index 0000000..79773b6 --- /dev/null +++ b/app/src/main/java/com/wdtt/plus/ui/DeviceCompatibilityDialog.kt @@ -0,0 +1,300 @@ +package com.wdtt.plus.ui + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +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.CheckCircle +import androidx.compose.material.icons.filled.Close +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.Error +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.Warning +import androidx.compose.material3.Button +import androidx.compose.material3.FilledTonalIconButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import com.wdtt.plus.DeviceCheckAction +import com.wdtt.plus.DeviceCheckItem +import com.wdtt.plus.DeviceCheckSeverity +import com.wdtt.plus.DeviceCompatibilityReport +import com.wdtt.plus.label + +@Composable +fun DeviceCompatibilityDialog( + report: DeviceCompatibilityReport, + title: String, + subtitle: String, + note: String, + onDismiss: () -> Unit, + onCopy: (() -> Unit)? = null, + onAction: ((DeviceCheckAction) -> Unit)? = null +) { + val visibleItems = remember(report) { + report.items.ifEmpty { + listOf( + DeviceCheckItem( + title = "Проверка устройства", + status = "замечаний нет", + details = "Архитектурных проблем для запуска WDTT Plus не найдено.", + severity = DeviceCheckSeverity.Ok + ) + ) + } + } + + Dialog( + onDismissRequest = onDismiss, + properties = DialogProperties(usePlatformDefaultWidth = false) + ) { + BoxWithConstraints( + modifier = Modifier + .fillMaxSize() + .padding(8.dp), + contentAlignment = Alignment.Center + ) { + Surface( + shape = RoundedCornerShape(28.dp), + color = MaterialTheme.colorScheme.surface, + tonalElevation = 8.dp, + shadowElevation = 18.dp, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp) + .heightIn(max = maxHeight * 0.92f) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(14.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + title, + modifier = Modifier.weight(1f), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + FilledTonalIconButton(onClick = onDismiss) { + Icon(Icons.Default.Close, contentDescription = "Закрыть") + } + } + + Surface( + shape = RoundedCornerShape(20.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.46f), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f)) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(14.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + val summarySeverity = if (report.hasErrors) { + DeviceCheckSeverity.Error + } else if (report.problemItems.isNotEmpty()) { + DeviceCheckSeverity.Warning + } else { + DeviceCheckSeverity.Ok + } + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.Top + ) { + Icon( + imageVector = when (summarySeverity) { + DeviceCheckSeverity.Error -> Icons.Default.Error + DeviceCheckSeverity.Warning -> Icons.Default.Warning + else -> Icons.Default.CheckCircle + }, + contentDescription = null, + tint = severityColor(summarySeverity), + modifier = Modifier + .padding(top = 2.dp) + .size(22.dp) + ) + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { + Text( + "Итог: ${report.overallStatus}", + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 18.sp + ) + } + } + Text( + note, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 18.sp + ) + } + } + + visibleItems.forEach { item -> + DeviceCheckItemCard(item = item, onAction = onAction) + } + + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + if (onCopy != null) { + OutlinedButton( + onClick = onCopy, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth() + ) { + Icon(Icons.Default.ContentCopy, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(modifier = Modifier.size(8.dp)) + Text("Скопировать") + } + } + Button( + onClick = onDismiss, + shape = RoundedCornerShape(16.dp), + modifier = Modifier.fillMaxWidth() + ) { + Text("Понятно", fontWeight = FontWeight.Bold) + } + } + Spacer(modifier = Modifier.height(2.dp)) + } + } + } + } +} + +@Composable +private fun DeviceCheckItemCard( + item: DeviceCheckItem, + onAction: ((DeviceCheckAction) -> Unit)? +) { + val color = severityColor(item.severity) + Surface( + shape = RoundedCornerShape(22.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.38f), + border = BorderStroke(1.dp, color.copy(alpha = 0.32f)) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(14.dp), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(10.dp), + verticalAlignment = Alignment.Top + ) { + Icon( + imageVector = severityIcon(item.severity), + contentDescription = null, + tint = color, + modifier = Modifier + .padding(top = 2.dp) + .size(20.dp) + ) + Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + item.title, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + item.status, + style = MaterialTheme.typography.bodySmall, + color = color, + fontWeight = FontWeight.SemiBold + ) + } + } + + Text( + item.details, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 18.sp + ) + if (item.recommendation.isNotBlank()) { + Text( + item.recommendation, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurface, + lineHeight = 18.sp, + fontWeight = FontWeight.Medium + ) + } + if (item.action != null && onAction != null) { + TextButton( + onClick = { onAction(item.action) }, + shape = RoundedCornerShape(14.dp) + ) { + Icon(Icons.Default.Settings, contentDescription = null, modifier = Modifier.size(17.dp)) + Spacer(modifier = Modifier.size(7.dp)) + Text(item.action.label()) + } + } + } + } +} + +@Composable +private fun severityColor(severity: DeviceCheckSeverity): Color = when (severity) { + DeviceCheckSeverity.Ok -> Color(0xFF4CAF50) + DeviceCheckSeverity.Info -> MaterialTheme.colorScheme.primary + DeviceCheckSeverity.Warning -> Color(0xFFFFA000) + DeviceCheckSeverity.Error -> MaterialTheme.colorScheme.error +} + +private fun severityIcon(severity: DeviceCheckSeverity): ImageVector = when (severity) { + DeviceCheckSeverity.Ok -> Icons.Default.CheckCircle + DeviceCheckSeverity.Info -> Icons.Default.Info + DeviceCheckSeverity.Warning -> Icons.Default.Warning + DeviceCheckSeverity.Error -> Icons.Default.Error +} diff --git a/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt b/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt index 797ae7e..8c7a4cf 100644 --- a/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/ExceptionsTab.kt @@ -1,6 +1,11 @@ package com.wdtt.plus.ui import android.content.pm.PackageManager +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInVertically +import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.isSystemInDarkTheme @@ -32,6 +37,8 @@ import com.wdtt.plus.SettingsStore import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -201,161 +208,204 @@ fun ExceptionsTab( } } + val listState = rememberRememberedLazyListState( + firstVisibleItemIndex, + firstVisibleItemScrollOffset + ) + var topBlockVisible by rememberSaveable { mutableStateOf(true) } + + LaunchedEffect(listState) { + var previousIndex = listState.firstVisibleItemIndex + var previousOffset = listState.firstVisibleItemScrollOffset + + snapshotFlow { + Triple( + listState.firstVisibleItemIndex, + listState.firstVisibleItemScrollOffset, + listState.isScrollInProgress + ) + } + .distinctUntilChanged() + .filter { it.third } + .collect { (index, offset, _) -> + val scrollingDown = index > previousIndex || + (index == previousIndex && offset > previousOffset) + val scrollingUp = index < previousIndex || + (index == previousIndex && offset < previousOffset) + + if (scrollingDown) { + topBlockVisible = false + } else if (scrollingUp || (index == 0 && offset == 0)) { + topBlockVisible = true + } + + previousIndex = index + previousOffset = offset + } + } + Column(modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp)) { - // Header - Text( - "Маршрутизация приложений", - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurface, - modifier = Modifier.padding(top = 16.dp, bottom = 4.dp) - ) + AnimatedVisibility( + visible = topBlockVisible, + enter = slideInVertically(initialOffsetY = { -it }) + fadeIn(), + exit = slideOutVertically(targetOffsetY = { -it }) + fadeOut() + ) { + Column { + // Header + Text( + "Маршрутизация приложений", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(top = 16.dp, bottom = 4.dp) + ) + + Spacer(modifier = Modifier.height(12.dp)) + + // Mode Toggle + AppSectionCard( + modifier = Modifier.padding(bottom = 12.dp), + contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(0.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) { + Text( + "Режим списка", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + fontSize = 14.sp, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + if (isWhitelist) "БС: только отмеченные — через VPN" + else "ЧС: отмеченные — без VPN", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 11.sp, + lineHeight = 14.sp + ) + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + ModeChip("ЧС", !isWhitelist) { + if (isWhitelist) { + scope.launch { + settingsStore.saveIsWhitelist(false) + scheduleWireGuardReload() + } + } + } + ModeChip("БС", isWhitelist) { + if (!isWhitelist) { + scope.launch { + settingsStore.saveIsWhitelist(true) + scheduleWireGuardReload() + } + } + } + } + } + + HorizontalDivider( + modifier = Modifier.padding(vertical = 12.dp), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) + ) + + Row( + modifier = Modifier.fillMaxWidth(), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween + ) { + Text( + "Показывать системные", + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + fontSize = 14.sp, + color = MaterialTheme.colorScheme.onSurface + ) + Switch( + checked = showSystemAppsOpt ?: false, + onCheckedChange = { enabled -> + scope.launch { + settingsStore.saveShowSystemApps(enabled) + } + } + ) + } + + if (!isWhitelist) { + Spacer(modifier = Modifier.height(12.dp)) + OutlinedButton( + onClick = { + val detectedPackages = appsList + .filter { it.matchesVpnDetectionApp() } + .map { it.packageName } + .toSet() + if (detectedPackages.isEmpty()) { + quickExcludeStatus = "Подходящие приложения не найдены." + } else { + scope.launch { + val addedCount = settingsStore.addBlacklistPackages(detectedPackages) + quickExcludeStatus = "Исключено: ${detectedPackages.size}, добавлено: $addedCount." + scheduleWireGuardReload() + } + } + }, + enabled = !isLoading && appsList.isNotEmpty(), + modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), + shape = RoundedCornerShape(16.dp) + ) { + Icon(Icons.Default.Search, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text( + "Быстрые исключения", + fontWeight = FontWeight.SemiBold, + textAlign = TextAlign.Center, + modifier = Modifier.weight(1f) + ) + } + Text( + "Банки, маркетплейсы и другие приложения, чувствительные к VPN. Поиск выполняется по известным названиям.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp) + ) + if (quickExcludeStatus.isNotBlank()) { + Text( + quickExcludeStatus, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 6.dp) + ) + } + } + } + } + } // Search Bar OutlinedTextField( value = searchQuery, onValueChange = { searchQuery = it }, placeholder = { Text("Поиск приложений...", fontSize = 14.sp) }, - modifier = Modifier.fillMaxWidth().padding(top = 12.dp).height(52.dp), + modifier = Modifier + .fillMaxWidth() + .padding(top = if (topBlockVisible) 0.dp else 16.dp, bottom = 12.dp) + .height(52.dp), shape = RoundedCornerShape(16.dp), leadingIcon = { Icon(Icons.Default.Search, null, modifier = Modifier.size(20.dp)) }, singleLine = true, ) - Spacer(modifier = Modifier.height(14.dp)) - - // Mode Toggle - AppSectionCard( - modifier = Modifier.padding(bottom = 12.dp), - contentPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(0.dp) - ) { - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween - ) { - Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) { - Text( - "Режим списка", - style = MaterialTheme.typography.bodyMedium, - fontWeight = FontWeight.Medium, - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurface - ) - Text( - if (isWhitelist) "БС: только отмеченные — через VPN" - else "ЧС: отмеченные — без VPN", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - fontSize = 11.sp, - lineHeight = 14.sp - ) - } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - ModeChip("ЧС", !isWhitelist) { - if (isWhitelist) { - scope.launch { - settingsStore.saveIsWhitelist(false) - scheduleWireGuardReload() - } - } - } - ModeChip("БС", isWhitelist) { - if (!isWhitelist) { - scope.launch { - settingsStore.saveIsWhitelist(true) - scheduleWireGuardReload() - } - } - } - } - } - - HorizontalDivider( - modifier = Modifier.padding(vertical = 12.dp), - color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) - ) - - Row( - modifier = Modifier.fillMaxWidth(), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.SpaceBetween - ) { - Text( - "Показывать системные", - style = MaterialTheme.typography.bodyMedium, - fontWeight = FontWeight.Medium, - fontSize = 14.sp, - color = MaterialTheme.colorScheme.onSurface - ) - Switch( - checked = showSystemAppsOpt ?: false, - onCheckedChange = { enabled -> - scope.launch { - settingsStore.saveShowSystemApps(enabled) - } - } - ) - } - - if (!isWhitelist) { - Spacer(modifier = Modifier.height(12.dp)) - OutlinedButton( - onClick = { - val detectedPackages = appsList - .filter { it.matchesVpnDetectionApp() } - .map { it.packageName } - .toSet() - if (detectedPackages.isEmpty()) { - quickExcludeStatus = "Подходящие приложения не найдены." - } else { - scope.launch { - val addedCount = settingsStore.addBlacklistPackages(detectedPackages) - quickExcludeStatus = "Исключено: ${detectedPackages.size}, добавлено: $addedCount." - scheduleWireGuardReload() - } - } - }, - enabled = !isLoading && appsList.isNotEmpty(), - modifier = Modifier.fillMaxWidth().heightIn(min = 48.dp), - shape = RoundedCornerShape(16.dp) - ) { - Icon(Icons.Default.Search, contentDescription = null, modifier = Modifier.size(18.dp)) - Spacer(Modifier.width(8.dp)) - Text( - "Быстрые исключения", - fontWeight = FontWeight.SemiBold, - textAlign = TextAlign.Center, - modifier = Modifier.weight(1f) - ) - } - Text( - "Банки, маркетплейсы и другие приложения, чувствительные к VPN. Поиск выполняется по известным названиям.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 6.dp) - ) - if (quickExcludeStatus.isNotBlank()) { - Text( - quickExcludeStatus, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 6.dp) - ) - } - } - } - // List if (isLoading || showSystemAppsOpt == null) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator() } } else { - val listState = rememberRememberedLazyListState( - firstVisibleItemIndex, - firstVisibleItemScrollOffset - ) if (filteredApps.isEmpty()) { Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text( 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 d69fa70..8aa4685 100644 --- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt @@ -2,13 +2,23 @@ package com.wdtt.plus.ui import androidx.compose.runtime.MutableState +import android.app.ActivityManager import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent +import android.content.pm.PackageManager +import android.net.ConnectivityManager +import android.net.NetworkCapabilities import android.net.Uri +import android.net.VpnService import android.os.Build +import android.os.PowerManager +import android.os.StatFs import android.provider.Settings +import android.system.Os +import android.system.OsConstants +import android.webkit.WebView import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts @@ -92,8 +102,11 @@ import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.wdtt.plus.BuildConfig +import com.wdtt.plus.DeviceCheckAction +import com.wdtt.plus.DeviceCompatibility import com.wdtt.plus.R import com.wdtt.plus.SettingsStore +import com.wdtt.plus.TunnelManager import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE import com.wdtt.plus.WDTTColors @@ -104,9 +117,19 @@ 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.selectUpdateApkAsset +import com.wdtt.plus.deviceCheckActionIntent +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import java.io.File +import java.security.MessageDigest +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.TimeZone import kotlin.math.PI import kotlin.math.cos import kotlin.math.min @@ -175,6 +198,23 @@ private fun openUrlInBrowser(context: Context, url: String) { } } +private fun openDeviceCheckAction(context: Context, action: DeviceCheckAction) { + runCatching { + val intent = deviceCheckActionIntent(context, action) + if (intent.resolveActivity(context.packageManager) != null) { + context.startActivity(intent) + } else { + context.startActivity( + Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { + data = Uri.parse("package:${context.packageName}") + } + ) + } + }.onFailure { + Toast.makeText(context, "Не удалось открыть настройки Android", Toast.LENGTH_SHORT).show() + } +} + @Composable fun InfoTab( actionsExpandedState: MutableState = rememberSaveable { mutableStateOf(true) }, @@ -198,6 +238,8 @@ fun InfoTab( var pendingUpdateApkPath by rememberSaveable { mutableStateOf(null) } var showHelpDialog by remember { mutableStateOf(false) } var showSupportDialog by remember { mutableStateOf(false) } + var isCheckingDevice by remember { mutableStateOf(false) } + var deviceCheckReport by remember { mutableStateOf(null) } var actionsExpanded by actionsExpandedState var projectExpanded by projectExpandedState val updateLatestVersion by settingsStore.updateLatestVersion.collectAsStateWithLifecycle(initialValue = "") @@ -256,6 +298,33 @@ fun InfoTab( } } + suspend fun buildDeviceCheckReportWithVersion(): com.wdtt.plus.DeviceCompatibilityReport { + val latestCheckedAt = System.currentTimeMillis() + val latestRelease = fetchLatestReleaseInfo(currentVersion) + settingsStore.saveUpdateState( + lastCheckAt = latestCheckedAt, + latestVersion = latestRelease?.versionTag ?: "", + error = if (latestRelease == null) "Не удалось проверить" else "" + ) + val versionItem = DeviceCompatibility.appVersionItem( + currentVersion = currentVersion, + releaseDate = releaseDate, + latestRelease = latestRelease + ) + val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull() + val report = withContext(Dispatchers.Default) { + DeviceCompatibility.check( + context = context.applicationContext, + includeRuntimeChecks = true, + workersPerHash = workers + ) + } + return report.copy( + items = listOf(versionItem) + + report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE } + ) + } + Column( modifier = Modifier .fillMaxSize() @@ -285,7 +354,7 @@ fun InfoTab( ExpandableSectionCard( title = "Действия", - itemCount = "4 пункта", + itemCount = "5 пунктов", expanded = actionsExpanded, modifier = Modifier.onGloballyPositioned { actionsSectionY = it.positionInParent().y }, onToggle = { @@ -323,11 +392,16 @@ fun InfoTab( WideActionTile( title = "Собрать отчёт", - subtitle = "Android, ABI, версия, устройство", + subtitle = "Android, ABI, память, сеть и компоненты", onClick = { - val clipboard = context.getSystemService(ClipboardManager::class.java) - clipboard?.setPrimaryClip(ClipData.newPlainText("WDTT Report", buildSupportReport())) - Toast.makeText(context, "Отчёт сформирован и скопирован", Toast.LENGTH_SHORT).show() + 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( @@ -339,6 +413,41 @@ fun InfoTab( } ) + WideActionTile( + title = "Проверить устройство", + subtitle = if (isCheckingDevice) { + "Проверяем версию, Android, ABI и системные условия..." + } else { + "Версия, совместимость, ABI, native, WebView и настройки" + }, + onClick = { + if (isCheckingDevice) return@WideActionTile + isCheckingDevice = true + scope.launch { + runCatching { + buildDeviceCheckReportWithVersion() + }.onSuccess { report -> + deviceCheckReport = report + }.onFailure { error -> + Toast.makeText( + context, + error.message ?: "Не удалось проверить устройство", + Toast.LENGTH_LONG + ).show() + } + isCheckingDevice = false + } + }, + icon = { + Icon( + imageVector = Icons.Default.Info, + contentDescription = null, + modifier = Modifier.size(20.dp), + tint = MaterialTheme.colorScheme.onPrimaryContainer + ) + } + ) + WideActionTile( title = "Справка", subtitle = "Коротко про VPN, исключения, капчу и запуск", @@ -561,6 +670,29 @@ fun InfoTab( } if (showHelpDialog) ImportantInfoDialog(onDismiss = { showHelpDialog = false }) + deviceCheckReport?.let { report -> + DeviceCompatibilityDialog( + report = report, + title = "Проверка устройства", + subtitle = "Расширенная проверка не запускает VPN, но показывает совместимость устройства, настройки Android и текущее состояние туннеля.", + note = "Здесь проверяется всё, что можно проверить без тестового подключения: VPN-разрешение, активен ли туннель сейчас, сеть, WebView, батарея, установка APK и базовая совместимость устройства.", + onDismiss = { deviceCheckReport = null }, + onCopy = { + scope.launch { + val freshReport = runCatching { + buildDeviceCheckReportWithVersion() + }.getOrElse { + report + } + 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() + } + }, + onAction = { action -> openDeviceCheckAction(context, action) } + ) + } if (showSupportDialog) { SupportProjectDialog( onDismiss = { showSupportDialog = false }, @@ -1131,7 +1263,13 @@ private fun ProjectLinkRow( } } -private fun buildSupportReport(): String { +private fun diagnosticText(block: () -> Any?): String = + runCatching { block()?.toString()?.takeIf(String::isNotBlank) ?: "недоступно" } + .getOrDefault("недоступно") + +private fun formatMiB(bytes: Long): String = "${bytes.coerceAtLeast(0L) / (1024L * 1024L)} МБ" + +private suspend fun buildSupportReport(context: Context, settingsStore: SettingsStore): String { val androidVersion = Build.VERSION.RELEASE ?: "?" val sdkInt = Build.VERSION.SDK_INT val primaryAbi = Build.SUPPORTED_ABIS.firstOrNull().orEmpty().ifBlank { "unknown" } @@ -1158,15 +1296,168 @@ private fun buildSupportReport(): String { "n/a" } + val appInfo = runCatching { context.applicationInfo }.getOrNull() + val packageInfo = runCatching { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.getPackageInfo( + context.packageName, + PackageManager.PackageInfoFlags.of(PackageManager.GET_SIGNING_CERTIFICATES.toLong()) + ) + } else { + @Suppress("DEPRECATION") + context.packageManager.getPackageInfo( + context.packageName, + PackageManager.GET_SIGNING_CERTIFICATES + ) + } + }.getOrNull() + val signingCertificate = diagnosticText { + val certificate = packageInfo?.signingInfo?.apkContentsSigners?.firstOrNull()?.toByteArray() + ?: return@diagnosticText null + MessageDigest.getInstance("SHA-256") + .digest(certificate) + .joinToString("") { "%02x".format(it) } + } + val installSource = diagnosticText { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + context.packageManager.getInstallSourceInfo(context.packageName).installingPackageName + } else { + @Suppress("DEPRECATION") + context.packageManager.getInstallerPackageName(context.packageName) + } ?: "ручная установка" + } + val dateFormat = SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.ROOT) + val firstInstallTime = diagnosticText { packageInfo?.firstInstallTime?.let { dateFormat.format(Date(it)) } } + val lastUpdateTime = diagnosticText { packageInfo?.lastUpdateTime?.let { dateFormat.format(Date(it)) } } + val processBits = diagnosticText { if (android.os.Process.is64Bit()) "64-bit" else "32-bit" } + val pageSize = diagnosticText { "${Os.sysconf(OsConstants._SC_PAGESIZE)} байт" } + val securityPatch = Build.VERSION.SECURITY_PATCH.orEmpty().ifBlank { "unknown" } + val kernel = diagnosticText { System.getProperty("os.version") } + + val activityManager = runCatching { + context.getSystemService(ActivityManager::class.java) + }.getOrNull() + val memoryInfo = runCatching { + ActivityManager.MemoryInfo().also { activityManager?.getMemoryInfo(it) } + }.getOrNull() + val memorySummary = if (memoryInfo != null && memoryInfo.totalMem > 0L) { + "всего ${formatMiB(memoryInfo.totalMem)}, доступно ${formatMiB(memoryInfo.availMem)}, " + + "lowMemory=${memoryInfo.lowMemory}" + } else { + "недоступно" + } + val memoryClass = diagnosticText { + "обычный ${activityManager?.memoryClass} МБ, большой ${activityManager?.largeMemoryClass} МБ" + } + val lowRamDevice = diagnosticText { activityManager?.isLowRamDevice } + + val storageSummary = runCatching { + val stat = StatFs(context.filesDir.absolutePath) + "свободно ${formatMiB(stat.availableBytes)}, всего ${formatMiB(stat.totalBytes)}" + }.getOrDefault("недоступно") + + val powerManager = runCatching { context.getSystemService(PowerManager::class.java) }.getOrNull() + val powerSummary = diagnosticText { + "экономия=${powerManager?.isPowerSaveMode}, " + + "без ограничений батареи=${powerManager?.isIgnoringBatteryOptimizations(context.packageName)}" + } + + val connectivityManager = runCatching { + context.getSystemService(ConnectivityManager::class.java) + }.getOrNull() + val activeNetwork = runCatching { connectivityManager?.activeNetwork }.getOrNull() + val networkCapabilities = runCatching { + activeNetwork?.let { connectivityManager?.getNetworkCapabilities(it) } + }.getOrNull() + val networkTransports = buildList { + if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true) add("Wi-Fi") + if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) == true) add("мобильная") + if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) == true) add("Ethernet") + if (networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true) add("VPN") + }.joinToString().ifBlank { "не определён" } + val networkSummary = if (networkCapabilities != null) { + "$networkTransports, internet=${networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)}, " + + "validated=${networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)}, " + + "metered=${connectivityManager?.isActiveNetworkMetered}" + } else { + "недоступно" + } + val privateDns = diagnosticText { + val properties = activeNetwork?.let { connectivityManager?.getLinkProperties(it) } + properties?.isPrivateDnsActive + } + + val webViewInfo = diagnosticText { + WebView.getCurrentWebViewPackage()?.let { "${it.packageName} ${it.versionName}" } + } + val nativeClientInfo = runCatching { + val nativeClient = File(appInfo?.nativeLibraryDir.orEmpty(), "libclient.so") + if (nativeClient.isFile) { + "найден, ${formatMiB(nativeClient.length())}, executable=${nativeClient.canExecute()}" + } else { + "не найден" + } + }.getOrDefault("недоступно") + + val notificationPermission = diagnosticText { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + "не требуется до Android 13" + } else { + context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + } + } + val updateInstallPermission = diagnosticText { + context.packageManager.canRequestPackageInstalls() + } + val vpnPermission = diagnosticText { VpnService.prepare(context) == null } + val displayMetrics = context.resources.displayMetrics + val screenSummary = diagnosticText { + "${displayMetrics.widthPixels}×${displayMetrics.heightPixels}, " + + "density=${displayMetrics.densityDpi} dpi, fontScale=${context.resources.configuration.fontScale}" + } + + 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]+")) + .count { it.isNotBlank() } + .coerceAtMost(4) + val hasSecondaryHash = runCatching { settingsStore.secondaryVkHash.first().isNotBlank() }.getOrNull() + val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull() + val captchaMode = runCatching { settingsStore.captchaMode.first() }.getOrNull() + val fingerprint = runCatching { settingsStore.selectedFingerprint.first() }.getOrNull() + val linkMode = runCatching { settingsStore.wdttLinkMode.first() }.getOrNull() + val interfaceRole = runCatching { settingsStore.interfaceRole.first() }.getOrNull() + val themeMode = runCatching { settingsStore.themeMode.first() }.getOrNull() + val dynamicColor = runCatching { settingsStore.isDynamicColor.first() }.getOrNull() + val loggingEnabled = runCatching { settingsStore.loggingEnabled.first() }.getOrNull() + 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("Андроид: $androidVersion (SDK $sdkInt)") + appendLine("Версия пакета: code ${packageInfo?.longVersionCode ?: "?"}") + appendLine("Источник установки: $installSource") + appendLine("Первая установка: $firstInstallTime") + appendLine("Последнее обновление: $lastUpdateTime") + appendLine("SHA-256 сертификата: $signingCertificate") + appendLine("Android: $androidVersion (SDK $sdkInt, patch $securityPatch)") + appendLine("SDK приложения: min ${appInfo?.minSdkVersion ?: "?"}, target ${appInfo?.targetSdkVersion ?: "?"}") appendLine("Устройство: $manufacturer / $brand / $model") appendLine("Код устройства: $device") appendLine("Продукт: $product") appendLine("ABI: $primaryAbi") appendLine("Все ABI: $supportedAbis") + appendLine("Процесс: $processBits") + appendLine("Страница памяти: $pageSize") appendLine("SoC: $socManufacturer / $socModel") appendLine("Hardware: $hardware") appendLine("Board: $board") @@ -1174,5 +1465,40 @@ private fun buildSupportReport(): String { appendLine("Build ID: $buildId") appendLine("Build type: $buildType") appendLine("Fingerprint: $buildFingerprint") + appendLine("Kernel: $kernel") + appendLine("RAM: $memorySummary") + appendLine("Memory class: $memoryClass") + appendLine("Low-RAM устройство: $lowRamDevice") + appendLine("Хранилище приложения: $storageSummary") + appendLine("Питание: $powerSummary") + appendLine("Сеть: $networkSummary") + appendLine("Private DNS: $privateDns") + appendLine("WebView: $webViewInfo") + appendLine("Нативный клиент: $nativeClientInfo") + appendLine("Экран: $screenSummary") + 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("Локаль: ${diagnosticText { Locale.getDefault().toLanguageTag() }}") + appendLine("Часовой пояс: ${diagnosticText { TimeZone.getDefault().id }}") + appendLine("Туннель: запущен=${TunnelManager.running.value}, активных=${TunnelManager.activeWorkers.value}") + appendLine("Последняя проблема: $tunnelIssue") + appendLine("Профиль: ${activeProfile ?: "недоступно"}") + appendLine("Потоки: ${workers ?: "недоступно"}") + appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}") + appendLine("VKCalls: ${vkCallsEnabled ?: "недоступно"}") + appendLine("Captcha mode: ${captchaMode ?: "недоступно"}") + appendLine("TLS fingerprint: ${fingerprint ?: "недоступно"}") + appendLine("Режим ссылки: ${linkMode ?: "недоступно"}") + appendLine("Роль интерфейса: ${interfaceRole?.ifBlank { "не выбрана" } ?: "недоступно"}") + appendLine("Тема: ${themeMode ?: "недоступно"}, Dynamic Colors=${dynamicColor ?: "недоступно"}") + appendLine("Логирование: ${loggingEnabled ?: "недоступно"}") }.trim() } 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 d0c2c06..313a0f9 100644 --- a/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/LogsTab.kt @@ -5,7 +5,6 @@ import android.content.ClipboardManager import android.content.Context import android.widget.Toast import androidx.compose.animation.core.* -import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items @@ -20,6 +19,7 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.graphics.luminance import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight @@ -110,9 +110,13 @@ fun LogsTab( } } - // Logs container — адаптивный к теме - val isDark = isSystemInDarkTheme() - val terminalBg = if (isDark) WDTTColors.terminalBgDark else WDTTColors.terminalBg + // Нейтральный фон в светлой теме не спорит с цветами уровней лога. + val isDark = MaterialTheme.colorScheme.background.luminance() < 0.5f + val terminalBg = if (isDark) { + WDTTColors.terminalBgDark + } else { + MaterialTheme.colorScheme.surfaceContainerHighest + } Card( modifier = Modifier.fillMaxSize(), @@ -135,23 +139,24 @@ fun LogsTab( @Composable fun LogLine(entry: LogEntry, sessionActive: Boolean) { + val isDark = MaterialTheme.colorScheme.background.luminance() < 0.5f val activeColor = when { - entry.severity == LogSeverity.Error -> WDTTColors.terminalRed - entry.severity == LogSeverity.Warning -> WDTTColors.terminalYellow - entry.priority <= 2 -> WDTTColors.terminalGreen - entry.priority == 3 -> WDTTColors.terminalBlue - else -> WDTTColors.terminalText + entry.severity == LogSeverity.Error -> if (isDark) WDTTColors.terminalRed else MaterialTheme.colorScheme.error + entry.severity == LogSeverity.Warning -> if (isDark) WDTTColors.terminalYellow else MaterialTheme.colorScheme.tertiary + entry.priority <= 2 -> if (isDark) WDTTColors.terminalGreen else WDTTColors.onConnected + 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 color = when { sessionActive -> activeColor isStoppedStats -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.9f) - else -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.48f) + else -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.68f) } val counterColor = if (sessionActive) { WDTTColors.terminalBlue } else { - MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = if (isStoppedStats) 0.85f else 0.48f) + MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = if (isStoppedStats) 0.85f else 0.68f) } var trigger by remember { mutableIntStateOf(0) } @@ -169,7 +174,11 @@ fun LogLine(entry: LogEntry, sessionActive: Boolean) { verticalAlignment = Alignment.CenterVertically ) { Surface( - color = WDTTColors.terminalCounter.copy(alpha = 0.2f), + color = if (isDark) { + WDTTColors.terminalCounter.copy(alpha = 0.2f) + } else { + MaterialTheme.colorScheme.primaryContainer + }, shape = RoundedCornerShape(12.dp), modifier = Modifier .defaultMinSize(minWidth = 24.dp, minHeight = 24.dp) 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 26211c6..c5a2bb8 100644 --- a/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/SettingsTab.kt @@ -444,18 +444,11 @@ fun SettingsTabContent( if (!wdttLinkMode) { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { // ═══ Заголовок раздела ═══ - Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text( - "Настройки туннеля", - style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), - color = MaterialTheme.colorScheme.onSurface - ) - Text( - "(${vpnProfileDisplayName(activeProfile, profileNames)})", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant - ) - } + Text( + "Настройки туннеля (${vpnProfileDisplayName(activeProfile, profileNames)})", + style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), + color = MaterialTheme.colorScheme.onSurface + ) // ═══ Настройки туннеля ═══ AppSectionCard( diff --git a/app/src/main/res/layout/vpn_widget.xml b/app/src/main/res/layout/vpn_widget.xml index b95d9b5..aa220d6 100644 --- a/app/src/main/res/layout/vpn_widget.xml +++ b/app/src/main/res/layout/vpn_widget.xml @@ -7,25 +7,32 @@ android:padding="12dp"> + + + + + + + diff --git a/app/src/main/res/xml/vpn_widget_compact_info.xml b/app/src/main/res/xml/vpn_widget_compact_info.xml new file mode 100644 index 0000000..f99c86c --- /dev/null +++ b/app/src/main/res/xml/vpn_widget_compact_info.xml @@ -0,0 +1,8 @@ + + diff --git a/app/src/main/res/xml/vpn_widget_info.xml b/app/src/main/res/xml/vpn_widget_info.xml index 781554b..5d9ab32 100644 --- a/app/src/main/res/xml/vpn_widget_info.xml +++ b/app/src/main/res/xml/vpn_widget_info.xml @@ -1,6 +1,6 @@