Выпуск WDTT Plus v18

This commit is contained in:
Ivan4537 committed 2026-09-11 15:45:55 +03:00
1 parent abf0a0f130
commit b3935b947a
101 files changed
+16512 -1477

No files matched your search

+2 -2
View File
@@ -132,7 +132,7 @@
android:stopWithTask="false">
<property
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="persistent_vpn_tunnel_transport" />
android:value="persistent_encrypted_tunnel_transport_or_local_socks_proxy" />
</service>
<!-- SafeGoBackend retains upstream wg-go but does not probe ownership
@@ -176,7 +176,7 @@
<receiver
android:name=".VpnWidgetProvider"
android:label="WDTT Plus ВПН Виджет"
android:label="WDTT Plus — подключение"
android:exported="true">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
+19 -7
View File
@@ -2,19 +2,20 @@
# ==============================================================================
# WDTT Plus Server — Универсальный установщик для VPS
# Поддержка: Debian 11+, Ubuntu 20.04+, CentOS/RHEL/Fedora/AlmaLinux/Rocky
# Версия: 3.10 | Дата: 2026-09-04
# Версия: 3.11 | Дата: 2026-09-06
# NAT: MASQUERADE через iptables
# WG: порт 56001 (не конфликтует с существующим WG на 51820)
# DTLS: порт 56000
# ==============================================================================
set -euo pipefail
readonly SCRIPT_VERSION="3.10"
readonly SCRIPT_VERSION="3.11"
readonly WDTT_DEPLOY_CONTRACT_VERSION="1"
readonly WDTT_SERVER_VERSION="17"
readonly WDTT_SERVER_BINARY_PATH="/usr/local/bin/wdtt-server"
readonly WDTT_SYSTEMD_UNIT_PATH="/etc/systemd/system/wdtt.service"
readonly WDTT_ANDROID_DEPLOY_MARKER="Managed by WDTT Plus Android deploy"
readonly WDTT_ANDROID_PRESERVED_MARKER="Preserved by WDTT Plus Android deploy"
readonly WDTT_ANDROID_CONTRACT_MARKER="WDTT deploy compatibility: 1"
readonly WDTT_STANDALONE_MARKER="Managed by WDTT Plus standalone server installer"
readonly WDTT_STANDALONE_OWNERSHIP_PATH="/var/lib/wdtt-server-installer/ownership"
@@ -406,17 +407,27 @@ validate_deploy_data_mode() {
grep -Fqx "${WDTT_STANDALONE_MARKER}" "$WDTT_STANDALONE_OWNERSHIP_PATH"; then
die "Обновление остановлено: сервер управляется standalone-инсталлером"
fi
[ -f "$WDTT_SYSTEMD_UNIT_PATH" ] && [ ! -L "$WDTT_SYSTEMD_UNIT_PATH" ] &&
[ -x "$WDTT_SERVER_BINARY_PATH" ] && [ ! -L "$WDTT_SERVER_BINARY_PATH" ] &&
[ -d "$WDTT_CONFIG_DIR" ] && [ ! -L "$WDTT_CONFIG_DIR" ] ||
die "Обновление остановлено: признаки Android-установки изменились после проверки"
if ! grep -Fqx "# ${WDTT_ANDROID_DEPLOY_MARKER}" "$WDTT_SYSTEMD_UNIT_PATH"; then
[ -d "$WDTT_CONFIG_DIR" ] && [ ! -L "$WDTT_CONFIG_DIR" ] ||
die "Обновление остановлено: каталог данных Android-установки изменился после проверки"
if [ -f "$WDTT_CONFIG_DIR/.android-deploy-preserved" ] &&
[ ! -L "$WDTT_CONFIG_DIR/.android-deploy-preserved" ] &&
grep -Fqx "$WDTT_ANDROID_PRESERVED_MARKER" "$WDTT_CONFIG_DIR/.android-deploy-preserved"; then
[ ! -e "$WDTT_SYSTEMD_UNIT_PATH" ] && [ ! -e "$WDTT_SERVER_BINARY_PATH" ] &&
[ -f "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" ] && [ ! -L "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" ] &&
[ -f "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] && [ ! -L "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] ||
die "Обновление остановлено: сохранённые данные Android-деплоя изменились после проверки"
else
[ -f "$WDTT_SYSTEMD_UNIT_PATH" ] && [ ! -L "$WDTT_SYSTEMD_UNIT_PATH" ] &&
[ -x "$WDTT_SERVER_BINARY_PATH" ] && [ ! -L "$WDTT_SERVER_BINARY_PATH" ] ||
die "Обновление остановлено: признаки Android-установки изменились после проверки"
if ! grep -Fqx "# ${WDTT_ANDROID_DEPLOY_MARKER}" "$WDTT_SYSTEMD_UNIT_PATH"; then
[ -f "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] &&
[ ! -L "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] &&
grep -Eq '^ExecStart=/usr/local/bin/wdtt-server([[:space:]]|$)' "$WDTT_SYSTEMD_UNIT_PATH" &&
grep -Eq '(^|[[:space:]])-config-dir[[:space:]]+/etc/wdtt([[:space:]]|$)' "$WDTT_SYSTEMD_UNIT_PATH" &&
grep -Fq 'wdtt0' "$WDTT_SYSTEMD_UNIT_PATH" ||
die "Обновление остановлено: не удалось подтвердить старую Android-установку"
fi
fi
;;
reset)
@@ -646,6 +657,7 @@ start_wdtt() {
echo "══════════════════════════════════════════════════════════════"
if [ "$status" = "active" ]; then
rm -f "$WDTT_CONFIG_DIR/.android-deploy-preserved"
echo "✅ Деплой успешно завершён!"
echo " NAT: MASQUERADE (стандартный)"
echo " DTLS: порт ${DTLS_PORT}"
@@ -8,6 +8,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
@@ -122,7 +123,9 @@ object AccessLifecycleCoordinator {
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
TunnelManager.noteAccessLifecycleEvent(
noteAccessLifecycleEventIfRelevant(
store = store,
profile = profile,
key = "profile_${profile}_values_sync_failed",
message = error.message
?: "Не удалось обновить сохранённые данные профиля",
@@ -153,7 +156,9 @@ object AccessLifecycleCoordinator {
current.status?.allowConnect != received.allowConnect ||
current.status?.title != received.title
) {
TunnelManager.noteAccessLifecycleEvent(
noteAccessLifecycleEventIfRelevant(
store = store,
profile = profile,
key = "profile_${profile}_decision",
message = received.title.ifBlank { "Состояние профиля обновлено" },
warning = received.severity != AccessLifecycleSeverity.NORMAL,
@@ -165,7 +170,7 @@ object AccessLifecycleCoordinator {
throw cancelled
} catch (error: AccessLifecycleRequestException) {
if (!error.kind.authoritative) {
return@withLock accessRefreshFailure(profile, current, error)
return@withLock accessRefreshFailure(store, profile, current, error)
}
val denied = authoritativeAccessDenialStatus(
failure = error,
@@ -185,7 +190,9 @@ object AccessLifecycleCoordinator {
current.status?.allowConnect != denied.allowConnect ||
current.status?.title != denied.title
) {
TunnelManager.noteAccessLifecycleEvent(
noteAccessLifecycleEventIfRelevant(
store = store,
profile = profile,
key = "profile_${profile}_${error.code}",
message = denied.title,
warning = true,
@@ -194,19 +201,22 @@ object AccessLifecycleCoordinator {
updateExternalSurfaces(appContext)
AccessLifecycleRefreshResult.Success(denied)
} catch (error: Exception) {
accessRefreshFailure(profile, current, error)
accessRefreshFailure(store, profile, current, error)
} finally {
setRefreshing(profile, false)
}
}
}
private fun accessRefreshFailure(
private suspend fun accessRefreshFailure(
store: SettingsStore,
profile: Int,
current: StoredAccessLifecycle,
error: Exception,
): AccessLifecycleRefreshResult.Failed {
TunnelManager.noteAccessLifecycleEvent(
noteAccessLifecycleEventIfRelevant(
store = store,
profile = profile,
key = "profile_${profile}_check_failed",
message = error.message ?: "Не удалось обновить сведения о доступе",
warning = true,
@@ -517,7 +527,9 @@ object AccessLifecycleCoordinator {
require(applied != null) { "Не удалось применить обновление профиля." }
store.saveAppliedAccessProfileRevision(profile, update.revision)
requestTunnelProfileRuntimeUpdate(profile)
TunnelManager.noteAccessLifecycleEvent(
noteAccessLifecycleEventIfRelevant(
store = store,
profile = profile,
key = "profile_${profile}_updated",
message = "Параметры профиля обновлены",
warning = false,
@@ -525,6 +537,20 @@ object AccessLifecycleCoordinator {
return true
}
private suspend fun noteAccessLifecycleEventIfRelevant(
store: SettingsStore,
profile: Int,
key: String,
message: String,
warning: Boolean,
) {
val selectedProfile = store.activeProfile.first().coerceIn(0, 2)
val connectedProfile = TunnelManager.activeTunnelProfile.value
.takeIf { TunnelManager.running.value }
if (profile != selectedProfile && profile != connectedProfile) return
TunnelManager.noteAccessLifecycleEvent(key, message, warning)
}
private fun androidDeviceLabel(): String {
val values = listOf(Build.MANUFACTURER, Build.MODEL)
.map(String::trim)
@@ -27,6 +27,12 @@ class AccessLifecycleRequestException(
object AccessLifecycleGateway {
private const val MAX_RESPONSE_CHARS = 32 * 1024
private data class HttpResponse(
val status: Int,
val body: String,
val codeHint: String,
)
suspend fun fetch(
capability: RemoteAccessCapability,
device: String,
@@ -145,47 +151,92 @@ object AccessLifecycleGateway {
}
.toString()
.toByteArray(Charsets.UTF_8)
var connection: HttpURLConnection? = null
val relayAllowed = operation == "status" && action.isBlank() && values.isEmpty() &&
TunnelManager.isUpdateRelayAvailable()
try {
connection = URL(capability.url).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.instanceFollowRedirects = false
connection.connectTimeout = 7_000
connection.readTimeout = 9_000
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
val body = readBody(connection, status)
if (status !in 200..299) {
throw parseHttpFailure(
status = status,
body = body,
operation = operation,
codeHint = connection.getHeaderField("X-WDTT-Access-Code").orEmpty(),
)
}
body
requestDirect(
url = capability.url,
payload = payload,
connectTimeoutMs = if (relayAllowed) 2_500 else 7_000,
readTimeoutMs = if (relayAllowed) 3_500 else 9_000,
).bodyOrThrow(operation)
} catch (cancelled: CancellationException) {
throw cancelled
} catch (error: Exception) {
if (error is IllegalStateException) throw error
throw IllegalStateException(
if (operation == "continue") {
"Не удалось открыть страницу. Проверьте интернет и повторите попытку."
} else if (action.isNotBlank()) {
"Не удалось обновить сохранённые данные профиля."
} else {
"Не удалось проверить профиль. Проверьте интернет."
if (relayAllowed) {
when (
val relayed = TunnelManager.postOpaqueHttpsStatusThroughTunnel(
capability.url,
payload,
)
) {
is OpaqueHttpsRelayResult.Success -> HttpResponse(
status = relayed.status,
body = relayed.body,
codeHint = relayed.codeHint,
).bodyOrThrow(operation)
is OpaqueHttpsRelayResult.Unavailable -> throw IllegalStateException(
"Не удалось проверить состояние доступа к профилю. " +
"Сохранённые настройки подключения не изменены.",
)
}
)
} finally {
connection?.disconnect()
} else {
throw IllegalStateException(requestFailureMessage(operation, action))
}
}
}
}
private fun requestDirect(
url: String,
payload: ByteArray,
connectTimeoutMs: Int,
readTimeoutMs: Int,
): HttpResponse {
var connection: HttpURLConnection? = null
return try {
connection = URL(url).openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.instanceFollowRedirects = false
connection.connectTimeout = connectTimeoutMs
connection.readTimeout = readTimeoutMs
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.setRequestProperty("Accept", "application/json")
connection.outputStream.use { it.write(payload) }
val status = connection.responseCode
HttpResponse(
status = status,
body = readBody(connection, status),
codeHint = connection.getHeaderField("X-WDTT-Access-Code").orEmpty(),
)
} finally {
connection?.disconnect()
}
}
private fun HttpResponse.bodyOrThrow(operation: String): String {
if (status !in 200..299) {
throw parseHttpFailure(
status = status,
body = body,
operation = operation,
codeHint = codeHint,
)
}
return body
}
private fun requestFailureMessage(operation: String, action: String): String = when {
operation == "continue" ->
"Не удалось открыть страницу. Проверьте интернет и повторите попытку."
action.isNotBlank() -> "Не удалось обновить сохранённые данные профиля."
else ->
"Не удалось проверить состояние доступа к профилю. " +
"Сохранённые настройки подключения не изменены."
}
internal fun parseHttpFailure(
status: Int,
body: String,
+232 -79
View File
@@ -34,6 +34,7 @@ private const val GITHUB_TAG_TREE_URL_PREFIX = "https://github.com/Ivan4537/WDTT
private const val UPDATE_CHECK_TOTAL_TIMEOUT_MS = 25_000L
private const val UPDATE_CHECK_REQUEST_TIMEOUT_MS = 6_000L
private const val UPDATE_CHECK_MIN_REQUEST_TIMEOUT_MS = 1_000L
private const val UPDATE_CHECK_DIRECT_HEDGE_TIMEOUT_MS = 3_000L
private const val UPDATE_APK_HASH_TIMEOUT_MS = 4_000L
private const val MAX_UPDATE_APK_BYTES = 200L * 1024L * 1024L
private const val MAX_UPDATE_METADATA_BYTES = 1024 * 1024
@@ -95,6 +96,14 @@ data class AppUpdateDownloadProgress(
get() = fraction?.let { (it * 100).toInt().coerceIn(0, 100) }
}
internal fun shouldFallbackSlowDirectUpdateDownload(
relayAvailable: Boolean,
downloadedBytes: Long,
elapsedMs: Long,
): Boolean = relayAvailable &&
elapsedMs >= 8_000L &&
downloadedBytes * 1000L < elapsedMs * 64L * 1024L
enum class RemoteVersionSource {
Release,
Tag
@@ -147,7 +156,11 @@ private class UpdateCheckBudget(
}
suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo? = withContext(Dispatchers.IO) {
val budget = UpdateCheckBudget()
fetchLatestReleaseInfoWithBudget(localVersion, UPDATE_CHECK_TOTAL_TIMEOUT_MS)
}
private fun fetchLatestReleaseInfoWithBudget(localVersion: String?, timeoutMs: Long): AppReleaseInfo? {
val budget = UpdateCheckBudget(timeoutMs)
val webRelease = fetchReleaseFromLatestWebRedirect(budget)
val apiRelease = fetchReleaseFromLatestEndpoint(budget) ?: fetchLatestStableReleaseFromList(budget)
val latestRelease = when {
@@ -158,7 +171,7 @@ suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo
}
val latestTag = fetchLatestTagFromList(budget)
when {
return when {
latestRelease == null -> latestTag
latestTag == null -> latestRelease
isNewerVersion(latestRelease.versionTag, latestTag.versionTag) -> latestTag
@@ -166,6 +179,104 @@ suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo
}
}
suspend fun fetchLatestReleaseInfo(_context: Context, localVersion: String? = null): AppReleaseInfo? =
withContext(Dispatchers.IO) {
val relayAvailable = TunnelManager.isUpdateRelayAvailable()
val directTimeout = if (relayAvailable) {
UPDATE_CHECK_DIRECT_HEDGE_TIMEOUT_MS
} else {
UPDATE_CHECK_TOTAL_TIMEOUT_MS
}
val direct = runCatching {
fetchLatestReleaseInfoWithBudget(localVersion, directTimeout)
}.getOrNull()
if (direct != null && (!relayAvailable || selectUpdateApkAsset(direct) != null)) {
return@withContext direct
}
val relayed = TunnelManager.fetchUpdateMetadataThroughTunnel()
?.let(::parseRelayedUpdateMetadata)
if (relayed != null) {
Log.i(UPDATE_LOG_TAG, "Update check: direct access failed, metadata received through active WDTT tunnel")
return@withContext when {
direct == null -> relayed
isNewerVersion(relayed.versionTag, direct.versionTag) -> direct
else -> relayed
}
}
direct
}
internal fun parseRelayedUpdateMetadata(payload: String): AppReleaseInfo? {
if (payload.isBlank() || payload.length > 64 * 1024) return null
val json = runCatching { JSONObject(payload) }.getOrNull() ?: return null
val versionTag = normalizeVersionTag(json.optString("version_tag"))
if (versionTag.isBlank()) return null
val source = when (json.optString("source")) {
"release" -> RemoteVersionSource.Release
"tag" -> RemoteVersionSource.Tag
else -> return null
}
val releaseUrl = json.optString("release_url").trim()
if (!isTrustedRelayedReleaseUrl(releaseUrl, versionTag, source)) return null
val assets = if (source == RemoteVersionSource.Release) {
buildList {
val values = json.optJSONArray("assets") ?: JSONArray()
for (index in 0 until minOf(values.length(), 8)) {
val asset = values.optJSONObject(index) ?: continue
val name = asset.optString("name").trim()
val downloadUrl = asset.optString("download_url").trim()
val size = asset.optLong("size", 0L)
if (
name.isBlank() || name.length > 200 || '/' in name || '\\' in name ||
size !in 1..MAX_UPDATE_APK_BYTES ||
!isTrustedUpdateDownloadUrl(downloadUrl, initialRequest = true)
) {
continue
}
add(
AppReleaseAsset(
name = name,
downloadUrl = downloadUrl,
sizeBytes = size,
digest = asset.optString("digest").trim(),
)
)
}
}
} else {
emptyList()
}
return AppReleaseInfo(
versionTag = versionTag,
releaseUrl = releaseUrl,
source = source,
assets = assets,
)
}
private fun isTrustedRelayedReleaseUrl(
value: String,
versionTag: String,
source: RemoteVersionSource,
): Boolean {
val uri = runCatching { java.net.URI(value) }.getOrNull() ?: return false
if (
!uri.scheme.equals("https", ignoreCase = true) ||
!uri.host.equals("github.com", ignoreCase = true) ||
!uri.rawUserInfo.isNullOrBlank() ||
(uri.port != -1 && uri.port != 443) ||
!uri.rawQuery.isNullOrBlank() ||
!uri.rawFragment.isNullOrBlank()
) {
return false
}
val expectedPath = when (source) {
RemoteVersionSource.Release -> "/Ivan4537/WDTT-Plus/releases/tag/$versionTag"
RemoteVersionSource.Tag -> "/Ivan4537/WDTT-Plus/tree/$versionTag"
}
return uri.path == expectedPath
}
suspend fun resolveAppUpdateCandidate(
context: Context,
localVersion: String,
@@ -231,7 +342,7 @@ suspend fun downloadUpdateApk(
}
val outputFile = File(updatesDir, asset.name.safeUpdateAssetName())
var conn: HttpURLConnection? = null
val relayAvailable = TunnelManager.isUpdateRelayAvailable()
suspend fun emit(downloaded: Long, total: Long) {
withContext(Dispatchers.Main) {
@@ -239,97 +350,139 @@ suspend fun downloadUpdateApk(
}
}
try {
var currentUrl = URL(asset.downloadUrl)
var responseCode = 0
for (redirect in 0..MAX_UPDATE_REDIRECTS) {
val currentConnection = currentUrl.openConnection() as HttpURLConnection
conn = currentConnection
applyNoCacheHeaders(currentConnection)
currentConnection.instanceFollowRedirects = false
currentConnection.requestMethod = "GET"
currentConnection.setRequestProperty(
"Accept",
"application/vnd.android.package-archive,application/octet-stream",
)
currentConnection.setRequestProperty(
"User-Agent",
"WDTTAndroid/${BuildConfig.VERSION_NAME}",
)
currentConnection.connectTimeout = 15_000
currentConnection.readTimeout = 30_000
responseCode = currentConnection.responseCode
if (responseCode !in 300..399) break
val location = currentConnection.getHeaderField("Location")
?.takeIf { it.isNotBlank() }
?: throw IOException("GitHub вернул перенаправление без адреса.")
if (redirect >= MAX_UPDATE_REDIRECTS) {
throw IOException("GitHub вернул слишком много перенаправлений.")
suspend fun downloadDirect(): File {
var conn: HttpURLConnection? = null
try {
var currentUrl = URL(asset.downloadUrl)
var responseCode = 0
for (redirect in 0..MAX_UPDATE_REDIRECTS) {
val currentConnection = currentUrl.openConnection() as HttpURLConnection
conn = currentConnection
applyNoCacheHeaders(currentConnection)
currentConnection.instanceFollowRedirects = false
currentConnection.requestMethod = "GET"
currentConnection.setRequestProperty(
"Accept",
"application/vnd.android.package-archive,application/octet-stream",
)
currentConnection.setRequestProperty(
"User-Agent",
"WDTTAndroid/${BuildConfig.VERSION_NAME}",
)
currentConnection.connectTimeout = if (relayAvailable) 3_000 else 15_000
currentConnection.readTimeout = if (relayAvailable) 5_000 else 30_000
responseCode = currentConnection.responseCode
if (responseCode !in 300..399) break
val location = currentConnection.getHeaderField("Location")
?.takeIf { it.isNotBlank() }
?: throw IOException("GitHub вернул перенаправление без адреса.")
if (redirect >= MAX_UPDATE_REDIRECTS) {
throw IOException("GitHub вернул слишком много перенаправлений.")
}
val nextUrl = URL(currentUrl, location)
require(isTrustedUpdateDownloadUrl(nextUrl.toString(), initialRequest = false)) {
"GitHub перенаправил загрузку на недоверенный адрес."
}
currentConnection.disconnect()
conn = null
currentUrl = nextUrl
}
val nextUrl = URL(currentUrl, location)
require(isTrustedUpdateDownloadUrl(nextUrl.toString(), initialRequest = false)) {
"GitHub перенаправил загрузку на недоверенный адрес."
val activeConnection = conn ?: throw IOException("Не удалось открыть загрузку APK.")
if (responseCode !in 200..299) {
throw IOException("GitHub вернул HTTP $responseCode при скачивании APK")
}
currentConnection.disconnect()
conn = null
currentUrl = nextUrl
}
val activeConnection = conn ?: throw IOException("Не удалось открыть загрузку APK.")
if (responseCode !in 200..299) {
throw IOException("GitHub вернул HTTP $responseCode при скачивании APK")
}
val responseLength = activeConnection.contentLengthLong
if (responseLength > MAX_UPDATE_APK_BYTES) {
throw IOException("APK превышает безопасный лимит размера.")
}
if (responseLength > 0L && responseLength != asset.sizeBytes) {
throw IOException("Размер APK не совпал с данными выпуска.")
}
val total = asset.sizeBytes
var downloaded = 0L
var lastEmitAt = 0L
emit(0L, total)
val responseLength = activeConnection.contentLengthLong
if (responseLength > MAX_UPDATE_APK_BYTES) {
throw IOException("APK превышает безопасный лимит размера.")
}
if (responseLength > 0L && responseLength != asset.sizeBytes) {
throw IOException("Размер APK не совпал с данными выпуска.")
}
val total = asset.sizeBytes
var downloaded = 0L
var lastEmitAt = 0L
val directStartedAt = System.currentTimeMillis()
emit(0L, total)
activeConnection.inputStream.use { input ->
outputFile.outputStream().use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
val read = input.read(buffer)
if (read < 0) break
output.write(buffer, 0, read)
downloaded += read
if (downloaded > MAX_UPDATE_APK_BYTES || downloaded > asset.sizeBytes) {
throw IOException("APK превышает заявленный размер.")
}
val now = System.currentTimeMillis()
if (now - lastEmitAt >= 250L || downloaded == total) {
lastEmitAt = now
emit(downloaded, total)
activeConnection.inputStream.use { input ->
outputFile.outputStream().use { output ->
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
while (true) {
val read = input.read(buffer)
if (read < 0) break
output.write(buffer, 0, read)
downloaded += read
if (downloaded > MAX_UPDATE_APK_BYTES || downloaded > asset.sizeBytes) {
throw IOException("APK превышает заявленный размер.")
}
val now = System.currentTimeMillis()
val elapsed = now - directStartedAt
if (shouldFallbackSlowDirectUpdateDownload(relayAvailable, downloaded, elapsed)) {
throw IOException("Прямая загрузка слишком медленная; переключаюсь на WDTT Plus")
}
if (now - lastEmitAt >= 250L || downloaded == total) {
lastEmitAt = now
emit(downloaded, total)
}
}
}
}
}
if (asset.sizeBytes > 0L && outputFile.length() != asset.sizeBytes) {
outputFile.delete()
throw IOException("Размер APK не совпал с GitHub asset")
}
if (asset.sizeBytes > 0L && outputFile.length() != asset.sizeBytes) {
outputFile.delete()
throw IOException("Размер APK не совпал с GitHub asset")
}
val actual = outputFile.sha256Hex()
if (!actual.equals(expectedSha256, ignoreCase = true)) {
outputFile.delete()
throw SecurityException("SHA-256 скачанного APK не совпал с GitHub digest")
}
validateUpdatePackage(appContext, outputFile)
emit(outputFile.length(), total.takeIf { it > 0L } ?: outputFile.length())
return outputFile
} finally {
conn?.disconnect()
}
}
val directFailure = try {
return@withContext downloadDirect()
} catch (error: Exception) {
outputFile.delete()
error
}
Log.i(UPDATE_LOG_TAG, "Update download: direct access failed, trying active WDTT tunnel")
emit(0L, asset.sizeBytes)
val downloadedThroughTunnel = TunnelManager.downloadUpdateApkThroughTunnel(
downloadUrl = asset.downloadUrl,
sizeBytes = asset.sizeBytes,
sha256 = expectedSha256,
outputFile = outputFile,
) { downloaded, total ->
emit(downloaded, total)
}
if (!downloadedThroughTunnel) {
outputFile.delete()
throw directFailure
}
try {
if (outputFile.length() != asset.sizeBytes) {
throw IOException("Размер APK после передачи через WDTT не совпал с данными выпуска")
}
val actual = outputFile.sha256Hex()
if (!actual.equals(expectedSha256, ignoreCase = true)) {
outputFile.delete()
throw SecurityException("SHA-256 скачанного APK не совпал с GitHub digest")
throw SecurityException("SHA-256 APK после передачи через WDTT не совпал с GitHub digest")
}
validateUpdatePackage(appContext, outputFile)
emit(outputFile.length(), total.takeIf { it > 0L } ?: outputFile.length())
emit(outputFile.length(), asset.sizeBytes)
outputFile
} catch (e: Exception) {
} catch (error: Exception) {
outputFile.delete()
throw e
} finally {
conn?.disconnect()
throw error
}
}
@@ -2,6 +2,7 @@ package com.wdtt.plus
import android.Manifest
import android.app.ActivityManager
import android.app.ApplicationExitInfo
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
@@ -97,6 +98,215 @@ data class DeviceCompatibilityReport(
}
}
internal enum class ProcessExitCategory {
SystemPolicy,
ExcessiveResources,
LowMemory,
Crash,
UserAction,
PackageChange,
NormalExit,
Dependency,
Unknown,
}
internal data class ProcessExitRecord(
val timestampMs: Long,
val reason: Int,
val description: String = "",
)
internal data class ProcessExitHistory(
val latest: ProcessExitRecord?,
val latestUnexpected: ProcessExitRecord?,
)
private const val PROCESS_EXIT_LOOKBACK_MS = 7L * 24L * 60L * 60L * 1000L
private val oemKillMarkerRegex = Regex("o-kill\\(\\d+\\)", RegexOption.IGNORE_CASE)
internal fun classifyProcessExit(record: ProcessExitRecord): ProcessExitCategory = when (record.reason) {
ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE -> ProcessExitCategory.ExcessiveResources
ApplicationExitInfo.REASON_LOW_MEMORY -> ProcessExitCategory.LowMemory
ApplicationExitInfo.REASON_CRASH,
ApplicationExitInfo.REASON_CRASH_NATIVE,
ApplicationExitInfo.REASON_ANR,
ApplicationExitInfo.REASON_INITIALIZATION_FAILURE -> ProcessExitCategory.Crash
ApplicationExitInfo.REASON_USER_REQUESTED,
ApplicationExitInfo.REASON_USER_STOPPED -> ProcessExitCategory.UserAction
ApplicationExitInfo.REASON_PACKAGE_STATE_CHANGE,
ApplicationExitInfo.REASON_PACKAGE_UPDATED,
ApplicationExitInfo.REASON_PERMISSION_CHANGE -> ProcessExitCategory.PackageChange
ApplicationExitInfo.REASON_EXIT_SELF -> ProcessExitCategory.NormalExit
ApplicationExitInfo.REASON_DEPENDENCY_DIED -> ProcessExitCategory.Dependency
ApplicationExitInfo.REASON_OTHER,
ApplicationExitInfo.REASON_FREEZER -> ProcessExitCategory.SystemPolicy
else -> ProcessExitCategory.Unknown
}
internal fun processExitHistory(
records: List<ProcessExitRecord>,
nowMs: Long = System.currentTimeMillis(),
): ProcessExitHistory {
val recent = records
.filter { it.timestampMs in (nowMs - PROCESS_EXIT_LOOKBACK_MS)..nowMs }
.sortedByDescending(ProcessExitRecord::timestampMs)
val latestUnexpected = recent.firstOrNull {
classifyProcessExit(it) in setOf(
ProcessExitCategory.SystemPolicy,
ProcessExitCategory.ExcessiveResources,
ProcessExitCategory.LowMemory,
ProcessExitCategory.Crash,
ProcessExitCategory.Dependency,
ProcessExitCategory.Unknown,
)
}
return ProcessExitHistory(
latest = recent.firstOrNull(),
latestUnexpected = latestUnexpected,
)
}
private fun processExitTimestamp(timestampMs: Long): String =
SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.ROOT).format(Date(timestampMs))
private fun recognizedSystemExitMarker(description: String): String =
oemKillMarkerRegex.find(description)?.value.orEmpty()
internal fun backgroundRestrictionRecommendation(
manufacturer: String,
backgroundRestricted: Boolean?,
batteryOptimizationsIgnored: Boolean?,
): String {
val systemState = when {
backgroundRestricted == true ->
"Android пометил WDTT Plus как ограниченное в фоне. Сначала разрешите фоновую работу в настройках приложения. "
batteryOptimizationsIgnored == false ->
"Для WDTT Plus ещё действует системная оптимизация батареи. Отключите её. "
else -> ""
}
val vendorHint = when (manufacturer.trim().lowercase(Locale.ROOT)) {
"xiaomi", "redmi", "poco" ->
"На MIUI/HyperOS выберите для приложения режим батареи «Без ограничений» и разрешите автозапуск."
"oneplus", "oppo", "realme" ->
"На OxygenOS/ColorOS/realme UI разрешите работу в фоне и проверьте оптимизацию сна или ожидания для приложения."
"samsung" ->
"На Samsung добавьте WDTT Plus в список приложений, которые не переводятся в сон."
"huawei", "honor" ->
"В настройках запуска приложений разрешите WDTT Plus автозапуск и работу в фоне."
else ->
"Откройте настройки батареи WDTT Plus и выберите неограниченную фоновую работу, если такой пункт доступен."
}
return systemState + vendorHint
}
internal fun processExitHistoryItem(
history: ProcessExitHistory,
manufacturer: String,
backgroundRestricted: Boolean?,
batteryOptimizationsIgnored: Boolean?,
): DeviceCheckItem {
val unexpected = history.latestUnexpected
if (unexpected == null) {
val latest = history.latest
return when (latest?.let(::classifyProcessExit)) {
ProcessExitCategory.UserAction -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "остановлено пользователем или системой настроек",
details = "Android зафиксировал штатную остановку ${processExitTimestamp(latest.timestampMs)}. Это не похоже на самопроизвольное завершение во сне.",
severity = DeviceCheckSeverity.Info,
)
ProcessExitCategory.PackageChange -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "обновление или изменение пакета",
details = "Последняя запись Android от ${processExitTimestamp(latest.timestampMs)} связана с обновлением приложения, его разрешений или состояния пакета.",
severity = DeviceCheckSeverity.Info,
)
ProcessExitCategory.NormalExit -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "штатное",
details = "За последние 7 дней Android не зафиксировал неожиданного завершения основного процесса WDTT Plus.",
severity = DeviceCheckSeverity.Ok,
)
else -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "неожиданных завершений не найдено",
details = "В доступной Android истории за последние 7 дней нет системного завершения процесса или сбоя WDTT Plus.",
severity = DeviceCheckSeverity.Ok,
)
}
}
val category = classifyProcessExit(unexpected)
val time = processExitTimestamp(unexpected.timestampMs)
val marker = recognizedSystemExitMarker(unexpected.description)
val newerExpectedEvent = history.latest
?.takeIf { it.timestampMs > unexpected.timestampMs }
?.let(::classifyProcessExit)
?.takeIf {
it == ProcessExitCategory.UserAction ||
it == ProcessExitCategory.PackageChange ||
it == ProcessExitCategory.NormalExit
}
val laterEventNote = if (newerExpectedEvent != null) {
" После этого Android зафиксировал более новое штатное событие, но оно не отменяет найденное неожиданное завершение."
} else {
""
}
val markerText = if (marker.isNotBlank()) " Метка оболочки Android: $marker." else ""
val commonRecommendation = backgroundRestrictionRecommendation(
manufacturer = manufacturer,
backgroundRestricted = backgroundRestricted,
batteryOptimizationsIgnored = batteryOptimizationsIgnored,
)
return when (category) {
ProcessExitCategory.SystemPolicy -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "процесс завершён системой",
details = "Android завершил основной процесс WDTT Plus $time вне штатной остановки приложения.$markerText$laterEventNote",
recommendation = commonRecommendation,
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.BatterySettings,
)
ProcessExitCategory.ExcessiveResources -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "система ограничила использование ресурсов",
details = "Android завершил WDTT Plus $time из-за зафиксированного системой длительного использования ресурсов.$laterEventNote",
recommendation = "$commonRecommendation Если это повторяется в режиме «Удерживать соединение», приложите отчёт устройства и системный журнал.",
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.BatterySettings,
)
ProcessExitCategory.LowMemory -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "не хватило памяти",
details = "Android завершил WDTT Plus $time при нехватке оперативной памяти.$laterEventNote",
recommendation = "Закройте тяжёлые приложения и повторите проверку. Если это происходит регулярно, приложите отчёт устройства.",
severity = DeviceCheckSeverity.Warning,
)
ProcessExitCategory.Crash -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "обнаружен сбой приложения",
details = "Android зафиксировал аварийное завершение WDTT Plus $time.$laterEventNote",
recommendation = "Скопируйте отчёт устройства и журнал приложения после повторения проблемы.",
severity = DeviceCheckSeverity.Error,
)
ProcessExitCategory.Dependency -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "завершился зависимый системный компонент",
details = "Android остановил WDTT Plus $time после завершения связанного системного процесса.$laterEventNote",
recommendation = "Повторите подключение. Если проблема возвращается, приложите отчёт устройства.",
severity = DeviceCheckSeverity.Warning,
)
else -> DeviceCheckItem(
title = "Последнее завершение приложения",
status = "причина не распознана",
details = "Android сохранил запись о завершении WDTT Plus $time, но не сообщил однозначную причину.$laterEventNote",
recommendation = "Приложите отчёт устройства и системный журнал после повторения проблемы.",
severity = DeviceCheckSeverity.Warning,
)
}
}
internal enum class RtMasqueEnrollmentState {
Missing,
Ready,
@@ -166,58 +376,128 @@ internal fun tunnelHealthItem(
activeWorkers: Int,
issue: ConnectionIssue?,
confirmedNetworkFailure: Boolean,
tunnelMode: String = TUNNEL_MODE_VPN,
): DeviceCheckItem = when {
!running -> DeviceCheckItem(
title = "Текущее подключение VPN",
title = "Текущее соединение",
status = "не активно",
details = "VPN сейчас не подключён. Это не мешает проверке устройства; пункт фиксирует текущее состояние туннеля.",
details = "Соединение сейчас не активно. Это не мешает проверке устройства; пункт фиксирует текущее состояние туннеля.",
recommendation = issue?.let { "${it.title}: ${it.action}" }.orEmpty(),
severity = DeviceCheckSeverity.Info,
)
confirmedNetworkFailure -> DeviceCheckItem(
title = "Текущее подключение VPN",
title = "Текущее соединение",
status = "нет ответа на пользовательский трафик",
details = "VPN-интерфейс включён, активных каналов: $activeWorkers, но приложение подтвердило отсутствие ответов на переданный трафик.",
details = if (tunnelModeUsesLocalProxy(tunnelMode)) {
"Прокси ${tunnelModeStatusLabel(tunnelMode)} запущен, активных каналов: $activeWorkers, но приложение подтвердило отсутствие ответов на переданный трафик."
} else {
"VPN-интерфейс включён, активных каналов: $activeWorkers, но приложение подтвердило отсутствие ответов на переданный трафик."
},
recommendation = issue?.let { "${it.title}: ${it.action}" }
?: "WDTT Plus автоматически проверит восстановление и при необходимости переподключит VPN.",
?: "WDTT Plus автоматически проверит восстановление и при необходимости переподключит транспорт.",
severity = DeviceCheckSeverity.Warning,
)
issue != null -> DeviceCheckItem(
title = "Текущее подключение VPN",
title = "Текущее соединение",
status = "обнаружена проблема",
details = "VPN-интерфейс включён, активных каналов: $activeWorkers. Приложение обнаружило состояние, требующее внимания.",
details = if (tunnelModeUsesLocalProxy(tunnelMode)) {
"Прокси ${tunnelModeStatusLabel(tunnelMode)} запущен, активных каналов: $activeWorkers. Приложение обнаружило состояние, требующее внимания."
} else {
"VPN-интерфейс включён, активных каналов: $activeWorkers. Приложение обнаружило состояние, требующее внимания."
},
recommendation = "${issue.title}: ${issue.action}",
severity = DeviceCheckSeverity.Warning,
)
activeWorkers <= 0 -> DeviceCheckItem(
title = "Текущее подключение VPN",
title = "Текущее соединение",
status = "нет активных каналов",
details = "VPN подключён, но сейчас нет активных транспортных каналов.",
recommendation = "Подождите автоматического восстановления. Если каналы не появятся, переподключите VPN и приложите новый отчёт.",
details = "Соединение запущено, но сейчас нет активных транспортных каналов.",
recommendation = "Подождите автоматического восстановления. Если каналы не появятся, переподключите транспорт и приложите новый отчёт.",
severity = DeviceCheckSeverity.Warning,
)
else -> DeviceCheckItem(
title = "Текущее подключение VPN",
title = "Текущее соединение",
status = "активно",
details = "VPN подключён. Активных каналов: $activeWorkers.",
details = if (tunnelModeUsesLocalProxy(tunnelMode)) {
"Прокси ${tunnelModeStatusLabel(tunnelMode)} работает. Активных каналов: $activeWorkers."
} else {
"Системный VPN подключён. Активных каналов: $activeWorkers."
},
severity = DeviceCheckSeverity.Ok,
)
}
internal fun lastTunnelStopItem(
running: Boolean,
reason: TunnelStopReason?,
): DeviceCheckItem? {
if (running || reason == null) return null
return when (reason) {
TunnelStopReason.User,
TunnelStopReason.CaptchaCancelled -> DeviceCheckItem(
title = "Последняя остановка соединения",
status = reason.displayText,
details = "Соединение было остановлено явным действием пользователя, а не системным завершением процесса.",
severity = DeviceCheckSeverity.Info,
)
TunnelStopReason.VpnSlotTransferred,
TunnelStopReason.VpnStoppedExternally -> DeviceCheckItem(
title = "Последняя остановка соединения",
status = reason.displayText,
details = "Android освободил единственный системный VPN-слот WDTT Plus. Это отдельное событие и не означает, что процесс приложения был завершён системой.",
recommendation = "Проверьте, не запускался ли другой VPN или его плитка быстрых настроек. Затем включите WDTT Plus снова.",
severity = DeviceCheckSeverity.Info,
action = DeviceCheckAction.VpnSettings,
)
TunnelStopReason.TrustedWifi -> DeviceCheckItem(
title = "Последняя остановка соединения",
status = reason.displayText,
details = "VPN намеренно остановлен автоматикой доверенной Wi-Fi сети и будет восстановлен после выхода из неё.",
severity = DeviceCheckSeverity.Ok,
)
else -> DeviceCheckItem(
title = "Последняя остановка соединения",
status = reason.displayText,
details = "WDTT Plus остановил соединение после обнаруженной ошибки или системного события. Причина выше относится к соединению; отдельный пункт о завершении приложения показывает, был ли уничтожен весь процесс.",
recommendation = "Если остановка повторяется, приложите отчёт устройства и журнал приложения.",
severity = DeviceCheckSeverity.Warning,
)
}
}
internal fun sleepBatteryModeItem(
enabled: Boolean,
screenOffMode: ScreenOffMode = if (enabled) ScreenOffMode.SAVE_BATTERY else ScreenOffMode.BALANCED,
mode: SleepBatteryMode,
pauseDelayMinutes: Int,
resumeDelayMinutes: Int,
runtime: SleepBatteryRuntimeState,
notificationsGranted: Boolean,
batteryOptimizationsIgnored: Boolean?,
backgroundRestricted: Boolean? = null,
): DeviceCheckItem {
if (!enabled) {
if (screenOffMode == ScreenOffMode.HOLD_CONNECTION) {
val restricted = batteryOptimizationsIgnored == false || backgroundRestricted == true
return DeviceCheckItem(
title = "Экономия батареи во сне",
status = "выключена",
details = "При выключенном экране WDTT Plus не будет намеренно останавливать VPN по сценарию сна.",
title = "Работа при выключенном экране",
status = "удерживать соединение",
details = "WDTT Plus старается сохранять активное соединение при выключенном экране, в том числе при работе через Wi-Fi. Android может применять собственные ограничения фоновой работы. Режим повышает надёжность, но увеличивает расход батареи.",
recommendation = if (backgroundRestricted == true) {
"Android сообщает, что WDTT Plus ограничен в фоне. Разрешите фоновую работу и снимите ограничение батареи, иначе система всё равно может остановить приложение."
} else if (restricted) {
"Снимите системное ограничение батареи с WDTT Plus, иначе Android всё равно может остановить приложение."
} else {
""
},
severity = if (restricted) DeviceCheckSeverity.Warning else DeviceCheckSeverity.Ok,
action = if (restricted) DeviceCheckAction.BatterySettings else null,
)
}
if (screenOffMode == ScreenOffMode.BALANCED || !enabled) {
return DeviceCheckItem(
title = "Работа при выключенном экране",
status = "сбалансированно",
details = "WDTT Plus использует обычную фоновую работу Android и автоматически проверяет каналы после пробуждения.",
severity = DeviceCheckSeverity.Info,
)
}
@@ -263,7 +543,7 @@ internal fun sleepBatteryModeItem(
" Включение экрана завершает текущий сценарий."
}
return DeviceCheckItem(
title = "Экономия батареи во сне",
title = "Работа при выключенном экране",
status = status,
details = "Текущее состояние: $runtimeText.$timerNote Во время паузы интернет телефона идёт напрямую, без VPN.",
recommendation = recommendation,
@@ -277,6 +557,54 @@ internal fun sleepBatteryModeItem(
)
}
internal fun connectionHoldRuntimeItem(
running: Boolean,
diagnostics: ConnectionHoldDiagnostics,
): DeviceCheckItem {
val technicalDetails =
"Системные признаки: CPU wake lock — ${if (diagnostics.cpuWakeLockHeld) "активен" else "не активен"}; " +
"Wi-Fi lock — ${if (diagnostics.wifiLockHeld) "активен" else "не активен"}; " +
"Wi-Fi — ${if (diagnostics.wifiTransportAvailable) "используется" else "не используется"}; " +
"экран — ${if (diagnostics.deviceInteractive) "включён" else "выключен"}."
return when {
!diagnostics.modeSelected -> DeviceCheckItem(
title = "Удержание соединения",
status = "не выбрано",
details = "Сейчас используется другой режим работы при выключенном экране. $technicalDetails",
severity = DeviceCheckSeverity.Info,
)
!running -> DeviceCheckItem(
title = "Удержание соединения",
status = "ожидает запуска",
details = "Режим выбран и начнёт действовать после запуска соединения. $technicalDetails",
severity = DeviceCheckSeverity.Info,
)
!diagnostics.active || !diagnostics.cpuWakeLockHeld -> DeviceCheckItem(
title = "Удержание соединения",
status = "не действует",
details = "Соединение запущено, но системное удержание CPU не подтверждено. $technicalDetails",
recommendation = "Перезапустите соединение. Если состояние повторится, приложите отчёт устройства и журнал.",
severity = DeviceCheckSeverity.Warning,
)
!diagnostics.deviceInteractive &&
diagnostics.wifiTransportAvailable &&
!diagnostics.wifiLockHeld -> DeviceCheckItem(
title = "Удержание соединения",
status = "Wi-Fi не удерживается",
details = "Удержание CPU активно, но удержание используемого Wi-Fi не подтверждено. $technicalDetails",
recommendation = "Проверьте ограничения батареи и фоновой работы WDTT Plus. Если состояние повторится, приложите отчёт устройства и журнал.",
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.BatterySettings,
)
else -> DeviceCheckItem(
title = "Удержание соединения",
status = "действует",
details = "Режим работает. Удержание Wi-Fi включается только при выключенном экране и активном Wi-Fi. $technicalDetails",
severity = DeviceCheckSeverity.Ok,
)
}
}
internal fun trustedWifiModeItem(
enabled: Boolean,
savedNetworkCount: Int,
@@ -452,14 +780,16 @@ object DeviceCompatibility {
fun check(
context: Context,
includeRuntimeChecks: Boolean,
workersPerHash: Int? = null
workersPerHash: Int? = null,
tunnelMode: String = TUNNEL_MODE_VPN,
screenOffMode: ScreenOffMode? = null,
): DeviceCompatibilityReport {
val appContext = context.applicationContext
val television = isTelevisionDevice(appContext)
val items = buildList {
add(androidVersionItem())
add(abiItem())
add(nativeComponentsItem(appContext))
add(nativeComponentsItem(appContext, tunnelMode))
nativeRuntimeSafetyItem()?.let(::add)
add(pageSizeItem())
add(memoryClassItem(appContext, workersPerHash))
@@ -468,10 +798,27 @@ object DeviceCompatibility {
if (includeRuntimeChecks) {
add(networkItem(appContext))
add(vpnPermissionItem())
add(tunnelStateItem())
if (tunnelModeNeedsVpnPermission(tunnelMode)) {
add(vpnPermissionItem())
}
add(tunnelStateItem(tunnelMode))
add(
connectionHoldRuntimeItem(
running = TunnelManager.running.value,
diagnostics = TunnelManager.connectionHoldDiagnostics.value.let { diagnostics ->
screenOffMode?.let { mode ->
diagnostics.copy(modeSelected = mode == ScreenOffMode.HOLD_CONNECTION)
} ?: diagnostics
},
)
)
lastTunnelStopItem(
running = TunnelManager.running.value,
reason = TunnelManager.lastStopReason.value,
)?.let(::add)
add(notificationPermissionItem(appContext, television))
add(batteryItem(appContext, television))
add(processExitItem(appContext))
add(updateInstallPermissionItem(appContext))
}
}
@@ -578,13 +925,16 @@ object DeviceCompatibility {
)
}
private fun nativeComponentsItem(context: Context): DeviceCheckItem {
private fun nativeComponentsItem(context: Context, tunnelMode: String): DeviceCheckItem {
val nativeLibraryDir = context.applicationInfo.nativeLibraryDir.orEmpty()
val nativeClient = File(nativeLibraryDir, "libclient.so")
val wireGuardBackend = File(nativeLibraryDir, "libwg-go.so")
val systemVpnMode = tunnelModeNeedsVpnPermission(tunnelMode)
val missing = buildList {
if (!nativeClient.isFile || nativeClient.length() <= 0L) add("libclient.so")
if (!wireGuardBackend.isFile || wireGuardBackend.length() <= 0L) add("libwg-go.so")
if (systemVpnMode && (!wireGuardBackend.isFile || wireGuardBackend.length() <= 0L)) {
add("libwg-go.so")
}
}
return when {
missing.isNotEmpty() -> DeviceCheckItem(
@@ -595,6 +945,13 @@ object DeviceCompatibility {
severity = DeviceCheckSeverity.Error,
firstLaunchRelevant = true
)
!systemVpnMode -> DeviceCheckItem(
title = "Нативные компоненты",
status = "прокси-клиент найден",
details = "libclient.so: ${formatMiB(nativeClient.length())}. Системный WireGuard backend не требуется режиму ${tunnelModeStatusLabel(tunnelMode)}.",
severity = DeviceCheckSeverity.Ok,
firstLaunchRelevant = true
)
else -> DeviceCheckItem(
title = "Нативные компоненты",
status = "клиент и WireGuard найдены",
@@ -809,14 +1166,14 @@ object DeviceCompatibility {
)
}
private fun tunnelStateItem(): DeviceCheckItem {
private fun tunnelStateItem(tunnelMode: String): DeviceCheckItem {
val running = TunnelManager.running.value
val trustedWifi = TrustedWifiManager.state.value
val activeWorkers = TunnelManager.activeWorkers.value
val issue = TunnelManager.connectionIssue.value
return if (trustedWifi.waiting) {
DeviceCheckItem(
title = "Текущее подключение VPN",
title = "Текущее соединение",
status = "ожидание доверенной Wi-Fi сети",
details = "VPN сейчас выключен автоматикой доверенных сетей и восстановится после выхода из Wi-Fi.",
severity = DeviceCheckSeverity.Ok
@@ -827,6 +1184,7 @@ object DeviceCompatibility {
activeWorkers = activeWorkers,
issue = issue,
confirmedNetworkFailure = TunnelManager.hasConfirmedNetworkFailureSince(0L),
tunnelMode = tunnelMode,
)
} else {
tunnelHealthItem(
@@ -834,6 +1192,7 @@ object DeviceCompatibility {
activeWorkers = activeWorkers,
issue = issue,
confirmedNetworkFailure = false,
tunnelMode = tunnelMode,
)
}
}
@@ -896,23 +1255,42 @@ object DeviceCompatibility {
val ignored = runCatching {
powerManager?.isIgnoringBatteryOptimizations(context.packageName)
}.getOrNull()
return when (ignored) {
true -> DeviceCheckItem(
val backgroundRestricted = runCatching {
context.getSystemService(ActivityManager::class.java)?.isBackgroundRestricted
}.getOrNull()
return when {
backgroundRestricted == true -> DeviceCheckItem(
title = "Фоновая работа",
status = "без ограничений батареи",
details = "Android не должен агрессивно останавливать VPN в фоне.",
status = "ограничена системой",
details = "Android сообщает, что фоновая работа WDTT Plus ограничена. Это ограничение может действовать даже при исключении из обычной оптимизации батареи.",
recommendation = backgroundRestrictionRecommendation(
manufacturer = Build.MANUFACTURER,
backgroundRestricted = true,
batteryOptimizationsIgnored = ignored,
),
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.BatterySettings,
)
ignored == true -> DeviceCheckItem(
title = "Фоновая работа",
status = "стандартная оптимизация отключена",
details = "Стандартная оптимизация батареи Android отключена для WDTT Plus. Производитель телефона всё равно может применять отдельные правила фоновой работы.",
severity = DeviceCheckSeverity.Ok,
action = DeviceCheckAction.BatterySettings
)
false -> DeviceCheckItem(
ignored == false -> DeviceCheckItem(
title = "Фоновая работа",
status = "ограничения батареи могут мешать",
details = "Это не архитектурная ошибка, но на некоторых прошивках VPN может засыпать при выключенном экране.",
recommendation = "Отключите ограничения батареи для WDTT Plus, если туннель сам останавливается.",
recommendation = backgroundRestrictionRecommendation(
manufacturer = Build.MANUFACTURER,
backgroundRestricted = backgroundRestricted,
batteryOptimizationsIgnored = false,
),
severity = DeviceCheckSeverity.Warning,
action = DeviceCheckAction.BatterySettings
)
null -> DeviceCheckItem(
else -> DeviceCheckItem(
title = "Фоновая работа",
status = "не удалось проверить",
details = "Состояние ограничений батареи не определено.",
@@ -922,6 +1300,76 @@ object DeviceCompatibility {
}
}
internal fun recentProcessExitHistory(context: Context): ProcessExitHistory? {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return null
val activityManager = runCatching {
context.getSystemService(ActivityManager::class.java)
}.getOrNull() ?: return null
val records = runCatching {
activityManager.getHistoricalProcessExitReasons(context.packageName, 0, 16)
}.getOrNull() ?: return null
val mainProcessRecords = records
.filter { it.processName == context.packageName }
.map {
ProcessExitRecord(
timestampMs = it.timestamp,
reason = it.reason,
description = it.description.orEmpty(),
)
}
return processExitHistory(mainProcessRecords)
}
internal fun recentUnexpectedProcessExitLog(context: Context): Pair<String, String>? {
val history = recentProcessExitHistory(context) ?: return null
val latest = history.latest ?: return null
if (history.latestUnexpected?.timestampMs != latest.timestampMs) return null
val category = classifyProcessExit(latest)
val marker = recognizedSystemExitMarker(latest.description)
val time = processExitTimestamp(latest.timestampMs)
val reason = when (category) {
ProcessExitCategory.SystemPolicy -> "предыдущий процесс завершён системой"
ProcessExitCategory.ExcessiveResources -> "предыдущий процесс остановлен из-за ограничения ресурсов"
ProcessExitCategory.LowMemory -> "предыдущий процесс остановлен при нехватке памяти"
ProcessExitCategory.Crash -> "предыдущий процесс завершился со сбоем"
ProcessExitCategory.Dependency -> "предыдущий процесс остановлен после завершения системного компонента"
ProcessExitCategory.Unknown -> "причина завершения предыдущего процесса не распознана"
else -> return null
}
val markerText = if (marker.isNotBlank()) " · метка оболочки: $marker" else ""
return "process_exit_${latest.timestampMs}" to "$reason ($time)$markerText"
}
private fun processExitItem(context: Context): DeviceCheckItem {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
return DeviceCheckItem(
title = "Последнее завершение приложения",
status = "история недоступна",
details = "Android ниже версии 11 не предоставляет приложению надёжную историю причин завершения процесса.",
severity = DeviceCheckSeverity.Info,
)
}
val history = recentProcessExitHistory(context) ?: return DeviceCheckItem(
title = "Последнее завершение приложения",
status = "не удалось проверить",
details = "Android не вернул историю завершений основного процесса WDTT Plus.",
severity = DeviceCheckSeverity.Info,
)
val powerManager = runCatching { context.getSystemService(PowerManager::class.java) }.getOrNull()
val batteryOptimizationsIgnored = runCatching {
powerManager?.isIgnoringBatteryOptimizations(context.packageName)
}.getOrNull()
val backgroundRestricted = runCatching {
context.getSystemService(ActivityManager::class.java)?.isBackgroundRestricted
}.getOrNull()
return processExitHistoryItem(
history = history,
manufacturer = Build.MANUFACTURER,
backgroundRestricted = backgroundRestricted,
batteryOptimizationsIgnored = batteryOptimizationsIgnored,
)
}
private fun updateInstallPermissionItem(context: Context): DeviceCheckItem {
val canInstall = runCatching { context.packageManager.canRequestPackageInstalls() }
.getOrDefault(false)
+74 -28
View File
@@ -647,7 +647,7 @@ class MainActivity : ComponentActivity() {
)
return@launch
}
wdttConnectFlow = WdttConnectFlow.Progress("Доступ получен. Подготавливаем VPN-профиль...")
wdttConnectFlow = WdttConnectFlow.Progress("Доступ получен. Подготавливаем профиль подключения...")
var boundProfile: Int? = null
for (binding in listOf(delivery.binding, delivery.access.binding)) {
if (binding.isBlank()) continue
@@ -786,7 +786,7 @@ class MainActivity : ComponentActivity() {
) {
lifecycleScope.launch {
if (fromRemoteDocument) {
wdttConnectFlow = WdttConnectFlow.Progress("Сохраняем настройки в выбранный VPN-профиль...")
wdttConnectFlow = WdttConnectFlow.Progress("Сохраняем настройки в выбранный профиль...")
}
val store = SettingsStore(this@MainActivity)
runCatching {
@@ -826,7 +826,7 @@ class MainActivity : ComponentActivity() {
?.hashes
.isNullOrBlank()
) {
append(" Добавьте свой VK-хеш перед запуском VPN.")
append(" Добавьте свой VK-хеш перед запуском соединения.")
}
}
}
@@ -925,16 +925,16 @@ class MainActivity : ComponentActivity() {
profile = profile,
continuation = continuation,
access = access,
message = "Останавливаем VPN и ждём стабильного подключения перед входом в VK..."
message = "Останавливаем соединение и ждём стабильного доступа в интернет перед входом в VK..."
)
}
val stopResult = TunnelStopCoordinator.stopAndAwait(this@MainActivity)
if (!stopResult.succeeded) {
throw IllegalStateException(
if (stopResult == TunnelStopResult.TIMED_OUT) {
"VPN не остановился за 20 секунд. Вернитесь в приложение и повторите попытку."
"Соединение не остановилось за 20 секунд. Вернитесь в приложение и повторите попытку."
} else {
"Не удалось запросить остановку VPN. Остановите туннель и повторите попытку."
"Не удалось запросить остановку соединения. Остановите его и повторите попытку."
}
)
}
@@ -956,7 +956,7 @@ class MainActivity : ComponentActivity() {
launchRemoteContinuation(target)
wdttConnectFlow = WdttConnectFlow.Complete(
if (tunnelStoppedForVk) {
"Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически. VPN оставлен выключенным."
"Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически. Соединение оставлено выключенным."
} else {
"Страница открыта. Завершите действие там; результат вернётся в нужный профиль автоматически."
}
@@ -1023,7 +1023,7 @@ class MainActivity : ComponentActivity() {
)
}
wdttConnectFlow = WdttConnectFlow.Complete(
"VK-хеши сохранены в новом VPN-профиле."
"VK-хеши сохранены в новом профиле подключения."
)
}.onFailure { error ->
wdttConnectFlow = WdttConnectFlow.Failed(
@@ -1150,14 +1150,14 @@ private fun RoleSelectionScreen(
RoleChoiceButton(
title = "Я - юзер",
body = "Хочу подключаться бесплатно по ссылке WDTT или вручную, управлять VPN, исключениями и смотреть логи.",
body = "Хочу подключаться бесплатно по ссылке WDTT или вручную, выбирать режим, управлять исключениями и смотреть логи.",
icon = Icons.Filled.VpnKey,
onClick = { onRoleSelected("user") },
modifier = Modifier.focusRequester(initialFocusRequester),
)
RoleChoiceButton(
title = "Я - админ",
body = "Хочу подключаться к VPN и дополнительно настраивать, переносить или обслуживать свой сервер.",
body = "Хочу подключаться и дополнительно настраивать, переносить или обслуживать свой сервер.",
icon = Icons.Filled.Cloud,
onClick = { onRoleSelected("admin") }
)
@@ -1360,7 +1360,7 @@ private fun PermissionOnboardingScreen(
Text(
if (!isNotifications && batteryFallbackVisible) "Открыть настройки" else "Разрешить",
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
textAlign = TextAlign.Center,
)
}
}
@@ -1510,6 +1510,7 @@ private fun MainScreen(
val infoScrollPosition = rememberSaveable { mutableIntStateOf(0) }
var dragTargetIndex by remember { mutableIntStateOf(-1) }
var dragProgress by remember { mutableFloatStateOf(0f) }
var navigationDragActive by remember { mutableStateOf(false) }
val updateCheckIntervalMinutes by settingsStore.updateCheckIntervalMinutes.collectAsStateWithLifecycle(
initialValue = DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES
)
@@ -1701,7 +1702,7 @@ private fun MainScreen(
var updateCandidate: AppUpdateCandidate? = null
var errorMessage = ""
runCatching {
release = fetchLatestReleaseInfo(currentVersion)
release = fetchLatestReleaseInfo(context, currentVersion)
if (release == null) {
errorMessage = "Не удалось проверить"
return@runCatching
@@ -1814,20 +1815,33 @@ private fun MainScreen(
detectHorizontalDragGestures(
onDragStart = {
totalDrag = 0f
navigationDragActive = true
dragTargetIndex = -1
dragProgress = 0f
},
onDragCancel = {
navigationDragActive = false
dragTargetIndex = -1
dragProgress = 0f
},
onDragEnd = {
if (dragTargetIndex in activeNavItems.indices && dragProgress >= 0.5f) {
selectedTab = activeNavItems[dragTargetIndex].id
if (selectedTab == 3) TunnelManager.clearUnreadErrors()
}
val selectedIndex = activeNavItems.indexOfFirst {
it.id == selectedTab
}.coerceAtLeast(0)
val destinationIndex = navigationDestinationIndex(
selectedIndex = selectedIndex,
dragTargetIndex = dragTargetIndex,
dragProgress = dragProgress,
itemCount = activeNavItems.size,
)
val destination = activeNavItems.getOrNull(destinationIndex)?.id
navigationDragActive = false
dragTargetIndex = -1
dragProgress = 0f
if (destination != null) {
selectedTab = destination
if (selectedTab == 3) TunnelManager.clearUnreadErrors()
}
}
) { change, dragAmount ->
if (change.isConsumed) return@detectHorizontalDragGestures
@@ -1929,6 +1943,7 @@ private fun MainScreen(
selectedTab = selectedTab,
dragTargetIndex = dragTargetIndex,
dragProgress = dragProgress,
dragActive = navigationDragActive,
unreadErrors = unreadErrors,
tunnelRunning = tunnelRunning,
onTabSelected = { index ->
@@ -1937,6 +1952,7 @@ private fun MainScreen(
selectedTab = index
if (index == 3) TunnelManager.clearUnreadErrors()
}
navigationDragActive = false
dragTargetIndex = -1
dragProgress = 0f
},
@@ -2007,7 +2023,7 @@ private fun MainScreen(
"Клиенты, выданные доступы и настройки сохранятся. Установку с нуля выполнять не нужно."
)
Text(
"После успешной установки приложение отметит обновление для выбранного VPN-профиля.",
"После успешной установки приложение отметит обновление для выбранного профиля.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -2203,10 +2219,10 @@ private fun MainScreen(
val incomingProfileName = WdttDeepLink.parse(plan.link)?.profileName.orEmpty()
AlertDialog(
onDismissRequest = onCancelWdttDeepLinkOverwrite,
title = { Text("Профили VPN заполнены") },
title = { Text("Профили подключения заполнены") },
text = {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
Text("Свободных профилей VPN нет. Выберите профиль, который можно перезаписать:")
Text("Свободных профилей подключения нет. Выберите профиль, который можно перезаписать:")
if (incomingProfileName.isNotBlank()) {
Text("Название из подключения: «$incomingProfileName».")
}
@@ -2702,6 +2718,28 @@ private fun SharedVkHashDialog(
)
}
internal fun navigationIndicatorTarget(
selectedIndex: Int,
dragTargetIndex: Int,
dragProgress: Float,
itemCount: Int,
): Float {
val selected = selectedIndex.coerceIn(0, (itemCount - 1).coerceAtLeast(0))
if (dragTargetIndex !in 0 until itemCount) return selected.toFloat()
return selected + (dragTargetIndex - selected) * dragProgress.coerceIn(0f, 1f)
}
internal fun navigationDestinationIndex(
selectedIndex: Int,
dragTargetIndex: Int,
dragProgress: Float,
itemCount: Int,
): Int {
val selected = selectedIndex.coerceIn(0, (itemCount - 1).coerceAtLeast(0))
if (dragTargetIndex !in 0 until itemCount) return selected
return if (dragProgress.coerceIn(0f, 1f) >= 0.5f) dragTargetIndex else selected
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun ProxyNavigationBar(
@@ -2709,6 +2747,7 @@ private fun ProxyNavigationBar(
selectedTab: Int,
dragTargetIndex: Int,
dragProgress: Float,
dragActive: Boolean,
unreadErrors: Int,
tunnelRunning: Boolean,
onTabSelected: (Int) -> Unit,
@@ -2751,8 +2790,22 @@ private fun ProxyNavigationBar(
}
}
LaunchedEffect(selectedVisualIndex) {
if (dragTargetIndex !in navItems.indices) {
LaunchedEffect(
selectedVisualIndex,
dragTargetIndex,
dragProgress,
dragActive,
navItems.size,
) {
val target = navigationIndicatorTarget(
selectedIndex = selectedVisualIndex,
dragTargetIndex = dragTargetIndex,
dragProgress = dragProgress,
itemCount = navItems.size,
)
if (dragActive) {
indicatorIndex.snapTo(target)
} else {
indicatorIndex.animateTo(
targetValue = selectedVisualIndex.toFloat(),
animationSpec = tween(
@@ -2763,13 +2816,6 @@ private fun ProxyNavigationBar(
}
}
LaunchedEffect(selectedVisualIndex, dragTargetIndex, dragProgress) {
if (dragTargetIndex in navItems.indices) {
val target = selectedVisualIndex.toFloat() + (dragTargetIndex - selectedVisualIndex) * dragProgress
indicatorIndex.snapTo(target)
}
}
BoxWithConstraints(
modifier = modifier
.fillMaxWidth()
@@ -10,6 +10,8 @@ internal data class NativeClientStartupSecrets(
val connectionPassword: String = "",
val customVkClientId: String = "",
val customVkClientSecret: String = "",
val socksUsername: String = "",
val socksPassword: String = "",
)
internal fun nativeClientStartupConfigLine(secrets: NativeClientStartupSecrets): String {
@@ -18,6 +20,8 @@ internal fun nativeClientStartupConfigLine(secrets: NativeClientStartupSecrets):
.put("connection_password", secrets.connectionPassword)
.put("custom_vk_client_id", secrets.customVkClientId)
.put("custom_vk_client_secret", secrets.customVkClientSecret)
.put("socks_username", secrets.socksUsername)
.put("socks_password", secrets.socksPassword)
.toString()
val encoded = Base64.getUrlEncoder()
.withoutPadding()
@@ -0,0 +1,250 @@
package com.wdtt.plus
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.URI
import java.security.SecureRandom
internal const val PROXY_ACCESS_DEVICE = "device"
internal const val PROXY_ACCESS_LAN = "lan"
internal const val PROXY_ACCESS_BOTH = "both"
internal data class ProxyInterfaceAddress(
val interfaceName: String,
val host: String,
val prefixLength: Int,
)
internal data class ProxyListenBinding(
val host: String,
val allowedCidr: String,
)
internal data class ProxyCopyOption(
val protocolLabel: String,
val accessLabel: String,
val address: String,
val uri: String,
)
internal fun normalizeProxyAccess(value: String?): String = when (value?.trim()?.lowercase()) {
PROXY_ACCESS_DEVICE -> PROXY_ACCESS_DEVICE
PROXY_ACCESS_LAN -> PROXY_ACCESS_LAN
PROXY_ACCESS_BOTH -> PROXY_ACCESS_BOTH
else -> PROXY_ACCESS_BOTH
}
internal fun resolveStoredProxyAccess(
value: String?,
legacyLanEnabled: Boolean,
explicitlyActivated: Boolean,
): String = value?.takeIf { it.isNotBlank() }?.let(::normalizeProxyAccess)
?: if (explicitlyActivated) {
if (legacyLanEnabled) PROXY_ACCESS_LAN else PROXY_ACCESS_DEVICE
} else {
PROXY_ACCESS_BOTH
}
internal fun proxyAccessIncludesDevice(value: String?): Boolean =
normalizeProxyAccess(value) != PROXY_ACCESS_LAN
internal fun proxyAccessIncludesLan(value: String?): Boolean =
normalizeProxyAccess(value) != PROXY_ACCESS_DEVICE
internal fun proxyAccessNeedsAuthentication(value: String?): Boolean =
proxyAccessIncludesLan(value)
internal fun expectedProxyReadyAddresses(
access: String?,
port: Int,
lanHost: String?,
): List<String> = buildList {
if (proxyAccessIncludesDevice(access)) {
add("$SOCKS5_LOOPBACK_HOST:$port")
}
if (proxyAccessIncludesLan(access) && !lanHost.isNullOrBlank()) {
add("$lanHost:$port")
}
}
internal fun selectProxyLanBinding(
addresses: List<ProxyInterfaceAddress>,
): ProxyListenBinding? = addresses
.asSequence()
.filter { candidate ->
candidate.prefixLength in 8..30 &&
isPrivateIpv4(candidate.host) &&
!isTunnelLikeInterface(candidate.interfaceName)
}
.sortedWith(
compareBy<ProxyInterfaceAddress> { interfacePriority(it.interfaceName) }
.thenBy { it.interfaceName }
.thenBy { it.host },
)
.mapNotNull { candidate ->
val restrictedPrefixLength = maxOf(candidate.prefixLength, 24)
ipv4NetworkCidr(candidate.host, restrictedPrefixLength)?.let { cidr ->
ProxyListenBinding(candidate.host, cidr)
}
}
.firstOrNull()
internal fun findProxyLanBinding(): ProxyListenBinding? = runCatching {
val candidates = buildList {
val interfaces = NetworkInterface.getNetworkInterfaces() ?: return@buildList
while (interfaces.hasMoreElements()) {
val networkInterface = interfaces.nextElement()
runCatching {
if (!networkInterface.isUp || networkInterface.isLoopback) return@runCatching
networkInterface.interfaceAddresses.forEach { interfaceAddress ->
val address = interfaceAddress.address as? Inet4Address ?: return@forEach
add(
ProxyInterfaceAddress(
interfaceName = networkInterface.name.orEmpty(),
host = address.hostAddress.orEmpty(),
prefixLength = interfaceAddress.networkPrefixLength.toInt(),
),
)
}
}
}
}
selectProxyLanBinding(candidates)
}.getOrNull()
internal fun proxyDisplayAddress(
lanEnabled: Boolean,
port: Int,
readyAddress: String? = null,
lanBinding: ProxyListenBinding? = null,
): String = readyAddress?.takeIf { it.isNotBlank() }
?: if (lanEnabled) {
lanBinding?.let { "${it.host}:$port" } ?: "Сеть:$port"
} else {
"$SOCKS5_LOOPBACK_HOST:$port"
}
internal fun proxyImportUri(
mode: String,
readyAddress: String,
authEnabled: Boolean,
username: String,
password: String,
): String? {
val normalizedMode = normalizeTunnelMode(mode)
val (scheme, title) = when (normalizedMode) {
TUNNEL_MODE_SOCKS5 -> "socks5" to "WDTT-Plus SOCKS5"
TUNNEL_MODE_HTTP -> "http" to "WDTT-Plus HTTP"
else -> return null
}
if (authEnabled &&
(!isValidSocks5Credential(username) || !isValidSocks5Credential(password))
) {
return null
}
val endpoint = runCatching { URI("proxy://$readyAddress") }.getOrNull() ?: return null
val host = endpoint.host?.takeIf { it.isNotBlank() } ?: return null
val port = endpoint.port.takeIf { it in 1..65535 } ?: return null
val userInfo = if (authEnabled) "$username:$password" else null
return runCatching {
URI(scheme, userInfo, host, port, null, null, title).toASCIIString()
}.getOrNull()
}
internal fun proxyCopyOptions(
mode: String,
readyAddresses: List<String>,
authEnabled: Boolean,
username: String,
password: String,
): List<ProxyCopyOption> {
val protocols = when (normalizeTunnelMode(mode)) {
TUNNEL_MODE_AUTO -> listOf(
TUNNEL_MODE_SOCKS5 to "SOCKS5",
TUNNEL_MODE_HTTP to "HTTP",
)
TUNNEL_MODE_SOCKS5 -> listOf(TUNNEL_MODE_SOCKS5 to "SOCKS5")
TUNNEL_MODE_HTTP -> listOf(TUNNEL_MODE_HTTP to "HTTP")
else -> emptyList()
}
return readyAddresses
.distinct()
.sortedBy { if (it.startsWith("$SOCKS5_LOOPBACK_HOST:")) 0 else 1 }
.flatMap { address ->
val accessLabel = if (address.startsWith("$SOCKS5_LOOPBACK_HOST:")) {
"Устройство"
} else {
"Сеть"
}
protocols.mapNotNull { (protocol, protocolLabel) ->
proxyImportUri(
mode = protocol,
readyAddress = address,
authEnabled = authEnabled,
username = username,
password = password,
)?.let { uri ->
ProxyCopyOption(protocolLabel, accessLabel, address, uri)
}
}
}
}
internal fun generateProxyPassword(length: Int = 18): String {
val alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"
val random = SecureRandom()
return buildString(length.coerceIn(12, 64)) {
repeat(length.coerceIn(12, 64)) {
append(alphabet[random.nextInt(alphabet.length)])
}
}
}
private fun isTunnelLikeInterface(name: String): Boolean {
val normalized = name.lowercase()
return listOf("tun", "tap", "wg", "ppp", "rmnet", "dummy", "v4-").any(normalized::startsWith)
}
private fun interfacePriority(name: String): Int {
val normalized = name.lowercase()
return when {
normalized.startsWith("ap") || normalized.startsWith("swlan") ||
normalized.startsWith("softap") -> 0
normalized.startsWith("wlan") || normalized.startsWith("wifi") -> 1
normalized.startsWith("rndis") || normalized.startsWith("usb") -> 2
normalized.startsWith("eth") -> 3
else -> 4
}
}
private fun isPrivateIpv4(value: String): Boolean {
val bytes = parseIpv4(value) ?: return false
val first = bytes[0]
val second = bytes[1]
return first == 10 ||
first == 172 && second in 16..31 ||
first == 192 && second == 168
}
private fun ipv4NetworkCidr(host: String, prefixLength: Int): String? {
if (prefixLength !in 8..30) return null
val bytes = parseIpv4(host) ?: return null
var address = 0
bytes.forEach { part -> address = (address shl 8) or part }
val mask = (-1 shl (32 - prefixLength))
val network = address and mask
val networkHost = listOf(24, 16, 8, 0).joinToString(".") { shift ->
((network ushr shift) and 0xff).toString()
}
return "$networkHost/$prefixLength"
}
private fun parseIpv4(value: String): IntArray? {
val parts = value.split('.')
if (parts.size != 4) return null
return IntArray(4) { index ->
val part = parts[index]
if (part.isEmpty() || part.length > 3 || part.any { !it.isDigit() }) return null
part.toIntOrNull()?.takeIf { it in 0..255 } ?: return null
}
}
@@ -16,6 +16,7 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
class QuickToggleTileService : TileService() {
@@ -47,6 +48,8 @@ class QuickToggleTileService : TileService() {
)
}.combine(settingsStore.activeAccessLifecycle) { state, accessLifecycle ->
state.copy(accessLifecycle = accessLifecycle)
}.combine(TunnelManager.activeMode) { state, tunnelMode ->
state.copy(tunnelMode = tunnelMode)
}.collect { uiState ->
updateTile(uiState)
}
@@ -66,31 +69,35 @@ class QuickToggleTileService : TileService() {
runCatching {
val running = TunnelManager.running.value
val trustedWifiWaiting = TrustedWifiManager.state.value.waiting
val action = if (running || trustedWifiWaiting) {
TunnelToggleAction.STOP
} else {
tunnelToggleAction(
if (running || trustedWifiWaiting) {
startService(Intent(this, TunnelService::class.java).apply { action = "STOP" })
return
}
scope.launch {
val mode = SettingsStore(this@QuickToggleTileService).proxyMode.first()
val action = tunnelToggleAction(
running = false,
trustedWifiWaiting = false,
vpnPermissionRequired = VpnService.prepare(this) != null,
vpnPermissionRequired = tunnelModeNeedsVpnPermission(mode) &&
VpnService.prepare(this@QuickToggleTileService) != null,
)
}
when (action) {
when (action) {
TunnelToggleAction.STOP -> {
// Состояние плитки изменится после фактической остановки службы.
startService(
Intent(this, TunnelService::class.java).apply { this.action = "STOP" }
Intent(this@QuickToggleTileService, TunnelService::class.java)
.setAction("STOP")
)
}
TunnelToggleAction.REQUEST_VPN_PERMISSION -> {
Toast.makeText(
this,
this@QuickToggleTileService,
"Откройте WDTT Plus и выдайте VPN-разрешение",
Toast.LENGTH_LONG
).show()
openMainActivity()
}
TunnelToggleAction.START -> scope.launch {
TunnelToggleAction.START -> {
try {
val intent = buildTunnelStartIntentFromSettings(this@QuickToggleTileService)
if (intent == null) {
@@ -117,6 +124,7 @@ class QuickToggleTileService : TileService() {
).show()
}
}
}
}
}.onFailure { e ->
Log.e("QuickToggleTile", "Crash prevented in onClick", e)
@@ -159,7 +167,7 @@ class QuickToggleTileService : TileService() {
if (Build.VERSION.SDK_INT >= 29) {
subtitle = when {
waiting -> uiState.trustedWifi.ssid.ifBlank { "Wi-Fi" }
running -> ""
running -> tunnelModeStatusLabel(uiState.tunnelMode)
accessBlocked -> uiState.accessLifecycle.title
.ifBlank { uiState.accessLifecycle.fallbackTitle() }
else -> "Отключено"
@@ -179,6 +187,7 @@ class QuickToggleTileService : TileService() {
val activeTunnelProfile: Int?,
val profileNames: List<String>,
val accessLifecycle: AccessLifecycleUiState,
val tunnelMode: String = TUNNEL_MODE_VPN,
)
@SuppressLint("StartActivityAndCollapseDeprecated")
@@ -7,6 +7,7 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URI
import java.net.URL
@@ -193,23 +194,34 @@ object RemoteActionCatalogGateway {
connection.readTimeout = 6_000
connection.setRequestProperty("Accept", "application/json")
val status = connection.responseCode
if (status !in 200..299) return RemoteActionCatalog.Empty
parse(connection.inputStream.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) })
if (status !in 200..299) {
throw IOException("Каталог действий временно недоступен: HTTP $status")
}
val body = connection.inputStream.use { it.readUtf8TextLimited(MAX_RESPONSE_CHARS) }
parseValidCatalog(body)
?: throw IOException("Получен некорректный каталог действий")
} finally {
connection?.disconnect()
}
}
internal fun parse(body: String): RemoteActionCatalog {
if (body.length > MAX_RESPONSE_CHARS) return RemoteActionCatalog.Empty
internal fun parse(body: String): RemoteActionCatalog =
parseValidCatalog(body) ?: RemoteActionCatalog.Empty
internal fun parseValidCatalog(body: String): RemoteActionCatalog? {
if (body.length > MAX_RESPONSE_CHARS) return null
val root = runCatching { JSONObject(body) }.getOrNull()
?: return RemoteActionCatalog.Empty
if (root.optInt("version", 0) != 1) return RemoteActionCatalog.Empty
val source = root.optJSONObject("actions") ?: return RemoteActionCatalog.Empty
val actions = placements.mapNotNull { placement ->
val item = source.optJSONObject(placement) ?: return@mapNotNull null
parseAction(item)?.let { placement to it }
}.toMap()
?: return null
if (root.optInt("version", 0) != 1) return null
val source = root.optJSONObject("actions") ?: return null
val actions = buildMap {
placements.forEach { placement ->
if (!source.has(placement)) return@forEach
val item = source.optJSONObject(placement) ?: return null
val action = parseAction(item) ?: return null
put(placement, action)
}
}
return RemoteActionCatalog(actions)
}
@@ -215,22 +215,43 @@ data class ServerStoredBackupDocument(
)
object ServerAdminClient {
private const val SAFE_DIRECT_CONNECT_TIMEOUT_MS = 4_000
private const val ADMIN_TIMEOUT = 45_000L
private const val RESTART_TIMEOUT = 70_000L
private const val BACKUP_TIMEOUT = 120_000L
private const val MAX_BACKUP_DOCUMENT_BYTES = 8 * 1024 * 1024
suspend fun list(target: ServerAdminTarget): ServerAdminState = withContext(Dispatchers.IO) {
withSession(target) { ssh ->
parseState(callAdmin(ssh, target, listOf("list")))
}
parseState(callSafeAdmin(target, listOf("list")))
}
suspend fun details(target: ServerAdminTarget, password: String): ServerClientInfo = withContext(Dispatchers.IO) {
withSession(target) { ssh ->
val json = callAdmin(ssh, target, listOf("details", "--password", password))
json.optJSONObject("password")?.let(::parseClient)
?: throw IllegalStateException("сервер не вернул данные клиента")
val json = callSafeAdmin(target, listOf("details", "--password", password))
json.optJSONObject("password")?.let(::parseClient)
?: throw IllegalStateException("сервер не вернул данные клиента")
}
internal suspend fun safeInspectThroughTunnel(
target: ServerAdminTarget,
operationArgs: List<String>,
timeout: Long = ADMIN_TIMEOUT,
): String {
require(operationArgs.isNotEmpty()) { "Не указан вид безопасной проверки" }
val availability = TunnelManager.deploySafeRelayAvailability(target.host)
if (!availability.available) {
throw IllegalStateException(availability.unavailableMessage())
}
val args = listOf("safe-inspect") + operationArgs
return when (val relay = TunnelManager.executeDeploySafeRequest(
targetHost = target.host,
requestJson = adminRequestJson(target, args),
timeoutMs = timeout.coerceAtLeast(15_000L),
)) {
is DeploySafeRelayResult.Success -> parseAdminRelayResponse(relay.payload)
.optString("safe_output", "")
.takeIf(String::isNotBlank)
?: throw IllegalStateException("сервер не вернул результат безопасной проверки")
is DeploySafeRelayResult.Unavailable -> throw IllegalStateException(relay.reason)
}
}
@@ -392,7 +413,7 @@ object ServerAdminClient {
runArgsAction(target, listOf("reset-traffic"))
suspend fun backupStatus(target: ServerAdminTarget): ServerBackupManagerInfo = withContext(Dispatchers.IO) {
withSession(target) { ssh -> parseBackupStatus(callAdmin(ssh, target, listOf("backup-status"), BACKUP_TIMEOUT)) }
parseBackupStatus(callSafeAdmin(target, listOf("backup-status"), BACKUP_TIMEOUT))
}
suspend fun configureBackups(
@@ -425,31 +446,29 @@ object ServerAdminClient {
reason: String = "manual"
): ServerBackupManagerInfo = withContext(Dispatchers.IO) {
require(reason in setOf("manual", "pre_deploy", "pre_restore")) { "Некорректная причина резервной копии" }
withSession(target) {
ssh -> parseBackupStatus(
callAdmin(ssh, target, listOf("backup-create", "--reason", reason), BACKUP_TIMEOUT)
)
if (reason == "manual") {
parseBackupStatus(callSafeAdmin(target, listOf("backup-create", "--reason", reason), BACKUP_TIMEOUT))
} else {
withSession(target) { ssh ->
parseBackupStatus(callAdmin(ssh, target, listOf("backup-create", "--reason", reason), BACKUP_TIMEOUT))
}
}
}
suspend fun verifyBackup(target: ServerAdminTarget, id: String): ServerStoredBackupInfo = withContext(Dispatchers.IO) {
requireBackupId(id)
withSession(target) { ssh ->
parseBackupInfo(
callAdmin(ssh, target, listOf("backup-verify", "--id", id), BACKUP_TIMEOUT)
.getJSONObject("backup")
)
}
parseBackupInfo(
callSafeAdmin(target, listOf("backup-verify", "--id", id), BACKUP_TIMEOUT)
.getJSONObject("backup")
)
}
suspend fun exportBackup(target: ServerAdminTarget, id: String): ServerStoredBackupDocument = withContext(Dispatchers.IO) {
requireBackupId(id)
withSession(target) { ssh ->
parseBackupDocument(
callAdmin(ssh, target, listOf("backup-export", "--id", id), BACKUP_TIMEOUT)
.getJSONObject("backup_document")
)
}
parseBackupDocument(
callSafeAdmin(target, listOf("backup-export", "--id", id), BACKUP_TIMEOUT)
.getJSONObject("backup_document")
)
}
suspend fun deleteBackup(target: ServerAdminTarget, id: String): ServerBackupManagerInfo = withContext(Dispatchers.IO) {
@@ -491,10 +510,14 @@ object ServerAdminClient {
withSession(target) { ssh -> actionFromResponse(callAdmin(ssh, target, args)) }
}
private fun <T> withSession(target: ServerAdminTarget, block: (AdminSshClient) -> T): T {
private fun <T> withSession(
target: ServerAdminTarget,
safeReadOnly: Boolean = false,
block: (AdminSshClient) -> T,
): T {
var session: Session? = null
try {
session = createSession(target)
session = createSession(target, safeReadOnly)
return block(AdminSshClient(session, target.sshPassword))
} finally {
try { session?.disconnect() } catch (_: Exception) {}
@@ -523,6 +546,103 @@ object ServerAdminClient {
return json
}
private fun adminRequestJson(target: ServerAdminTarget, args: List<String>): String =
JSONObject()
.put("main_password", target.mainPassword)
.put("args", JSONArray(args))
.toString()
private suspend fun callSafeAdmin(
target: ServerAdminTarget,
args: List<String>,
timeout: Long = ADMIN_TIMEOUT,
): JSONObject {
val availability = TunnelManager.deploySafeRelayAvailability(target.host)
if (!availability.transportAvailable) {
return withSession(target, safeReadOnly = true) { ssh -> callAdmin(ssh, target, args, timeout) }
}
var directFailure: Exception? = null
var session: Session? = null
try {
session = createSession(
target = target,
safeReadOnly = true,
connectTimeoutMs = SAFE_DIRECT_CONNECT_TIMEOUT_MS,
)
} catch (error: Exception) {
if (!isConnectivityFailure(error)) throw error
directFailure = error
}
val connectedSession = session
if (connectedSession != null) {
try {
// После установленного SSH-соединения не повторяем команду другим
// путём: ответ мог потеряться уже после выполнения на сервере.
return callAdmin(AdminSshClient(connectedSession, target.sshPassword), target, args, timeout)
} finally {
runCatching { connectedSession.disconnect() }
}
}
if (!availability.available) {
throw IllegalStateException(availability.unavailableMessage(), directFailure)
}
TunnelManager.noteDeployNetworkRoute(
key = "deploy_safe_relay",
message = "Прямое подключение не ответило; безопасная операция выполняется через активный WDTT.",
warning = false,
)
return when (val relay = TunnelManager.executeDeploySafeRequest(
targetHost = target.host,
requestJson = adminRequestJson(target, args),
timeoutMs = timeout.coerceAtLeast(15_000L),
)) {
is DeploySafeRelayResult.Success -> parseAdminRelayResponse(relay.payload)
is DeploySafeRelayResult.Unavailable -> {
if (relay.reason.indicatesOldDeployRelay()) {
TunnelManager.noteDeployNetworkRoute(
key = "deploy_safe_relay_legacy",
message = "Сервер ещё не поддерживает безопасный канал Деплоя; используется совместимое прямое SSH-подключение.",
warning = true,
)
return withSession(target, safeReadOnly = true) { ssh -> callAdmin(ssh, target, args, timeout) }
}
val directText = directFailure?.message.orEmpty().substringBefore(" WDTT Plus")
throw IllegalStateException(
buildString {
append("Безопасная операция не выполнена через активный WDTT: ")
append(relay.reason.ifBlank { "сервер не ответил" })
if (directText.isNotBlank()) append(". Прямая попытка: $directText")
},
directFailure,
)
}
}
}
private fun parseAdminRelayResponse(payload: String): JSONObject {
val json = runCatching { JSONObject(payload) }
.getOrElse { throw IllegalStateException("сервер вернул повреждённый ответ безопасной операции", it) }
if (!json.optBoolean("ok", false)) {
throw IllegalStateException(friendlyAdminError(json.optString("message", "операция отклонена сервером")))
}
return json
}
private fun isConnectivityFailure(error: Throwable): Boolean =
isSshConnectivityFailure(
generateSequence(error) { it.cause }
.mapNotNull { it.message?.takeIf(String::isNotBlank) }
.joinToString(": "),
)
private fun String.indicatesOldDeployRelay(): Boolean {
val value = lowercase()
return "ещё не поддерживает" in value || "не поддерживает проверку через туннель" in value
}
private fun requireBackupId(id: String) {
require(Regex("^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{12}$").matches(id)) {
"Некорректный идентификатор резервной копии"
@@ -786,7 +906,11 @@ object ServerAdminClient {
status = json.optString("status"), note = json.optString("note")
)
private fun createSession(target: ServerAdminTarget): Session {
private fun createSession(
target: ServerAdminTarget,
safeReadOnly: Boolean = false,
connectTimeoutMs: Int = 20_000,
): Session {
return createSshSession(
host = target.host,
user = target.user,
@@ -796,7 +920,13 @@ object ServerAdminClient {
privateKeyPassphrase = target.sshKeyPassphrase,
allowPasswordAuthentication = target.allowPasswordAuthentication
),
port = target.sshPort
port = target.sshPort,
routePolicy = if (safeReadOnly) {
SshRoutePolicy.SAFE_READ_ONLY_DIRECT
} else {
SshRoutePolicy.SERVER_MUTATION_DIRECT_ONLY
},
connectTimeoutMs = connectTimeoutMs,
)
}
@@ -839,12 +969,12 @@ object ServerAdminClient {
"root privileges required" in lower || "sudo not found" in lower ->
"для управления нужны root-права или sudo на сервере."
"connection refused" in lower ->
"сервер отклонил SSH-подключение. Проверьте SSH-порт."
"Сервер отклонил SSH-подключение. Проверьте SSH-порт."
"timeout" in lower || "timed out" in lower ->
"сервер не ответил вовремя."
"Сервер не ответил вовремя."
text.isBlank() -> "операция не выполнена"
else -> text.take(220)
}
}.let(::capitalizeUserSentence)
}
}
+248 -16
View File
@@ -49,6 +49,27 @@ enum class SleepBatteryMode(val storedValue: String) {
}
}
enum class ScreenOffMode(val storedValue: String) {
BALANCED("balanced"),
HOLD_CONNECTION("hold_connection"),
SAVE_BATTERY("save_battery");
companion object {
fun fromStoredValue(value: String?): ScreenOffMode? =
entries.firstOrNull { it.storedValue == value }
}
}
internal fun resolveScreenOffMode(
storedValue: String?,
legacyPauseVpnDuringSleep: Boolean,
): ScreenOffMode = ScreenOffMode.fromStoredValue(storedValue)
?: if (legacyPauseVpnDuringSleep) {
ScreenOffMode.SAVE_BATTERY
} else {
ScreenOffMode.BALANCED
}
internal enum class SleepBatteryRuntimePhase(val storedValue: String) {
IDLE("idle"),
WAITING_TO_PAUSE("waiting_to_pause"),
@@ -121,9 +142,9 @@ data class WdttDeepLinkValidation(
return if (parts != null && errors.isEmpty()) {
buildString {
if (parts.hashes.isBlank()) {
append("Ссылка wdtt:// распознана. Добавьте свой VK-хеш перед запуском VPN.")
append("Ссылка wdtt:// распознана. Добавьте свой VK-хеш перед запуском соединения.")
} else {
append("Ссылка wdtt:// корректна. VPN сможет использовать эти данные для подключения.")
append("Ссылка wdtt:// корректна. WDTT Plus сможет использовать эти данные для подключения.")
}
parts?.profileName?.takeIf { it.isNotBlank() }?.let {
append("\nНазвание профиля: «")
@@ -137,7 +158,7 @@ data class WdttDeepLinkValidation(
}
} else {
buildString {
append("VPN не запустится по этой ссылке, потому что в ней есть ошибки:\n")
append("Соединение не запустится по этой ссылке, потому что в ней есть ошибки:\n")
append(errors.joinToString("\n") { "• $it" })
append("\n\n")
append(supportedWdttLinkFormats)
@@ -226,6 +247,14 @@ data class TunnelProfileSnapshot(
val customVkCredentialsEnabled: Boolean,
val customVkClientId: String,
val customVkClientSecret: String,
val proxyMode: String = TUNNEL_MODE_VPN,
val proxyPort: Int = DEFAULT_SOCKS5_PORT,
val proxyUdpEnabled: Boolean = true,
val proxyAccess: String = PROXY_ACCESS_BOTH,
val proxyLanEnabled: Boolean = false,
val proxyAuthEnabled: Boolean = false,
val proxyUsername: String = "",
val proxyPassword: String = "",
)
data class RemoteAttachmentCandidate(
@@ -336,6 +365,14 @@ data class ActiveTunnelProfileUiSnapshot(
val accessLifecycle: AccessLifecycleUiState,
val accessLifecycleDismissedSignature: String,
val profileMaxWorkers: Int,
val proxyMode: String = TUNNEL_MODE_VPN,
val proxyPort: Int = DEFAULT_SOCKS5_PORT,
val proxyUdpEnabled: Boolean = true,
val proxyAccess: String = PROXY_ACCESS_BOTH,
val proxyLanEnabled: Boolean = false,
val proxyAuthEnabled: Boolean = false,
val proxyUsername: String = "",
val proxyPassword: String = "",
)
data class ActiveTunnelAccessUiSnapshot(
@@ -453,7 +490,7 @@ object WdttDeepLink {
if (invalidHashesProvided) {
errors += "VK-хеш содержит недопустимые символы. Используйте латинские буквы, цифры, _ и - либо ссылку VK-звонка."
} else if (allowMissingHashes) {
warnings += "VK-хеши ещё не заполнены. Добавьте их в WDTT Plus перед запуском VPN."
warnings += "VK-хеши ещё не заполнены. Добавьте их в WDTT Plus перед запуском соединения."
} else {
errors += "Нет рабочего VK-хеша. Нужен хеш из латинских букв, цифр, _ или - либо ссылка VK-звонка."
}
@@ -576,6 +613,7 @@ class SettingsStore(context: Context) {
private val TRUSTED_WIFI_WAITING = booleanPreferencesKey("trusted_wifi_waiting")
private val TRUSTED_WIFI_WAITING_SSID = stringPreferencesKey("trusted_wifi_waiting_ssid")
private val PAUSE_VPN_DURING_SLEEP = booleanPreferencesKey("pause_vpn_during_sleep")
private val SCREEN_OFF_MODE = stringPreferencesKey("screen_off_mode")
private val PAUSE_VPN_DURING_SLEEP_DELAY_MINUTES =
intPreferencesKey("pause_vpn_during_sleep_delay_minutes")
private val PAUSE_VPN_DURING_SLEEP_MODE =
@@ -713,9 +751,16 @@ class SettingsStore(context: Context) {
private val DEPLOY_BOT_TOKEN_ENCRYPTED = stringPreferencesKey("deploy_bot_token_encrypted")
// ═══ Proxy Mode ═══
private val PROXY_MODE = stringPreferencesKey("proxy_mode") // "tun" or "socks5"
private val PROXY_MODE = stringPreferencesKey("proxy_mode") // "vpn", "socks5" or "http"
private val PROXY_HOST = stringPreferencesKey("proxy_host")
private val PROXY_PORT = intPreferencesKey("proxy_port")
private val PROXY_UDP_ENABLED = booleanPreferencesKey("proxy_udp_enabled")
private val PROXY_ACCESS = stringPreferencesKey("proxy_access")
private val PROXY_LAN_ENABLED = booleanPreferencesKey("proxy_lan_enabled")
private val PROXY_AUTH_ENABLED = booleanPreferencesKey("proxy_auth_enabled")
private val PROXY_MODE_ACTIVATED = booleanPreferencesKey("proxy_mode_activated")
private val PROXY_USERNAME = stringPreferencesKey("proxy_username")
private val PROXY_PASSWORD_ENCRYPTED = stringPreferencesKey("proxy_password_encrypted")
// ═══ Captcha Solve Mode ═══
private val VKCALLS_PREFLIGHT = booleanPreferencesKey("vkcalls_preflight")
@@ -856,7 +901,10 @@ class SettingsStore(context: Context) {
DEPLOY_BOT_TOKEN,
DEPLOY_BOT_TOKEN_ENCRYPTED,
PROXY_MODE,
PROXY_ACCESS,
PROXY_HOST,
PROXY_USERNAME,
PROXY_PASSWORD_ENCRYPTED,
CAPTCHA_MODE,
CAPTCHA_SOLVE_METHOD,
CAPTCHA_WBV_SOLVE_METHOD,
@@ -906,6 +954,10 @@ class SettingsStore(context: Context) {
ACCESS_DISMISSIBLE,
PROFILE_VALUES_SYNC_PENDING,
PROFILE_EXCHANGE_ACTION_AVAILABLE,
PROXY_UDP_ENABLED,
PROXY_LAN_ENABLED,
PROXY_AUTH_ENABLED,
PROXY_MODE_ACTIVATED,
)
internal fun resettableProfilePreferenceNames(): Set<String> =
@@ -1019,6 +1071,33 @@ class SettingsStore(context: Context) {
profileMaxWorkers =
(it[getProfileKey(PROFILE_MAX_WORKERS, profile)] ?: 0)
.coerceIn(0, APP_MAX_WORKERS),
proxyMode = resolveStoredTunnelMode(
it[getProfileKey(PROXY_MODE, profile)],
it[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
),
proxyPort = normalizeSocks5Port(
it[getProfileKey(PROXY_PORT, profile)] ?: DEFAULT_SOCKS5_PORT
),
proxyUdpEnabled = it[getProfileKey(PROXY_UDP_ENABLED, profile)] ?: true,
proxyAccess = resolveStoredProxyAccess(
it[getProfileKey(PROXY_ACCESS, profile)],
it[getProfileKey(PROXY_LAN_ENABLED, profile)] ?: false,
it[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
),
proxyLanEnabled = proxyAccessIncludesLan(
resolveStoredProxyAccess(
it[getProfileKey(PROXY_ACCESS, profile)],
it[getProfileKey(PROXY_LAN_ENABLED, profile)] ?: false,
it[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
),
),
proxyAuthEnabled = it[getProfileKey(PROXY_AUTH_ENABLED, profile)] ?: false,
proxyUsername = truncateSocks5Credential(
it[getProfileKey(PROXY_USERNAME, profile)].orEmpty(),
),
proxyPassword = truncateSocks5Credential(
readProtectedSecret(it, PROXY_PASSWORD_ENCRYPTED, profile),
),
)
}
}.distinctUntilChanged()
@@ -1119,9 +1198,15 @@ class SettingsStore(context: Context) {
val trustedWifiWaitingSsid: Flow<String> = preferencesFlow.map {
sanitizeTrustedWifiSsid(it[TRUSTED_WIFI_WAITING_SSID].orEmpty())
}
val pauseVpnDuringSleep: Flow<Boolean> = preferencesFlow.map {
it[PAUSE_VPN_DURING_SLEEP] ?: false
}
val screenOffMode: Flow<ScreenOffMode> = preferencesFlow.map { prefs ->
resolveScreenOffMode(
storedValue = prefs[SCREEN_OFF_MODE],
legacyPauseVpnDuringSleep = prefs[PAUSE_VPN_DURING_SLEEP] ?: false,
)
}.distinctUntilChanged()
val pauseVpnDuringSleep: Flow<Boolean> = screenOffMode.map {
it == ScreenOffMode.SAVE_BATTERY
}.distinctUntilChanged()
val pauseVpnDuringSleepDelayMinutes: Flow<Int> = preferencesFlow.map {
normalizeSleepPauseDelayMinutes(
it[PAUSE_VPN_DURING_SLEEP_DELAY_MINUTES] ?: DEFAULT_SLEEP_PAUSE_DELAY_MINUTES
@@ -1401,7 +1486,10 @@ class SettingsStore(context: Context) {
// ═══ Proxy Mode ═══
val proxyMode: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROXY_MODE, profile)] ?: "tun"
resolveStoredTunnelMode(
prefs[getProfileKey(PROXY_MODE, profile)],
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
)
}
val proxyHost: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
@@ -1409,8 +1497,42 @@ class SettingsStore(context: Context) {
}
val proxyPort: Flow<Int> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROXY_PORT, profile)] ?: 1080
normalizeSocks5Port(prefs[getProfileKey(PROXY_PORT, profile)] ?: DEFAULT_SOCKS5_PORT)
}
val proxyUdpEnabled: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROXY_UDP_ENABLED, profile)] ?: true
}
val proxyAccess: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
resolveStoredProxyAccess(
prefs[getProfileKey(PROXY_ACCESS, profile)],
prefs[getProfileKey(PROXY_LAN_ENABLED, profile)] ?: false,
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
)
}
val proxyLanEnabled: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
proxyAccessIncludesLan(
resolveStoredProxyAccess(
prefs[getProfileKey(PROXY_ACCESS, profile)],
prefs[getProfileKey(PROXY_LAN_ENABLED, profile)] ?: false,
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
),
)
}
val proxyAuthEnabled: Flow<Boolean> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROXY_AUTH_ENABLED, profile)] ?: false
}
val proxyUsername: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
truncateSocks5Credential(prefs[getProfileKey(PROXY_USERNAME, profile)].orEmpty())
}
val proxyPassword: Flow<String> = preferencesFlow.map { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
truncateSocks5Credential(readProtectedSecret(prefs, PROXY_PASSWORD_ENCRYPTED, profile))
}.flowOn(Dispatchers.IO)
// ═══ Captcha Solve Mode ═══
val vkCallsPreflight: Flow<Boolean> = preferencesFlow.map { prefs ->
@@ -1902,6 +2024,20 @@ class SettingsStore(context: Context) {
suspend fun savePauseVpnDuringSleep(enabled: Boolean) {
dataStore.edit { prefs ->
prefs[PAUSE_VPN_DURING_SLEEP] = enabled
prefs[SCREEN_OFF_MODE] = if (enabled) {
ScreenOffMode.SAVE_BATTERY.storedValue
} else {
ScreenOffMode.BALANCED.storedValue
}
}
}
suspend fun saveScreenOffMode(mode: ScreenOffMode) {
dataStore.edit { prefs ->
prefs[SCREEN_OFF_MODE] = mode.storedValue
// Старые версии приложения знают только этот флаг. Поддерживаем его
// синхронно, чтобы откат APK не включил противоположный сценарий сна.
prefs[PAUSE_VPN_DURING_SLEEP] = mode == ScreenOffMode.SAVE_BATTERY
}
}
@@ -1913,6 +2049,11 @@ class SettingsStore(context: Context) {
) {
dataStore.edit { prefs ->
prefs[PAUSE_VPN_DURING_SLEEP] = enabled
prefs[SCREEN_OFF_MODE] = if (enabled) {
ScreenOffMode.SAVE_BATTERY.storedValue
} else {
ScreenOffMode.BALANCED.storedValue
}
prefs[PAUSE_VPN_DURING_SLEEP_DELAY_MINUTES] =
normalizeSleepPauseDelayMinutes(pauseDelayMinutes)
prefs[PAUSE_VPN_DURING_SLEEP_MODE] = mode.storedValue
@@ -2038,6 +2179,33 @@ class SettingsStore(context: Context) {
CUSTOM_VK_CLIENT_SECRET,
profile
),
proxyMode = resolveStoredTunnelMode(
prefs[getProfileKey(PROXY_MODE, profile)],
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
),
proxyPort = normalizeSocks5Port(
prefs[getProfileKey(PROXY_PORT, profile)] ?: DEFAULT_SOCKS5_PORT
),
proxyUdpEnabled = prefs[getProfileKey(PROXY_UDP_ENABLED, profile)] ?: true,
proxyAccess = resolveStoredProxyAccess(
prefs[getProfileKey(PROXY_ACCESS, profile)],
prefs[getProfileKey(PROXY_LAN_ENABLED, profile)] ?: false,
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
),
proxyLanEnabled = proxyAccessIncludesLan(
resolveStoredProxyAccess(
prefs[getProfileKey(PROXY_ACCESS, profile)],
prefs[getProfileKey(PROXY_LAN_ENABLED, profile)] ?: false,
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
),
),
proxyAuthEnabled = prefs[getProfileKey(PROXY_AUTH_ENABLED, profile)] ?: false,
proxyUsername = truncateSocks5Credential(
prefs[getProfileKey(PROXY_USERNAME, profile)].orEmpty(),
),
proxyPassword = truncateSocks5Credential(
readProtectedSecret(prefs, PROXY_PASSWORD_ENCRYPTED, profile),
),
)
}.first()
@@ -2243,8 +2411,26 @@ class SettingsStore(context: Context) {
put("deployAdminId", readSecret(prefs, DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, profile))
put("deployBotToken", readSecret(prefs, DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, profile))
put("proxyMode", prefs[getProfileKey(PROXY_MODE, profile)] ?: "tun")
put("proxyModeActivated", prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] ?: false)
put("proxyHost", prefs[getProfileKey(PROXY_HOST, profile)] ?: "127.0.0.1")
put("proxyPort", prefs[getProfileKey(PROXY_PORT, profile)] ?: 1080)
put("proxyUdpEnabled", prefs[getProfileKey(PROXY_UDP_ENABLED, profile)] ?: true)
val exportedProxyAccess = resolveStoredProxyAccess(
prefs[getProfileKey(PROXY_ACCESS, profile)],
prefs[getProfileKey(PROXY_LAN_ENABLED, profile)] ?: false,
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] == true,
)
put("proxyAccess", exportedProxyAccess)
put("proxyLanEnabled", proxyAccessIncludesLan(exportedProxyAccess))
put("proxyAuthEnabled", prefs[getProfileKey(PROXY_AUTH_ENABLED, profile)] ?: false)
put(
"proxyUsername",
truncateSocks5Credential(prefs[getProfileKey(PROXY_USERNAME, profile)].orEmpty()),
)
put(
"proxyPassword",
truncateSocks5Credential(readProtectedSecret(prefs, PROXY_PASSWORD_ENCRYPTED, profile)),
)
put("vkCallsPreflight", prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] ?: true)
put("rtNetwork", prefs[getProfileKey(RT_NETWORK, profile)] ?: false)
put("rtMasque", prefs[getProfileKey(RT_MASQUE, profile)] ?: false)
@@ -2400,9 +2586,29 @@ class SettingsStore(context: Context) {
prefs.putSecret(DEPLOY_MAIN_PASSWORD_ENCRYPTED, DEPLOY_MAIN_PASSWORD, item.optString("deployMainPassword"), profile)
prefs.putSecret(DEPLOY_ADMIN_ID_ENCRYPTED, DEPLOY_ADMIN_ID, item.optString("deployAdminId"), profile)
prefs.putSecret(DEPLOY_BOT_TOKEN_ENCRYPTED, DEPLOY_BOT_TOKEN, item.optString("deployBotToken"), profile)
prefs[getProfileKey(PROXY_MODE, profile)] = item.optString("proxyMode", "tun")
prefs[getProfileKey(PROXY_HOST, profile)] = item.optString("proxyHost", "127.0.0.1")
prefs[getProfileKey(PROXY_MODE, profile)] = normalizeTunnelMode(item.optString("proxyMode"))
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] =
item.optBoolean("proxyModeActivated", false)
prefs[getProfileKey(PROXY_HOST, profile)] = SOCKS5_LOOPBACK_HOST
prefs[getProfileKey(PROXY_PORT, profile)] = item.safePort("proxyPort", 1080)
prefs[getProfileKey(PROXY_UDP_ENABLED, profile)] = item.optBoolean("proxyUdpEnabled", true)
val importedProxyAccess = resolveStoredProxyAccess(
item.optString("proxyAccess").takeIf { it.isNotBlank() },
item.optBoolean("proxyLanEnabled", false),
item.optBoolean("proxyModeActivated", false),
)
prefs[getProfileKey(PROXY_ACCESS, profile)] = importedProxyAccess
prefs[getProfileKey(PROXY_LAN_ENABLED, profile)] =
proxyAccessIncludesLan(importedProxyAccess)
prefs[getProfileKey(PROXY_AUTH_ENABLED, profile)] = item.optBoolean("proxyAuthEnabled", false)
prefs[getProfileKey(PROXY_USERNAME, profile)] = truncateSocks5Credential(
item.optString("proxyUsername").take(64),
)
prefs.putProtectedSecret(
PROXY_PASSWORD_ENCRYPTED,
truncateSocks5Credential(item.optString("proxyPassword")),
profile,
)
prefs[getProfileKey(VKCALLS_PREFLIGHT, profile)] = item.optBoolean("vkCallsPreflight", true)
prefs[getProfileKey(RT_NETWORK, profile)] = item.optBoolean("rtNetwork", false)
prefs[getProfileKey(RT_MASQUE, profile)] = item.optBoolean("rtMasque", false)
@@ -3637,12 +3843,35 @@ class SettingsStore(context: Context) {
}
// ═══ Сохранение proxy mode ═══
suspend fun saveProxyMode(mode: String, host: String, port: Int) {
suspend fun saveProxyMode(
mode: String,
port: Int,
udpEnabled: Boolean = true,
access: String = PROXY_ACCESS_BOTH,
authEnabled: Boolean = false,
username: String = "",
password: String = "",
) {
dataStore.edit { prefs ->
val profile = prefs[ACTIVE_PROFILE] ?: 0
prefs[getProfileKey(PROXY_MODE, profile)] = mode
prefs[getProfileKey(PROXY_HOST, profile)] = host
prefs[getProfileKey(PROXY_PORT, profile)] = port
prefs[getProfileKey(PROXY_MODE, profile)] = normalizeTunnelMode(mode)
prefs[getProfileKey(PROXY_MODE_ACTIVATED, profile)] = true
prefs[getProfileKey(PROXY_HOST, profile)] = SOCKS5_LOOPBACK_HOST
prefs[getProfileKey(PROXY_PORT, profile)] = normalizeProxyPort(port, mode)
prefs[getProfileKey(PROXY_UDP_ENABLED, profile)] = udpEnabled
val normalizedAccess = normalizeProxyAccess(access)
prefs[getProfileKey(PROXY_ACCESS, profile)] = normalizedAccess
prefs[getProfileKey(PROXY_LAN_ENABLED, profile)] =
proxyAccessIncludesLan(normalizedAccess)
prefs[getProfileKey(PROXY_AUTH_ENABLED, profile)] = authEnabled
prefs[getProfileKey(PROXY_USERNAME, profile)] = truncateSocks5Credential(
username.trim().take(64),
)
prefs.putProtectedSecret(
PROXY_PASSWORD_ENCRYPTED,
truncateSocks5Credential(password),
profile,
)
}
}
@@ -4045,6 +4274,9 @@ class SettingsStore(context: Context) {
val url = prefs[getProfileKey(ACCESS_LIFECYCLE_URL, profile)].orEmpty()
val binding = prefs[getProfileKey(ACCESS_LIFECYCLE_BINDING, profile)].orEmpty()
val capability = RemoteAccessCapability(
// Дополнительная удалённая возможность может быть прикреплена к
// обычному локальному профилю (например, после отдельного действия),
// не передавая backend владение самим подключением.
available = key.isNotBlank() && url.isNotBlank() && binding.isNotBlank(),
key = key,
url = url,
@@ -10,6 +10,12 @@ const val MAX_SSH_PRIVATE_KEY_CHARS = 128 * 1024
private const val JSCH_BC_EDDSA_KEYPAIRGEN = "com.jcraft.jsch.bc.KeyPairGenEdDSA"
private const val JSCH_BC_ED25519_SIGNATURE = "com.jcraft.jsch.bc.SignatureEd25519"
private const val JSCH_BC_ED448_SIGNATURE = "com.jcraft.jsch.bc.SignatureEd448"
private const val SSH_CONNECT_TIMEOUT_MS = 20_000
enum class SshRoutePolicy {
DIRECT_ONLY,
SERVER_MUTATION_DIRECT_ONLY,
SAFE_READ_ONLY_DIRECT,
}
@Volatile
private var jschEdDsaConfigured = false
@@ -132,7 +138,11 @@ fun sshPrivateKeyIssue(value: String): String? {
return null
}
internal fun friendlySshConnectionError(message: String, credentials: SshCredentials): String = when {
internal fun friendlySshConnectionError(
message: String,
credentials: SshCredentials,
connectTimeoutMs: Int = SSH_CONNECT_TIMEOUT_MS,
): String = when {
message.contains("SignatureEd25519", ignoreCase = true) ||
message.contains("ssh-ed25519", ignoreCase = true) && (
message.contains("not available", ignoreCase = true) ||
@@ -159,64 +169,163 @@ internal fun friendlySshConnectionError(message: String, credentials: SshCredent
message.contains("unknown host", ignoreCase = true) ->
"Не удалось найти SSH-сервер. Проверьте IP-адрес или домен."
message.contains("timeout", ignoreCase = true) ->
"SSH-сервер не ответил за 20 секунд. Проверьте адрес, порт, сеть и межсетевой экран."
"SSH-сервер не ответил за ${sshTimeoutLabel(connectTimeoutMs)}. " +
"Проверьте адрес, порт, сеть и межсетевой экран."
else -> "Не удалось подключиться по SSH: ${message.ifBlank { "неизвестная ошибка" }}"
}
private fun sshTimeoutLabel(connectTimeoutMs: Int): String {
val seconds = (connectTimeoutMs / 1_000).coerceAtLeast(1)
val suffix = when {
seconds % 100 in 11..14 -> "секунд"
seconds % 10 == 1 -> "секунду"
seconds % 10 in 2..4 -> "секунды"
else -> "секунд"
}
return "$seconds $suffix"
}
private fun Throwable.messageWithCauses(): String =
generateSequence(this) { it.cause }
.mapNotNull { it.message?.takeIf(String::isNotBlank) }
.joinToString(": ")
internal fun isSshConnectivityFailure(message: String): Boolean {
val lower = message.lowercase()
if (
"auth fail" in lower ||
"authentication" in lower ||
"invalid privatekey" in lower ||
"passphrase" in lower ||
"algorithm negotiation" in lower ||
"hostkey" in lower
) return false
return "timeout" in lower ||
"timed out" in lower ||
"unknownhost" in lower ||
"unknown host" in lower ||
"connection refused" in lower ||
"connect failed" in lower ||
"failed to connect" in lower ||
"connection reset" in lower ||
"socket is not established" in lower ||
"network is unreachable" in lower ||
"network unreachable" in lower ||
"no route to host" in lower ||
"enetunreach" in lower ||
"ehostunreach" in lower
}
internal fun capitalizeUserSentence(message: String): String =
message.replaceFirstChar { first ->
if (first.isLowerCase()) first.uppercaseChar().toString() else first.toString()
}
private fun createSshSessionAttempt(
host: String,
user: String,
credentials: SshCredentials,
port: Int,
connectTimeoutMs: Int,
): Session {
configureJschEdDsaCompatibility()
val jsch = JSch()
val privateKey = normalizeSshPrivateKey(credentials.privateKey)
if (privateKey.isNotBlank()) {
sshPrivateKeyIssue(privateKey)?.let { throw IllegalArgumentException(it) }
jsch.addIdentity(
"wdtt-plus-memory-key",
privateKey.toByteArray(Charsets.UTF_8),
null,
credentials.privateKeyPassphrase.takeIf { it.isNotEmpty() }?.toByteArray(Charsets.UTF_8)
)
}
val session = jsch.getSession(user.ifBlank { "root" }, host.trim(), port)
if (credentials.allowPasswordAuthentication && credentials.password.isNotBlank()) {
session.setPassword(credentials.password)
}
session.setConfig(Properties().apply {
put("StrictHostKeyChecking", "no")
put("ServerAliveInterval", "10")
put("ServerAliveCountMax", "6")
put("ConnectTimeout", connectTimeoutMs.toString())
put(
"PreferredAuthentications",
when {
privateKey.isNotBlank() && credentials.allowPasswordAuthentication -> "publickey,password,keyboard-interactive"
privateKey.isNotBlank() -> "publickey"
credentials.allowPasswordAuthentication -> "password,keyboard-interactive"
else -> "publickey"
}
)
})
session.connect(connectTimeoutMs)
return session
}
fun createSshSession(
host: String,
user: String,
credentials: SshCredentials,
port: Int = 22
port: Int = 22,
routePolicy: SshRoutePolicy = SshRoutePolicy.DIRECT_ONLY,
connectTimeoutMs: Int = SSH_CONNECT_TIMEOUT_MS,
): Session {
require(host.isNotBlank()) { "Не указан адрес SSH-сервера." }
require(port in 1..65535) { "SSH-порт должен быть от 1 до 65535." }
require(credentials.hasAuthentication) { "Укажите SSH-пароль или приватный SSH-ключ." }
require(connectTimeoutMs in 1_000..SSH_CONNECT_TIMEOUT_MS) {
"Время ожидания SSH должно быть от 1 до ${SSH_CONNECT_TIMEOUT_MS / 1_000} секунд."
}
val wdttVpnActive = routePolicy != SshRoutePolicy.DIRECT_ONLY &&
TunnelManager.running.value &&
TunnelManager.vpnInterfaceUp.value &&
TunnelManager.activeMode.value == TUNNEL_MODE_VPN &&
!TunnelManager.vpnSlotYieldRequested.value
try {
configureJschEdDsaCompatibility()
val jsch = JSch()
val privateKey = normalizeSshPrivateKey(credentials.privateKey)
if (privateKey.isNotBlank()) {
sshPrivateKeyIssue(privateKey)?.let { throw IllegalArgumentException(it) }
jsch.addIdentity(
"wdtt-plus-memory-key",
privateKey.toByteArray(Charsets.UTF_8),
null,
credentials.privateKeyPassphrase.takeIf { it.isNotEmpty() }?.toByteArray(Charsets.UTF_8)
)
}
val session = jsch.getSession(user.ifBlank { "root" }, host.trim(), port)
if (credentials.allowPasswordAuthentication && credentials.password.isNotBlank()) {
session.setPassword(credentials.password)
}
session.setConfig(Properties().apply {
put("StrictHostKeyChecking", "no")
put("ServerAliveInterval", "10")
put("ServerAliveCountMax", "6")
put("ConnectTimeout", "15000")
put(
"PreferredAuthentications",
when {
privateKey.isNotBlank() && credentials.allowPasswordAuthentication -> "publickey,password,keyboard-interactive"
privateKey.isNotBlank() -> "publickey"
credentials.allowPasswordAuthentication -> "password,keyboard-interactive"
else -> "publickey"
}
)
})
session.connect(20_000)
return session
return createSshSessionAttempt(
host = host,
user = user,
credentials = credentials,
port = port,
connectTimeoutMs = connectTimeoutMs,
)
} catch (error: IllegalArgumentException) {
throw error
} catch (error: JSchException) {
val message = error.messageWithCauses()
throw IllegalStateException(friendlySshConnectionError(message, credentials), error)
val directMessage = error.messageWithCauses()
val friendlyMessage = friendlySshConnectionError(directMessage, credentials, connectTimeoutMs)
if (
routePolicy == SshRoutePolicy.SERVER_MUTATION_DIRECT_ONLY &&
wdttVpnActive &&
isSshConnectivityFailure(directMessage)
) {
TunnelManager.noteDeployNetworkRoute(
key = "ssh_mutation_direct_only",
message = "Изменяющая операция Деплоя выполняется только напрямую. Через активный WDTT она сейчас запрещена: для того же сервера это защищает от потери управления, а управление другим сервером через отдельный активный профиль пока не поддерживается.",
warning = true,
)
throw IllegalStateException(
"$friendlyMessage Эта операция изменяет сервер и не выполняется через активный WDTT: " +
"при подключении к тому же серверу это может оборвать канал управления. " +
"Используйте прямой интернет или временно отключите WDTT. " +
"Управление другим сервером через отдельный активный профиль пока не поддерживается.",
error,
)
}
if (
routePolicy == SshRoutePolicy.SAFE_READ_ONLY_DIRECT &&
wdttVpnActive &&
isSshConnectivityFailure(directMessage)
) {
throw IllegalStateException(
"$friendlyMessage WDTT Plus не перенаправляет собственный SSH-сокет в активный VPN, " +
"поскольку это создаёт сетевую петлю.",
error,
)
}
throw IllegalStateException(friendlyMessage, error)
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -6,6 +6,118 @@ import android.content.Intent
internal const val TUNNEL_PROFILE_INDEX_EXTRA = "profile_index"
internal const val CONFIG_FIRST_START_EXTRA = "config_first_start"
internal const val DEFAULT_RT_TURN_SNI = "ya.ru"
internal const val TUNNEL_MODE_VPN = "vpn"
internal const val TUNNEL_MODE_AUTO = "auto"
internal const val TUNNEL_MODE_SOCKS5 = "socks5"
internal const val TUNNEL_MODE_HTTP = "http"
internal const val SOCKS5_LOOPBACK_HOST = "127.0.0.1"
internal const val DEFAULT_SOCKS5_PORT = 1080
internal const val DEFAULT_HTTP_CONNECT_PORT = 8080
internal const val PROXY_VPN_CAPTURE_CONFIRMATIONS = 2
internal fun normalizeTunnelMode(value: String?): String = when (value?.trim()?.lowercase()) {
TUNNEL_MODE_AUTO, "mixed" -> TUNNEL_MODE_AUTO
TUNNEL_MODE_SOCKS5 -> TUNNEL_MODE_SOCKS5
TUNNEL_MODE_HTTP, "http-connect", "connect" -> TUNNEL_MODE_HTTP
"tun", TUNNEL_MODE_VPN -> TUNNEL_MODE_VPN
else -> TUNNEL_MODE_VPN
}
internal fun resolveStoredTunnelMode(value: String?, explicitlyActivated: Boolean): String =
if (explicitlyActivated) normalizeTunnelMode(value) else TUNNEL_MODE_VPN
internal fun tunnelModeNeedsVpnPermission(value: String?): Boolean =
normalizeTunnelMode(value) == TUNNEL_MODE_VPN
internal fun tunnelModeUsesLocalProxy(value: String?): Boolean =
normalizeTunnelMode(value) != TUNNEL_MODE_VPN
/**
* ConnectivityManager returns a UID-aware default network. If it is another
* VPN while WDTT runs as a local proxy, that VPN did not exclude WDTT Plus and
* will feed the transport back into the same proxy. Confirm twice so a single
* capabilities handover cannot stop a healthy proxy session.
*/
internal fun nextProxyVpnCaptureObservationCount(
tunnelMode: String?,
appDefaultNetworkIsVpn: Boolean,
previousCount: Int,
): Int = if (tunnelModeUsesLocalProxy(tunnelMode) && appDefaultNetworkIsVpn) {
(previousCount + 1).coerceAtMost(PROXY_VPN_CAPTURE_CONFIRMATIONS)
} else {
0
}
internal fun proxyVpnCaptureConfirmed(observationCount: Int): Boolean =
observationCount >= PROXY_VPN_CAPTURE_CONFIRMATIONS
internal fun tunnelModeStatusLabel(value: String?): String = when (normalizeTunnelMode(value)) {
TUNNEL_MODE_AUTO -> "АВТО ПРОКСИ"
TUNNEL_MODE_SOCKS5 -> "SOCKS5"
TUNNEL_MODE_HTTP -> "HTTP CONNECT"
else -> "VPN"
}
internal fun fullWidgetRunningStatus(tunnelMode: String?, profileName: String): String = when (
normalizeTunnelMode(tunnelMode)
) {
TUNNEL_MODE_AUTO -> "ПРОКСИ · $profileName"
TUNNEL_MODE_SOCKS5 -> "SOCKS5 · $profileName"
TUNNEL_MODE_HTTP -> "HTTP · $profileName"
else -> "Подключено к $profileName"
}
internal fun compactWidgetRunningStatus(tunnelMode: String?, profileName: String): String = when (
normalizeTunnelMode(tunnelMode)
) {
TUNNEL_MODE_AUTO -> "ПРОКСИ · $profileName"
TUNNEL_MODE_SOCKS5 -> "SOCKS · $profileName"
TUNNEL_MODE_HTTP -> "HTTP · $profileName"
else -> profileName
}
internal fun normalizeProxyPort(value: Int, mode: String): Int = value.takeIf { it in 1..65535 }
?: if (normalizeTunnelMode(mode) == TUNNEL_MODE_HTTP) DEFAULT_HTTP_CONNECT_PORT else DEFAULT_SOCKS5_PORT
internal fun proxySettingsAreValid(
mode: String,
port: Int,
access: String,
authEnabled: Boolean,
username: String,
password: String,
): Boolean = !tunnelModeUsesLocalProxy(mode) ||
port in 1..65535 &&
(!authEnabled || isValidSocks5Credential(username) && isValidSocks5Credential(password)) &&
(!proxyAccessIncludesLan(access) || authEnabled)
internal fun tunnelToggleContentDescription(running: Boolean, tunnelMode: String?): String =
if (running) {
"Остановить ${tunnelModeStatusLabel(tunnelMode)}"
} else {
"Запустить ${tunnelModeStatusLabel(tunnelMode)}"
}
internal fun normalizeSocks5Port(value: Int): Int =
value.takeIf { it in 1..65535 } ?: DEFAULT_SOCKS5_PORT
internal fun isValidSocks5Credential(value: String): Boolean =
value.isNotBlank() && value.toByteArray(Charsets.UTF_8).size <= 255
internal fun truncateSocks5Credential(value: String, maxBytes: Int = 255): String {
if (maxBytes <= 0 || value.isEmpty()) return ""
if (value.toByteArray(Charsets.UTF_8).size <= maxBytes) return value
var index = 0
var usedBytes = 0
while (index < value.length) {
val nextIndex = value.offsetByCodePoints(index, 1)
val codePointBytes = value.substring(index, nextIndex).toByteArray(Charsets.UTF_8).size
if (usedBytes + codePointBytes > maxBytes) break
usedBytes += codePointBytes
index = nextIndex
}
return value.substring(0, index)
}
internal fun normalizeRtTurnSni(value: String): String? {
val host = value.trim().lowercase()
@@ -87,10 +199,7 @@ internal fun displayedTunnelProfile(
*/
internal fun shouldUseConfigFirstStart(): Boolean = true
internal fun shouldUseManagedHashFallback(
profileMaxWorkers: Int,
hashCount: Int,
): Boolean = profileMaxWorkers >= TUNNEL_WORKERS_PER_GROUP && hashCount > 1
internal fun shouldUseHashFallback(hashCount: Int): Boolean = hashCount > 1
suspend fun buildTunnelParamsFromSettings(
context: Context,
@@ -138,6 +247,14 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
profileMaxWorkers = saved.profileMaxWorkers,
configFirstStart = configFirstStart,
profileIndex = saved.profileIndex,
mode = normalizeTunnelMode(saved.proxyMode),
socksPort = normalizeProxyPort(saved.proxyPort, saved.proxyMode),
socksUdpEnabled = saved.proxyUdpEnabled || normalizeTunnelMode(saved.proxyMode) == TUNNEL_MODE_AUTO,
proxyAccess = normalizeProxyAccess(saved.proxyAccess),
proxyLanEnabled = saved.proxyLanEnabled,
socksAuthEnabled = saved.proxyAuthEnabled,
socksUsername = saved.proxyUsername,
socksPassword = saved.proxyPassword,
)
} else {
val basePeer = saved.peer.trim()
@@ -174,6 +291,14 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
profileMaxWorkers = saved.profileMaxWorkers,
configFirstStart = configFirstStart,
profileIndex = saved.profileIndex,
mode = normalizeTunnelMode(saved.proxyMode),
socksPort = normalizeProxyPort(saved.proxyPort, saved.proxyMode),
socksUdpEnabled = saved.proxyUdpEnabled || normalizeTunnelMode(saved.proxyMode) == TUNNEL_MODE_AUTO,
proxyAccess = normalizeProxyAccess(saved.proxyAccess),
proxyLanEnabled = saved.proxyLanEnabled,
socksAuthEnabled = saved.proxyAuthEnabled,
socksUsername = saved.proxyUsername,
socksPassword = saved.proxyPassword,
)
}
}
@@ -208,6 +333,14 @@ suspend fun buildTunnelStartIntentFromSettings(
putExtra("profile_max_workers", params.profileMaxWorkers)
putExtra(CONFIG_FIRST_START_EXTRA, params.configFirstStart)
putExtra(TUNNEL_PROFILE_INDEX_EXTRA, params.profileIndex)
putExtra("tunnel_mode", params.mode)
putExtra("socks_port", params.socksPort)
putExtra("socks_udp", params.socksUdpEnabled)
putExtra("proxy_access", params.proxyAccess)
putExtra("proxy_lan", params.proxyLanEnabled)
putExtra("socks_auth", params.socksAuthEnabled)
putExtra("socks_username", params.socksUsername)
putExtra("socks_password", params.socksPassword)
}
}
@@ -54,6 +54,8 @@ class VpnCompactWidgetProvider : AppWidgetProvider() {
)
val profileNames = settingsStore.profileNames.first()
val profileName = vpnProfileDisplayName(displayedProfile, profileNames)
val configuredMode = settingsStore.proxyMode.first()
val displayedMode = if (running) TunnelManager.activeMode.value else configuredMode
val accessLifecycle =
settingsStore.accessLifecycleForProfile(displayedProfile).toUiState()
val accessBlocked =
@@ -75,9 +77,14 @@ class VpnCompactWidgetProvider : AppWidgetProvider() {
waiting -> "Ожидание"
accessBlocked ->
accessLifecycle.title.ifBlank { accessLifecycle.fallbackTitle() }
running -> compactWidgetRunningStatus(displayedMode, profileName)
else -> profileName
}
)
views.setContentDescription(
R.id.compact_widget_toggle,
tunnelToggleContentDescription(running && !waiting, displayedMode),
)
val toggleIntent = Intent(context, VpnWidgetProvider::class.java).apply {
action = VpnWidgetProvider.ACTION_WIDGET_TOGGLE
@@ -55,6 +55,8 @@ class VpnWidgetProvider : AppWidgetProvider() {
trustedWifiWaiting = trustedWifi.waiting,
)
val profileNames = settingsStore.profileNames.first()
val configuredMode = settingsStore.proxyMode.first()
val displayedMode = if (running) TunnelManager.activeMode.value else configuredMode
val accessLifecycle =
settingsStore.accessLifecycleForProfile(displayedProfile).toUiState()
for (appWidgetId in appWidgetIds) {
@@ -67,6 +69,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
activeProfile = displayedProfile,
profileNames = profileNames,
accessLifecycle = accessLifecycle,
tunnelMode = displayedMode,
)
}
}
@@ -78,16 +81,22 @@ class VpnWidgetProvider : AppWidgetProvider() {
runCatching {
val running = TunnelManager.running.value
val trustedWifiWaiting = TrustedWifiManager.state.value.waiting
val action = if (running || trustedWifiWaiting) {
TunnelToggleAction.STOP
} else {
tunnelToggleAction(
if (running || trustedWifiWaiting) {
context.startService(
Intent(context, TunnelService::class.java).apply { action = "STOP" }
)
updateAllWidgets(context)
return
}
scope.launch {
val mode = SettingsStore(context).proxyMode.first()
val action = tunnelToggleAction(
running = false,
trustedWifiWaiting = false,
vpnPermissionRequired = VpnService.prepare(context) != null,
vpnPermissionRequired = tunnelModeNeedsVpnPermission(mode) &&
VpnService.prepare(context) != null,
)
}
when (action) {
when (action) {
TunnelToggleAction.STOP -> {
context.startService(
Intent(context, TunnelService::class.java).apply { this.action = "STOP" }
@@ -102,7 +111,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
).show()
openMainActivity(context)
}
TunnelToggleAction.START -> scope.launch {
TunnelToggleAction.START -> {
try {
val startIntent = buildTunnelStartIntentFromSettings(context)
if (startIntent == null) {
@@ -129,6 +138,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
).show()
}
}
}
}
}.onFailure { e ->
Log.e("VpnWidget", "Error handling widget click", e)
@@ -145,6 +155,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
activeProfile: Int,
profileNames: List<String>,
accessLifecycle: AccessLifecycleUiState,
tunnelMode: String,
) {
val views = RemoteViews(context.packageName, R.layout.vpn_widget)
@@ -156,7 +167,7 @@ class VpnWidgetProvider : AppWidgetProvider() {
views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_inactive)
} else if (running) {
val profileName = vpnProfileDisplayName(activeProfile, profileNames)
val status = "Подключено к $profileName"
val status = fullWidgetRunningStatus(tunnelMode, 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)
@@ -205,6 +216,10 @@ class VpnWidgetProvider : AppWidgetProvider() {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
views.setOnClickPendingIntent(R.id.widget_toggle_btn, togglePendingIntent)
views.setContentDescription(
R.id.widget_toggle_btn,
tunnelToggleContentDescription(running && !trustedWifi.waiting, tunnelMode),
)
appWidgetManager.updateAppWidget(appWidgetId, views)
}
@@ -51,6 +51,11 @@ class WireGuardHelper(context: Context) {
TunnelManager.noteVpnInterfaceState(false)
}
if (isCurrentTunnel && !suppressDownCallback) {
TunnelManager.noteVpnInterfaceLifecycle(
"unexpected_down",
"Системный VPN-интерфейс отключён вне штатной остановки приложения. Проверяем причину и возможность восстановления.",
warning = true,
)
onExternalDown?.invoke()
}
}
@@ -267,6 +272,14 @@ class WireGuardHelper(context: Context) {
sharedTunnel = nextTunnel
sharedConfigFingerprint = wireGuardConfigFingerprint(finalConfig)
TunnelManager.noteVpnInterfaceState(true)
TunnelManager.noteVpnInterfaceLifecycle(
"established",
if (previousTunnel != null) {
"Системный VPN-интерфейс пересоздан для изменившихся настроек. Android может повторно показать уведомление о VPN."
} else {
"Создан системный VPN-интерфейс. Восстановление отдельных каналов само по себе его не пересоздаёт."
},
)
Log.d("WG", "WireGuard tunnel started successfully")
} catch (e: Exception) {
val stillUp = sharedTunnel?.let { tunnel ->
@@ -13,7 +13,6 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
File diff suppressed because it is too large. Load diff
@@ -24,7 +24,6 @@ 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
@@ -47,9 +47,9 @@ import androidx.compose.material.icons.filled.FileDownload
import androidx.compose.material.icons.filled.FileUpload
import androidx.compose.material.icons.filled.Hub
import androidx.compose.material.icons.filled.Language
import androidx.compose.material.icons.filled.SettingsEthernet
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.CircularProgressIndicator
@@ -107,10 +107,12 @@ import androidx.lifecycle.compose.LifecycleResumeEffect
import com.wdtt.plus.MAX_VPN_ADDRESS_IMPORT_BYTES
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.TUNNEL_MODE_VPN
import com.wdtt.plus.VpnAddressRule
import com.wdtt.plus.VpnAddressType
import com.wdtt.plus.isAlwaysBypassedVpnPackage
import com.wdtt.plus.normalizeVpnAddressRules
import com.wdtt.plus.tunnelModeNeedsVpnPermission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -174,6 +176,9 @@ fun ExceptionsTab(
val scope = rememberCoroutineScope()
val settingsStore = remember { SettingsStore(context) }
val routingSettings by settingsStore.vpnRoutingSettings.collectAsStateWithLifecycle(initialValue = null)
val selectedTunnelMode by settingsStore.proxyMode.collectAsStateWithLifecycle(
initialValue = TUNNEL_MODE_VPN,
)
val showSystemAppsOpt by settingsStore.showSystemApps.collectAsStateWithLifecycle(initialValue = null)
val routingReady = routingSettings != null
val savedPackages = routingSettings?.appPackages.orEmpty()
@@ -182,6 +187,11 @@ fun ExceptionsTab(
val visibleProfileIndex = routingSettings?.profileIndex ?: 0
val selectedPackages = remember(savedPackages) { savedPackages.toVpnPackageSet() }
if (!tunnelModeNeedsVpnPermission(selectedTunnelMode)) {
Socks5RoutingUnavailable()
return
}
var appsList by remember { mutableStateOf(AppCache.cachedList.orEmpty()) }
var isLoadingApps by remember { mutableStateOf(AppCache.cachedList == null) }
var appSearchQuery by rememberSaveable { mutableStateOf("") }
@@ -652,6 +662,51 @@ fun ExceptionsTab(
}
}
@Composable
private fun Socks5RoutingUnavailable() {
Box(
modifier = Modifier.fillMaxSize().padding(24.dp),
contentAlignment = Alignment.Center,
) {
Surface(
modifier = Modifier.fillMaxWidth(),
shape = RoundedCornerShape(22.dp),
color = MaterialTheme.colorScheme.surfaceContainerHighest,
) {
Column(
modifier = Modifier.padding(20.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Icon(
Icons.Default.SettingsEthernet,
contentDescription = null,
modifier = Modifier.size(34.dp),
tint = MaterialTheme.colorScheme.primary,
)
Text(
"Исключения задаёт клиент цепочки",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
)
Text(
"В режиме SOCKS5 WDTT Plus не перехватывает приложения и адреса. Настройте маршруты, исключения и прямой выход в Exclave, NekoBox или другом приложении, которое подключается к локальному прокси.",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
Text(
"Сохранённые списки WDTT Plus не удалены и снова появятся после выбора системного VPN.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center,
)
}
}
}
}
@Composable
private fun CollapsingExceptionsHeader(
offsetPx: Float,
@@ -4,7 +4,6 @@ import android.content.Intent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
@@ -14,12 +13,12 @@ import androidx.compose.animation.scaleOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.layout.*
@@ -35,24 +34,27 @@ import androidx.compose.ui.draw.scale
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.ScreenOffMode
import com.wdtt.plus.SleepBatteryMode
import com.wdtt.plus.TunnelManager
import com.wdtt.plus.TunnelService
import com.wdtt.plus.TunnelStopCoordinator
import com.wdtt.plus.TunnelStopResult
import com.wdtt.plus.TUNNEL_MODE_VPN
import com.wdtt.plus.tunnelModeNeedsVpnPermission
import com.wdtt.plus.sanitizeVpnProfileNameInput
import com.wdtt.plus.vpnProfileDefaultName
import com.wdtt.plus.vpnProfileDisplayName
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.IntOffset
import com.wdtt.plus.R
import android.os.Build
import androidx.compose.ui.graphics.Color
@@ -71,6 +73,17 @@ import kotlinx.coroutines.withTimeoutOrNull
private const val PROFILE_RESET_TIMEOUT_MS = 10_000L
internal fun floatingToolbarMaxOffset(
parentHeightPx: Float,
safeBottomPx: Float,
toolbarHeightPx: Float,
navigationReservePx: Float,
bottomGapPx: Float,
minOffsetY: Float,
): Float = (
parentHeightPx - safeBottomPx - navigationReservePx - toolbarHeightPx - bottomGapPx
).coerceAtLeast(minOffsetY)
@OptIn(ExperimentalLayoutApi::class, ExperimentalFoundationApi::class)
@Composable
fun FloatingToolbar(
@@ -100,19 +113,22 @@ fun FloatingToolbar(
val trustedWifiEnabled by settingsStore.trustedWifiEnabled.collectAsStateWithLifecycle(initialValue = false)
val trustedWifiSsids by settingsStore.trustedWifiSsids.collectAsStateWithLifecycle(initialValue = emptyList())
val trustedWifiRuntime by com.wdtt.plus.TrustedWifiManager.state.collectAsStateWithLifecycle()
val pauseVpnDuringSleep by settingsStore.pauseVpnDuringSleep.collectAsStateWithLifecycle(initialValue = false)
val screenOffMode by settingsStore.screenOffMode.collectAsStateWithLifecycle(
initialValue = ScreenOffMode.BALANCED,
)
val selectedTunnelMode by settingsStore.proxyMode.collectAsStateWithLifecycle(
initialValue = TUNNEL_MODE_VPN,
)
val pauseVpnDuringSleepDelayMinutes by
settingsStore.pauseVpnDuringSleepDelayMinutes.collectAsStateWithLifecycle(initialValue = 5)
val sleepBatteryMode by
settingsStore.sleepBatteryMode.collectAsStateWithLifecycle(initialValue = SleepBatteryMode.DELAYED_PAUSE)
val resumeVpnDuringSleepDelayMinutes by
settingsStore.resumeVpnDuringSleepDelayMinutes.collectAsStateWithLifecycle(initialValue = 5)
val sleepBatterySettingsConfigured by
settingsStore.sleepBatterySettingsConfigured.collectAsStateWithLifecycle(initialValue = false)
val customVkCredentialsEnabled by settingsStore.customVkCredentialsEnabled.collectAsStateWithLifecycle(initialValue = false)
val customVkCredentialsComplete by settingsStore.customVkCredentialsComplete.collectAsStateWithLifecycle(initialValue = false)
val savedToolbarYFraction by settingsStore.floatingToolbarYFraction.collectAsStateWithLifecycle(
initialValue = -2f
initialValue = -2f,
)
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
val tunnelTransition by TunnelManager.transition.collectAsStateWithLifecycle()
@@ -122,19 +138,11 @@ fun FloatingToolbar(
val screenHeightPx = remember(configuration.screenHeightDp, density) {
with(density) { configuration.screenHeightDp.dp.toPx() }
}
val screenWidthPx = remember(configuration.screenWidthDp, density) {
with(density) { configuration.screenWidthDp.dp.toPx() }
}
var parentWidthPx by remember { mutableFloatStateOf(0f) }
var parentHeightPx by remember { mutableFloatStateOf(0f) }
var tabHeightPx by remember { mutableFloatStateOf(0f) }
var offsetY by remember { mutableFloatStateOf(-1f) }
var toolbarPositionRestored by remember { mutableStateOf(false) }
var isRightSide by rememberSaveable { mutableStateOf(true) }
var isExpanded by rememberSaveable { mutableStateOf(false) }
var tabHeightPx by remember { mutableFloatStateOf(0f) }
var panelHeightPx by remember { mutableFloatStateOf(0f) }
var renamingProfile by remember { mutableStateOf<Int?>(null) }
var resettingProfile by remember { mutableStateOf<Int?>(null) }
var resetCountdown by remember { mutableIntStateOf(5) }
@@ -144,10 +152,11 @@ fun FloatingToolbar(
var enableTrustedWifiAfterSetup by rememberSaveable { mutableStateOf(false) }
var showVkClientSettings by rememberSaveable { mutableStateOf(false) }
var showSleepTimerSettings by rememberSaveable { mutableStateOf(false) }
var showScreenOffModeSettings by rememberSaveable { mutableStateOf(false) }
var screenOffModeDraftName by rememberSaveable { mutableStateOf<String?>(null) }
val tabWidthDp = 42.dp
val tabHeightDp = 52.dp
val panelWidthDp = 220.dp
// Move the thumb immediately on tap instead of waiting for the DataStore round trip.
// The persisted value still remains the source of truth and resynchronizes this state.
var displayedInterfaceRole by remember(interfaceRole, adminModeAllowed) {
@@ -165,32 +174,21 @@ fun FloatingToolbar(
}
}
val tabWidthPx = remember(density) { with(density) { tabWidthDp.toPx() } }
val fallbackTabHeightPx = remember(density) { with(density) { tabHeightDp.toPx() } }
val edgePaddingPx = remember(density) { with(density) { 8.dp.toPx() } }
val bottomGapPx = remember(density) { with(density) { 4.dp.toPx() } }
val navigationReservePx = remember(density) { with(density) { 96.dp.toPx() } }
val safeTopPx = WindowInsets.safeDrawing.getTop(density).toFloat()
val safeBottomPx = WindowInsets.safeDrawing.getBottom(density).toFloat()
val effectiveTabHeightPx = maxOf(tabHeightPx, fallbackTabHeightPx)
val floatingHeightPx = if (isExpanded && panelHeightPx > 0f) {
maxOf(effectiveTabHeightPx, panelHeightPx)
} else {
effectiveTabHeightPx
}
val currentParentHeight = if (parentHeightPx > 0f) parentHeightPx else screenHeightPx
val currentParentWidth = if (parentWidthPx > 0f) parentWidthPx else screenWidthPx
val minOffsetY = safeTopPx + edgePaddingPx
val maxOffsetY = (currentParentHeight - safeBottomPx - floatingHeightPx - edgePaddingPx)
.coerceAtLeast(minOffsetY)
val defaultOffsetY = (currentParentHeight * 0.30f).coerceIn(minOffsetY, maxOffsetY)
val targetXPx = if (isRightSide) currentParentWidth - tabWidthPx else 0f
val animatedTabXPx by animateFloatAsState(
targetValue = targetXPx,
animationSpec = spring(stiffness = Spring.StiffnessLow),
label = "tab_shift"
val maxOffsetY = floatingToolbarMaxOffset(
parentHeightPx = currentParentHeight,
safeBottomPx = safeBottomPx,
toolbarHeightPx = maxOf(tabHeightPx, fallbackTabHeightPx),
navigationReservePx = navigationReservePx,
bottomGapPx = bottomGapPx,
minOffsetY = minOffsetY,
)
LaunchedEffect(savedToolbarYFraction, minOffsetY, maxOffsetY) {
@@ -199,7 +197,10 @@ fun FloatingToolbar(
if (savedToolbarYFraction >= 0f && maxOffsetY > minOffsetY) {
minOffsetY + (maxOffsetY - minOffsetY) * savedToolbarYFraction
} else {
defaultOffsetY
// A new installation starts above the bottom navigation, as
// shown in the main tunnel layout. The thumb remains freely
// movable along the right edge and its chosen position is saved.
maxOffsetY
}
} else {
offsetY.coerceIn(minOffsetY, maxOffsetY)
@@ -218,24 +219,20 @@ fun FloatingToolbar(
scope.launch { settingsStore.saveFloatingToolbarYFraction(fraction) }
}
val tabShape = if (isRightSide) {
RoundedCornerShape(topStart = 14.dp, bottomStart = 14.dp)
} else {
RoundedCornerShape(topEnd = 14.dp, bottomEnd = 14.dp)
}
val tabShape = RoundedCornerShape(topStart = 14.dp, bottomStart = 14.dp)
Box(
modifier = modifier
.fillMaxSize()
.onGloballyPositioned { coordinates ->
parentWidthPx = coordinates.size.width.toFloat()
parentHeightPx = coordinates.size.height.toFloat()
}
) {
Surface(
onClick = { isExpanded = !isExpanded },
modifier = Modifier
.offset { IntOffset(animatedTabXPx.roundToInt(), offsetY.roundToInt()) }
.align(Alignment.TopEnd)
.offset { IntOffset(0, offsetY.coerceAtLeast(minOffsetY).roundToInt()) }
.remoteCompactFocus(tabShape)
.onGloballyPositioned { coordinates ->
tabHeightPx = coordinates.size.height.toFloat()
@@ -247,7 +244,7 @@ fun FloatingToolbar(
onDrag = { change, dragAmount ->
change.consume()
offsetY = (offsetY + dragAmount.y).coerceIn(minOffsetY, maxOffsetY)
}
},
)
},
shape = tabShape,
@@ -375,72 +372,79 @@ fun FloatingToolbar(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Column(
if (tunnelModeNeedsVpnPermission(selectedTunnelMode)) {
Row(
modifier = Modifier
.weight(1f)
.remoteFocusOutline(RoundedCornerShape(8.dp))
.clickable {
enableTrustedWifiAfterSetup = false
showTrustedWifiSettings = true
}
.padding(horizontal = 8.dp, vertical = 6.dp)
.fillMaxWidth()
.padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
"Доверенные сети Wi‑Fi",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
when {
trustedWifiRuntime.waiting -> "VPN ожидает выхода из сети"
trustedWifiSsids.isEmpty() ->
"Сети не настроены · нажмите для настройки"
trustedWifiEnabled ->
"Включено · сетей: ${trustedWifiSsids.size}"
else ->
"Выключено · сохранено сетей: ${trustedWifiSsids.size}"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 15.sp
)
}
Switch(
checked = trustedWifiEnabled,
onCheckedChange = { enabled ->
if (enabled && trustedWifiSsids.isEmpty()) {
enableTrustedWifiAfterSetup = true
showTrustedWifiSettings = true
} else {
scope.launch {
settingsStore.saveTrustedWifiEnabled(enabled)
if (TunnelManager.running.value || trustedWifiRuntime.waiting) {
runCatching {
context.startService(
Intent(context, TunnelService::class.java).apply {
action = "TRUSTED_WIFI_RECHECK"
}
)
Column(
modifier = Modifier
.weight(1f)
.remoteFocusOutline(RoundedCornerShape(8.dp))
.clickable {
enableTrustedWifiAfterSetup = false
showTrustedWifiSettings = true
}
.padding(end = 8.dp, top = 6.dp, bottom = 6.dp)
) {
Text(
"Доверенные сети Wi‑Fi",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
when {
trustedWifiRuntime.waiting -> "VPN ожидает выхода из сети"
trustedWifiSsids.isEmpty() ->
"Сети не настроены · нажмите для настройки"
trustedWifiEnabled ->
"Включено · сетей: ${trustedWifiSsids.size}"
else ->
"Выключено · сохранено сетей: ${trustedWifiSsids.size}"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 15.sp
)
}
Switch(
checked = trustedWifiEnabled,
onCheckedChange = { enabled ->
if (enabled && trustedWifiSsids.isEmpty()) {
enableTrustedWifiAfterSetup = true
showTrustedWifiSettings = true
} else {
scope.launch {
settingsStore.saveTrustedWifiEnabled(enabled)
if (TunnelManager.running.value || trustedWifiRuntime.waiting) {
runCatching {
context.startService(
Intent(context, TunnelService::class.java).apply {
action = "TRUSTED_WIFI_RECHECK"
}
)
}
}
}
}
}
},
modifier = Modifier.remoteSwitchFocus().scale(0.85f)
)
},
modifier = Modifier.remoteSwitchFocus().scale(0.85f)
)
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.remoteFocusOutline(RoundedCornerShape(8.dp))
.clickable {
screenOffModeDraftName = screenOffMode.name
showScreenOffModeSettings = true
}
.padding(horizontal = 4.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
@@ -448,84 +452,40 @@ fun FloatingToolbar(
Column(
modifier = Modifier
.weight(1f)
.remoteFocusOutline(RoundedCornerShape(8.dp))
.clickable { showSleepTimerSettings = true }
.padding(horizontal = 8.dp, vertical = 6.dp)
.padding(end = 8.dp, top = 6.dp, bottom = 6.dp)
) {
Text(
"Экономия батареи во сне",
"Работа при выключенном экране",
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
color = MaterialTheme.colorScheme.onSurface
)
Text(
if (pauseVpnDuringSleep) {
when (sleepBatteryMode) {
when (screenOffMode) {
ScreenOffMode.BALANCED -> "Сбалансированно"
ScreenOffMode.HOLD_CONNECTION ->
"Удерживать соединение · повышенный расход батареи"
ScreenOffMode.SAVE_BATTERY -> when (sleepBatteryMode) {
SleepBatteryMode.DELAYED_PAUSE ->
if (pauseVpnDuringSleepDelayMinutes == 0) {
"Отключение сразу после выключения экрана"
"Экономить батарею · отключение сразу"
} else {
"Отключение через ${formatSleepTimerDuration(pauseVpnDuringSleepDelayMinutes)}"
"Экономить батарею · отключение через ${formatSleepTimerDuration(pauseVpnDuringSleepDelayMinutes)}"
}
SleepBatteryMode.TIMED_PAUSE ->
if (resumeVpnDuringSleepDelayMinutes == 0) {
"Таймер 0 мин · VPN останется активным"
"Экономить батарею · таймер выключен"
} else {
"Сразу выключится · включение через ${formatSleepTimerDuration(resumeVpnDuringSleepDelayMinutes)}"
"Экономить батарею · включение через ${formatSleepTimerDuration(resumeVpnDuringSleepDelayMinutes)}"
}
}
} else {
if (sleepBatterySettingsConfigured) {
when (sleepBatteryMode) {
SleepBatteryMode.DELAYED_PAUSE ->
if (pauseVpnDuringSleepDelayMinutes == 0) {
"Выключено · сохранено немедленное отключение"
} else {
"Выключено · сохранено отключение через ${formatSleepTimerDuration(pauseVpnDuringSleepDelayMinutes)}"
}
SleepBatteryMode.TIMED_PAUSE ->
if (resumeVpnDuringSleepDelayMinutes == 0) {
"Выключено · сохранён таймер 0 мин"
} else {
"Выключено · сохранено включение через ${formatSleepTimerDuration(resumeVpnDuringSleepDelayMinutes)}"
}
}
} else {
"VPN остаётся активным · нажмите для настройки"
}
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 15.sp
)
}
Switch(
checked = pauseVpnDuringSleep,
onCheckedChange = { enabled ->
if (enabled) {
if (sleepBatterySettingsConfigured) {
scope.launch {
settingsStore.savePauseVpnDuringSleep(true)
TunnelManager.noteSleepBatteryEvent(
"settings_enabled",
"Экономия батареи во сне включена; сохранённый сценарий применится при следующем выключении экрана.",
)
}
} else {
showSleepTimerSettings = true
}
} else {
scope.launch {
settingsStore.savePauseVpnDuringSleep(false)
TunnelManager.noteSleepBatteryEvent(
"settings_disabled",
"Экономия батареи во сне выключена.",
)
}
}
},
modifier = Modifier.remoteSwitchFocus().scale(0.85f)
)
Text("›", style = MaterialTheme.typography.titleLarge)
}
HorizontalDivider(
@@ -550,9 +510,9 @@ fun FloatingToolbar(
!adminModeAllowed ->
"Режим «Админ» доступен для самостоятельного профиля"
isAdminRole ->
"VPN и настройка своего сервера"
"Подключение и настройка своего сервера"
else ->
"Подключение и работа VPN"
"Подключение через выбранный режим"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
@@ -802,8 +762,8 @@ fun FloatingToolbar(
check(stopResult.succeeded) {
when (stopResult) {
TunnelStopResult.TIMED_OUT ->
"VPN не остановился за отведённое время"
else -> "Не удалось остановить VPN"
"Соединение не остановилось за отведённое время"
else -> "Не удалось остановить соединение"
}
}
}
@@ -856,6 +816,38 @@ fun FloatingToolbar(
)
}
if (showScreenOffModeSettings) {
ScreenOffModeDialog(
initialMode = ScreenOffMode.entries.firstOrNull {
it.name == screenOffModeDraftName
} ?: screenOffMode,
onApply = { mode ->
scope.launch {
settingsStore.saveScreenOffMode(mode)
TunnelManager.noteSleepBatteryEvent(
"screen_off_mode_saved",
"Режим работы при выключенном экране: " + when (mode) {
ScreenOffMode.BALANCED -> "сбалансированно"
ScreenOffMode.HOLD_CONNECTION -> "удерживать соединение"
ScreenOffMode.SAVE_BATTERY -> "экономить батарею"
} + ".",
)
}
screenOffModeDraftName = null
showScreenOffModeSettings = false
},
onConfigureBatterySaving = { selectedMode ->
screenOffModeDraftName = selectedMode.name
showScreenOffModeSettings = false
showSleepTimerSettings = true
},
onDismiss = {
screenOffModeDraftName = null
showScreenOffModeSettings = false
},
)
}
if (showSleepTimerSettings) {
SleepTimerDialog(
initialMode = sleepBatteryMode,
@@ -883,9 +875,13 @@ fun FloatingToolbar(
"Настройки сохранены: $description.",
)
}
screenOffModeDraftName = null
showSleepTimerSettings = false
},
onDismiss = { showSleepTimerSettings = false },
onDismiss = {
showSleepTimerSettings = false
showScreenOffModeSettings = true
},
)
}
}
@@ -1055,7 +1051,7 @@ private fun ProfileResetDialog(
Text(
buildString {
append("На самом VPS и в других профилях ничего не удаляется.")
if (disconnectsActiveVpn) append(" Активное VPN-подключение этого профиля будет остановлено.")
if (disconnectsActiveVpn) append(" Активное соединение этого профиля будет остановлено.")
},
modifier = Modifier.padding(14.dp),
style = MaterialTheme.typography.bodySmall,
+217 -43
View File
@@ -67,7 +67,6 @@ import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.Person
import androidx.compose.material.icons.filled.Update
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalIconButton
@@ -121,6 +120,7 @@ import com.wdtt.plus.RemoteUiActionLauncher
import com.wdtt.plus.RT_MASQUE_CONFIG_FILE_NAME
import com.wdtt.plus.RtMasqueEnrollmentState
import com.wdtt.plus.SettingsStore
import com.wdtt.plus.ScreenOffMode
import com.wdtt.plus.SleepBatteryMode
import com.wdtt.plus.SleepBatteryRuntimePhase
import com.wdtt.plus.SleepBatteryRuntimeState
@@ -134,6 +134,8 @@ import com.wdtt.plus.trustedWifiModeItem
import com.wdtt.plus.vpnRoutingModeItem
import com.wdtt.plus.vpnProfileDisplayName
import com.wdtt.plus.inspectRtMasqueEnrollment
import com.wdtt.plus.normalizeTunnelMode
import com.wdtt.plus.tunnelModeNeedsVpnPermission
import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED
import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE
import com.wdtt.plus.WDTTColors
@@ -325,6 +327,13 @@ fun InfoTab(
LaunchedEffect(Unit) {
actionCatalog = RemoteActionCatalogGateway.fetch()
}
LaunchedEffect(showSupportDialog) {
if (showSupportDialog) {
// Каталог общий для всех режимов соединения. Обновляем его при каждом
// открытии окна, сохраняя последний корректный кэш при сетевом сбое.
actionCatalog = RemoteActionCatalogGateway.fetch(force = true)
}
}
LaunchedEffect(Unit) {
questionActionLoading = true
questionAction = RemoteActionCatalogGateway.fetchQuestionAction()
@@ -357,7 +366,7 @@ fun InfoTab(
suspend fun buildDeviceCheckReportWithVersion(): com.wdtt.plus.DeviceCompatibilityReport {
val latestCheckedAt = System.currentTimeMillis()
val latestRelease = fetchLatestReleaseInfo(currentVersion)
val latestRelease = fetchLatestReleaseInfo(context, currentVersion)
settingsStore.saveUpdateState(
lastCheckAt = latestCheckedAt,
latestVersion = latestRelease?.versionTag ?: "",
@@ -384,6 +393,8 @@ fun InfoTab(
val tunnelProfile = runCatching {
settingsStore.tunnelProfileSnapshot(diagnosticProfile)
}.getOrNull()
val diagnosticTunnelMode = normalizeTunnelMode(tunnelProfile?.proxyMode)
val systemVpnMode = tunnelModeNeedsVpnPermission(diagnosticTunnelMode)
val workers = tunnelProfile?.workersPerHash
?: runCatching { settingsStore.workersPerHash.first() }.getOrNull()
val routingSnapshot = runCatching {
@@ -410,6 +421,8 @@ fun InfoTab(
null
}
val sleepEnabled = runCatching { settingsStore.pauseVpnDuringSleep.first() }.getOrDefault(false)
val screenOffMode = runCatching { settingsStore.screenOffMode.first() }
.getOrDefault(ScreenOffMode.BALANCED)
val sleepMode = runCatching { settingsStore.sleepBatteryMode.first() }
.getOrDefault(SleepBatteryMode.DELAYED_PAUSE)
val sleepPauseDelay = runCatching {
@@ -427,8 +440,15 @@ fun InfoTab(
context.getSystemService(PowerManager::class.java)
?.isIgnoringBatteryOptimizations(context.packageName)
}.getOrNull()
val backgroundRestricted = runCatching {
context.getSystemService(ActivityManager::class.java)?.isBackgroundRestricted
}.getOrNull()
val diagnosticsSummary = withContext(Dispatchers.Default) {
buildSupportReportSummary(context.applicationContext, settingsStore)
buildSupportReportSummary(
context.applicationContext,
settingsStore,
diagnosticTunnelMode,
)
}
val clientNetworkDiagnostics = try {
collectClientNetworkDiagnostics(context.applicationContext)
@@ -449,7 +469,7 @@ fun InfoTab(
)
)
}
val vpnDnsRuntimeItem = vpnDnsSnapshot?.let { settings ->
val vpnDnsRuntimeItem = vpnDnsSnapshot?.takeIf { systemVpnMode }?.let { settings ->
try {
com.wdtt.plus.collectVpnDnsRuntimeDiagnostic(
context = context.applicationContext,
@@ -473,11 +493,19 @@ fun InfoTab(
DeviceCompatibility.check(
context = context.applicationContext,
includeRuntimeChecks = true,
workersPerHash = workers
workersPerHash = workers,
tunnelMode = diagnosticTunnelMode,
screenOffMode = screenOffMode,
)
}
val relevantNetworkSummary = clientNetworkDiagnostics.summaryLines.filterNot { line ->
!systemVpnMode && line.contains("DNS внутри VPN", ignoreCase = true)
}
val relevantNetworkItems = clientNetworkDiagnostics.items.filterNot { item ->
!systemVpnMode && item.title.contains("DNS внутри VPN", ignoreCase = true)
}
return report.copy(
summaryLines = diagnosticsSummary + clientNetworkDiagnostics.summaryLines +
summaryLines = diagnosticsSummary + relevantNetworkSummary +
listOfNotNull(vpnDnsRuntimeItem?.let { "DNS внутри VPN: ${it.status}" }),
items = listOf(versionItem) +
report.items.filterNot {
@@ -487,28 +515,32 @@ fun InfoTab(
tunnelProfile?.let { DeviceCompatibility.rtNetworkModeItem(context, it) },
sleepBatteryModeItem(
enabled = sleepEnabled,
screenOffMode = screenOffMode,
mode = sleepMode,
pauseDelayMinutes = sleepPauseDelay,
resumeDelayMinutes = sleepResumeDelay,
runtime = sleepRuntime,
notificationsGranted = notificationsGranted,
batteryOptimizationsIgnored = batteryOptimizationsIgnored,
),
backgroundRestricted = backgroundRestricted,
).takeIf {
systemVpnMode || screenOffMode == ScreenOffMode.HOLD_CONNECTION
},
trustedWifiModeItem(
enabled = trustedWifiEnabled,
savedNetworkCount = trustedWifiSsids.size,
waiting = trustedWifiWaiting,
waitingSsid = trustedWifiWaitingSsid,
accessProblem = trustedWifiProblem,
),
routingSnapshot?.let {
).takeIf { systemVpnMode },
routingSnapshot?.takeIf { systemVpnMode }?.let {
vpnRoutingModeItem(
snapshot = it,
installedPackages = installedPackages,
ownPackageName = context.packageName,
)
},
vpnDnsSnapshot?.let {
vpnDnsSnapshot?.takeIf { systemVpnMode }?.let {
com.wdtt.plus.vpnDnsModeItem(
settings = it,
tunnelRunning = TunnelManager.running.value,
@@ -518,7 +550,7 @@ fun InfoTab(
},
vpnDnsRuntimeItem,
) +
clientNetworkDiagnostics.items
relevantNetworkItems
)
}
@@ -637,7 +669,7 @@ fun InfoTab(
WideActionTile(
title = "Справка",
subtitle = "Коротко про VPN, исключения, капчу и запуск",
subtitle = "Коротко про режимы, цепочки, исключения и запуск",
onClick = { showHelpDialog = true },
icon = {
Icon(
@@ -662,7 +694,7 @@ fun InfoTab(
var errorMessage = ""
try {
runCatching {
release = fetchLatestReleaseInfo(currentVersion)
release = fetchLatestReleaseInfo(context, currentVersion)
if (release == null) {
errorMessage = "Не удалось проверить"
return@runCatching
@@ -903,7 +935,7 @@ fun InfoTab(
DeviceCompatibilityDialog(
report = report,
title = "Проверка устройства",
subtitle = "Расширенная проверка не запускает VPN, но безопасно проверяет системный DNS, DNS-путь клиента и доступность узлов VK/OK.",
subtitle = "Расширенная проверка не запускает соединение, но безопасно проверяет системный DNS, сетевой путь клиента и доступность узлов VK/OK.",
note = "Кнопка «Скопировать отчёт» повторит сетевые пробы и добавит их результат без VK-хешей, паролей, токенов и локальных IP-адресов телефона.",
onDismiss = { deviceCheckReport = null },
onCopy = {
@@ -1123,6 +1155,11 @@ private fun AdditionalActionsDialog(
onProjectFallbackClick: () -> Unit,
onDonateOriginalClick: () -> Unit
) {
var originalAuthorExpanded by rememberSaveable { mutableStateOf(false) }
val supportScrollState = rememberScrollState()
val supportScope = rememberCoroutineScope()
val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() }
var originalAuthorSectionY by remember { mutableStateOf(0f) }
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
@@ -1145,7 +1182,7 @@ private fun AdditionalActionsDialog(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp)
.verticalScroll(rememberScrollState()),
.verticalScroll(supportScrollState),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Row(
@@ -1209,12 +1246,26 @@ private fun AdditionalActionsDialog(
)
}
ExternalSupportBlock(
title = "Автор оригинального приложения",
body = "Оригинальная основа проекта создана amurcanov. Можно отдельно поддержать автора исходного приложения.",
buttonText = "ЮMoney",
OriginalAuthorSupportBlock(
expanded = originalAuthorExpanded,
onToggle = {
val willExpand = !originalAuthorExpanded
originalAuthorExpanded = willExpand
if (willExpand) {
supportScope.launch {
delay(80)
supportScrollState.animateScrollTo(
(originalAuthorSectionY - topRevealOffsetPx)
.toInt()
.coerceAtLeast(0),
)
}
}
},
onClick = onDonateOriginalClick,
emphasized = false
modifier = Modifier.onGloballyPositioned {
originalAuthorSectionY = it.positionInParent().y
},
)
Spacer(Modifier.height(4.dp))
}
@@ -1223,6 +1274,91 @@ private fun AdditionalActionsDialog(
}
}
@Composable
private fun OriginalAuthorSupportBlock(
expanded: Boolean,
onToggle: () -> Unit,
onClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val arrowRotation by animateFloatAsState(
targetValue = if (expanded) 180f else 0f,
label = "original_author_arrow_rotation",
)
Surface(
modifier = modifier,
shape = RoundedCornerShape(22.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
border = BorderStroke(
1.dp,
MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f),
),
) {
Column(modifier = Modifier.fillMaxWidth()) {
Row(
modifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(22.dp))
.remoteFocusOutline(RoundedCornerShape(22.dp))
.clickable(onClick = onToggle)
.padding(horizontal = 16.dp, vertical = 14.dp),
horizontalArrangement = Arrangement.spacedBy(10.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
Icons.Default.Person,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(20.dp),
)
Text(
"Автор оригинального приложения",
modifier = Modifier.weight(1f),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold,
)
Icon(
Icons.Default.KeyboardArrowDown,
contentDescription = if (expanded) "Свернуть" else "Развернуть",
modifier = Modifier.size(24.dp).rotate(arrowRotation),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
AnimatedVisibility(
visible = expanded,
enter = expandVertically() + fadeIn(),
exit = shrinkVertically() + fadeOut(),
) {
Column(
modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f),
)
Text(
"Оригинальная основа проекта создана amurcanov. Можно отдельно поддержать автора исходного приложения.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
lineHeight = 18.sp,
)
Button(
onClick = onClick,
shape = RoundedCornerShape(18.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = Color.White,
),
modifier = Modifier.fillMaxWidth().heightIn(min = 46.dp),
) {
Text("ЮMoney", fontWeight = FontWeight.Bold)
}
}
}
}
}
}
@Composable
private fun RemoteActionFormDialog(
form: RemoteActionForm,
@@ -2056,7 +2192,12 @@ internal fun sleepBatteryRuntimeDiagnosticText(
return "$phase, осталось ${formatSleepTimerDuration(boundedMinutes)}"
}
private suspend fun buildSupportReportSummary(context: Context, settingsStore: SettingsStore): List<String> {
private suspend fun buildSupportReportSummary(
context: Context,
settingsStore: SettingsStore,
tunnelMode: String,
): List<String> {
val systemVpnMode = tunnelModeNeedsVpnPermission(tunnelMode)
val androidVersion = Build.VERSION.RELEASE ?: "?"
val sdkInt = Build.VERSION.SDK_INT
val primaryAbi = Build.SUPPORTED_ABIS.firstOrNull().orEmpty().ifBlank { "unknown" }
@@ -2146,7 +2287,8 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
val powerManager = runCatching { context.getSystemService(PowerManager::class.java) }.getOrNull()
val powerSummary = diagnosticText {
"экономия=${powerManager?.isPowerSaveMode}, " +
"без ограничений батареи=${powerManager?.isIgnoringBatteryOptimizations(context.packageName)}"
"без ограничений батареи=${powerManager?.isIgnoringBatteryOptimizations(context.packageName)}, " +
"ограничено в фоне=${activityManager?.isBackgroundRestricted}"
}
val webViewInfo = diagnosticText {
@@ -2155,8 +2297,14 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
val nativeComponentsInfo = runCatching {
val nativeClient = File(appInfo?.nativeLibraryDir.orEmpty(), "libclient.so")
val wireGuardBackend = File(appInfo?.nativeLibraryDir.orEmpty(), "libwg-go.so")
"libclient.so=${if (nativeClient.isFile) formatMiB(nativeClient.length()) else "не найден"}, " +
"libwg-go.so=${if (wireGuardBackend.isFile) formatMiB(wireGuardBackend.length()) else "не найден"}"
buildString {
append("libclient.so=${if (nativeClient.isFile) formatMiB(nativeClient.length()) else "не найден"}")
if (systemVpnMode) {
append(", libwg-go.so=${if (wireGuardBackend.isFile) formatMiB(wireGuardBackend.length()) else "не найден"}")
} else {
append(", libwg-go.so не требуется для SOCKS5")
}
}
}.getOrDefault("недоступно")
val notificationPermission = diagnosticText {
@@ -2204,7 +2352,6 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
.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 rtNetworkEnabled = runCatching { settingsStore.rtNetwork.first() }.getOrNull()
val rtMasqueEnabled = runCatching { settingsStore.rtMasque.first() }.getOrNull()
@@ -2233,6 +2380,7 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrNull()
val trustedWifiCount = runCatching { settingsStore.trustedWifiSsids.first().size }.getOrNull()
val sleepBatteryEnabled = runCatching { settingsStore.pauseVpnDuringSleep.first() }.getOrNull()
val screenOffMode = runCatching { settingsStore.screenOffMode.first() }.getOrNull()
val sleepBatteryPauseDelay = runCatching { settingsStore.pauseVpnDuringSleepDelayMinutes.first() }.getOrNull()
val sleepBatteryMode = runCatching { settingsStore.sleepBatteryMode.first() }.getOrNull()
val sleepBatteryResumeDelay = runCatching { settingsStore.resumeVpnDuringSleepDelayMinutes.first() }.getOrNull()
@@ -2293,36 +2441,62 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
appendLine("Экран: $screenSummary")
appendLine("Разрешение уведомлений: $notificationPermission")
appendLine("Установка обновлений APK: $updateInstallPermission")
appendLine("VPN-разрешение: $vpnPermission")
appendLine("Режим соединения: ${if (systemVpnMode) "системный VPN" else "локальный SOCKS5"}")
if (systemVpnMode) {
appendLine("VPN-разрешение: $vpnPermission")
appendLine(
"Доверенные Wi-Fi: включено=${trustedWifiEnabled ?: "недоступно"}, " +
"сетей=${trustedWifiCount ?: "недоступно"}, ожидание=$trustedWifiWaiting, доступ=$trustedWifiAccess"
)
}
appendLine(
"Доверенные Wi-Fi: включено=${trustedWifiEnabled ?: "недоступно"}, " +
"сетей=${trustedWifiCount ?: "недоступно"}, ожидание=$trustedWifiWaiting, доступ=$trustedWifiAccess"
)
appendLine(
"Экономия батареи во сне: включено=${sleepBatteryEnabled ?: "недоступно"}, " +
"Работа при выключенном экране: режим=${screenOffMode?.let { mode ->
when (mode) {
ScreenOffMode.BALANCED -> "сбалансированно"
ScreenOffMode.HOLD_CONNECTION -> "удерживать соединение"
ScreenOffMode.SAVE_BATTERY -> "экономить батарею"
}
} ?: "недоступно"}, " +
"экономия включена=${sleepBatteryEnabled ?: "недоступно"}, " +
"режим=${sleepBatteryMode?.let(::sleepBatteryModeDiagnosticText) ?: "недоступно"}, " +
"отключение через=${sleepBatteryPauseDelay?.let(::formatSleepTimerDuration) ?: "недоступно"}, " +
"включение через=${sleepBatteryResumeDelay?.let(::formatSleepTimerDuration) ?: "недоступно"}, " +
"состояние=${sleepBatteryRuntime?.let(::sleepBatteryRuntimeDiagnosticText) ?: "недоступно"}"
)
TunnelManager.connectionHoldDiagnostics.value.let { hold ->
appendLine(
"Диагностика удержания: выбрано=${hold.modeSelected}, активно=${hold.active}, " +
"CPU wake lock=${hold.cpuWakeLockHeld}, Wi-Fi lock=${hold.wifiLockHeld}, " +
"Wi-Fi доступен=${hold.wifiTransportAvailable}, экран активен=${hold.deviceInteractive}"
)
}
appendLine("Локаль: ${diagnosticText { Locale.getDefault().toLanguageTag() }}")
appendLine("Часовой пояс: ${diagnosticText { TimeZone.getDefault().id }}")
appendLine("Туннель: запущен=${TunnelManager.running.value}, активных=${TunnelManager.activeWorkers.value}")
appendLine("Последняя проблема: $tunnelIssue")
appendLine(
"Последняя остановка соединения: " +
(TunnelManager.lastStopReason.value?.displayText ?: "не зафиксирована в текущем процессе")
)
appendLine("Профиль: ${activeProfile ?: "недоступно"}")
appendLine(
"Маршрутизация профиля: режим=${routingSettings?.let { if (it.isWhitelist) "БС" else "ЧС" } ?: "недоступно"}, " +
"приложений=${routingSettings?.let { routingPackages.size } ?: "недоступно"}, " +
"адресов=${routingSettings?.addressRules?.size ?: "недоступно"}, " +
"доменов=${routingDomains ?: "недоступно"}"
)
appendLine(
"DNS внутри VPN: ${vpnDnsSettings?.title ?: "недоступно"}, " +
"адреса=${vpnDnsSettings?.configuredServers?.joinToString(", ")?.ifBlank { "из WireGuard-профиля" } ?: "недоступно"}, " +
"smart=${vpnDnsSettings?.isSmartDns ?: "недоступно"}"
)
if (systemVpnMode) {
appendLine(
"Маршрутизация профиля: режим=${routingSettings?.let { if (it.isWhitelist) "БС" else "ЧС" } ?: "недоступно"}, " +
"приложений=${routingSettings?.let { routingPackages.size } ?: "недоступно"}, " +
"адресов=${routingSettings?.addressRules?.size ?: "недоступно"}, " +
"доменов=${routingDomains ?: "недоступно"}"
)
appendLine(
"DNS внутри VPN: ${vpnDnsSettings?.title ?: "недоступно"}, " +
"адреса=${vpnDnsSettings?.configuredServers?.joinToString(", ")?.ifBlank { "из WireGuard-профиля" } ?: "недоступно"}, " +
"smart=${vpnDnsSettings?.isSmartDns ?: "недоступно"}"
)
}
appendLine("Потоки: ${workers ?: "недоступно"}")
appendLine("VK-хеши: заполнено $hashCount, запасной=${hasSecondaryHash ?: "недоступно"}")
appendLine(
"VK-хеши: заполнено $hashCount, " +
"автоматический резерв между хешами=${if (hashCount > 1) "включён" else "недоступен"}"
)
appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}")
appendLine("Сеть РТ (TURN stream-first): ${rtNetworkEnabled ?: "недоступно"}")
appendLine(
@@ -149,8 +149,11 @@ fun LogLine(entry: LogEntry, sessionActive: Boolean) {
entry.priority == 3 -> if (isDark) WDTTColors.terminalBlue else MaterialTheme.colorScheme.primary
else -> if (isDark) WDTTColors.terminalText else MaterialTheme.colorScheme.onSurface
}
val isStoppedStats = entry.key == "stats" &&
(entry.message.contains("VPN отключён") || entry.message.contains("VPN в ожидании"))
val isStoppedStats = entry.key == "stats" && listOf(
"VPN отключён",
"VPN в ожидании",
"SOCKS5 отключён",
).any(entry.message::contains)
val color = when {
sessionActive -> activeColor
isStoppedStats -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.9f)
@@ -63,7 +63,7 @@ internal fun RtNetworkSettingsDialog(
!rtNetwork -> "Сначала включите «Сеть РТ»"
!rtMasque -> "Сначала включите MASQUE"
!serverAccess.available -> "Недоступно: ${serverAccess.unavailableReason}"
tunnelRunning -> "Остановите VPN, чтобы изменить настройку"
tunnelRunning -> "Остановите соединение, чтобы изменить настройку"
else -> "Только первая регистрация WARP · SSH из «Деплой»"
}
val serverTextIsError = rtNetwork && rtMasque && !serverAccess.available
@@ -149,7 +149,7 @@ internal fun RtNetworkSettingsDialog(
if (!rtNetwork) {
"Включите «Сеть РТ» в основном окне, чтобы изменить эти параметры."
} else {
"Остановите VPN, чтобы изменить параметры режима."
"Остановите соединение, чтобы изменить параметры режима."
},
modifier = Modifier.padding(14.dp),
style = MaterialTheme.typography.bodySmall,
@@ -0,0 +1,198 @@
package com.wdtt.plus.ui
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.PowerManager
import android.provider.Settings
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.wdtt.plus.ScreenOffMode
import com.wdtt.plus.DeviceCompatibility
import com.wdtt.plus.ProcessExitCategory
import com.wdtt.plus.classifyProcessExit
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
internal fun isBatteryOptimizationDisabled(context: Context): Boolean {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
return powerManager.isIgnoringBatteryOptimizations(context.packageName)
}
@Composable
internal fun ScreenOffModeDialog(
initialMode: ScreenOffMode,
onApply: (ScreenOffMode) -> Unit,
onConfigureBatterySaving: (ScreenOffMode) -> Unit,
onDismiss: () -> Unit,
) {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
var selectedName by rememberSaveable(initialMode) { mutableStateOf(initialMode.name) }
val selected = ScreenOffMode.valueOf(selectedName)
var batteryUnrestricted by remember { mutableStateOf(isBatteryOptimizationDisabled(context)) }
var recentSystemStop by remember {
mutableStateOf(
DeviceCompatibility.recentProcessExitHistory(context)
?.latestUnexpected
?.let(::classifyProcessExit) == ProcessExitCategory.SystemPolicy
)
}
DisposableEffect(lifecycleOwner, context) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
batteryUnrestricted = isBatteryOptimizationDisabled(context)
recentSystemStop = DeviceCompatibility.recentProcessExitHistory(context)
?.latestUnexpected
?.let(::classifyProcessExit) == ProcessExitCategory.SystemPolicy
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
}
val options = listOf(
ScreenOffMode.BALANCED to (
"Сбалансированно" to
"Обычная фоновая работа и современное автоматическое восстановление. Режим по умолчанию."
),
ScreenOffMode.HOLD_CONNECTION to (
"Удерживать соединение" to
"Старается сохранять активное соединение при выключенном экране, в том числе при работе через Wi‑Fi. " +
"Может заметно увеличить расход батареи."
),
ScreenOffMode.SAVE_BATTERY to (
"Экономить батарею" to
"Намеренно приостанавливает VPN по сохранённому сценарию и возобновляет его автоматически."
),
)
AlertDialog(
onDismissRequest = onDismiss,
text = {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
options.forEach { (mode, presentation) ->
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { selectedName = mode.name }
.padding(vertical = 6.dp),
verticalAlignment = Alignment.Top,
) {
RadioButton(
selected = selected == mode,
onClick = { selectedName = mode.name },
)
Column(modifier = Modifier.padding(start = 8.dp)) {
Text(presentation.first, fontWeight = FontWeight.SemiBold)
Text(
presentation.second,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
}
if (selected == ScreenOffMode.HOLD_CONNECTION) {
Text(
if (recentSystemStop) {
"Android недавно принудительно завершил WDTT Plus. Проверьте в настройках приложения разрешение фоновой работы; на некоторых телефонах оно действует отдельно от обычной оптимизации батареи."
} else if (batteryUnrestricted) {
"WDTT Plus исключён из стандартной оптимизации батареи Android. Ограничения производителя телефона могут действовать отдельно."
} else {
"Android может всё равно ограничить приложение. Разрешите работу без ограничения батареи."
},
style = MaterialTheme.typography.bodySmall,
color = if (batteryUnrestricted) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.error
},
)
OutlinedButton(
onClick = {
if (!batteryUnrestricted) {
val intent = Intent(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
Uri.parse("package:${context.packageName}"),
).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
runCatching { context.startActivity(intent) }.onFailure {
context.startActivity(
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.parse("package:${context.packageName}"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
batteryUnrestricted = isBatteryOptimizationDisabled(context)
} else {
context.startActivity(
Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
.setData(Uri.parse("package:${context.packageName}"))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
)
}
},
) {
Text(if (batteryUnrestricted) "Настройки приложения" else "Разрешить фоновую работу")
}
}
if (selected == ScreenOffMode.SAVE_BATTERY) {
TextButton(onClick = { onConfigureBatterySaving(selected) }) {
Text("Настроить таймер экономии")
}
}
}
},
title = {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = "Работа при выключенном экране",
modifier = Modifier.weight(1f),
)
IconButton(
onClick = onDismiss,
modifier = Modifier.remoteIconButtonFocus(),
) {
Icon(Icons.Default.Close, contentDescription = "Закрыть")
}
}
},
confirmButton = {
Button(onClick = { onApply(selected) }) { Text("Сохранить") }
},
)
}
@@ -70,7 +70,6 @@ import androidx.compose.material.icons.filled.SaveAlt
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.Smartphone
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
File diff suppressed because it is too large. Load diff
@@ -23,7 +23,6 @@ import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
@@ -1,35 +1,11 @@
package com.wdtt.plus.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
/**
* Выбранный сегмент уже однозначно обозначен заливкой. Пустой icon slot не
* отнимает ширину у подписи и сохраняет единый API существующих кнопок.
*/
@Composable
internal fun StableSegmentedButtonIcon(selected: Boolean) {
Box(
modifier = Modifier.size(18.dp),
contentAlignment = Alignment.Center
) {
AnimatedVisibility(
visible = selected,
enter = fadeIn(tween(120)),
exit = fadeOut(tween(90))
) {
Icon(
imageVector = Icons.Default.Check,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
}
}
}
@Suppress("UNUSED_PARAMETER")
internal fun StableSegmentedButtonIcon(selected: Boolean) = Unit
@@ -34,7 +34,6 @@ import androidx.compose.material.icons.filled.QrCode2
import androidx.compose.material.icons.filled.SaveAlt
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -225,7 +224,7 @@ fun TransferCenterDialog(
HorizontalDivider()
Text("Настройки администратора", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
Text(
"Все три VPN-профиля, параметры деплоя, пароли, токен бота, исключения и настройки выхода. Данные шифруются указанным паролем. Приватные SSH-ключи и конфигурации служб на VPS не передаются.",
"Все три профиля подключения, параметры деплоя, пароли, токен бота, исключения и настройки выхода. Данные шифруются указанным паролем. Приватные SSH-ключи и конфигурации служб на VPS не передаются.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -360,7 +359,7 @@ fun AdminImportDialog(
modifier = Modifier.fillMaxWidth().onFocusChanged { passwordFocused = it.isFocused }
)
} else {
Text("Будут заменены все три VPN-профиля и локальные настройки администратора. Текущие данные приложения восстановить автоматически не получится. Приватные SSH-ключи и конфигурации служб на VPS не входят в передачу: при необходимости добавьте их отдельно.")
Text("Будут заменены все три профиля подключения и локальные настройки администратора. Текущие данные приложения восстановить автоматически не получится. Приватные SSH-ключи и конфигурации служб на VPS не входят в передачу: при необходимости добавьте их отдельно.")
}
error?.let { Text(it, color = MaterialTheme.colorScheme.error) }
}
@@ -31,7 +31,6 @@ import androidx.compose.material.icons.filled.DeleteOutline
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.Wifi
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
@@ -239,7 +238,7 @@ fun TrustedWifiSettingsDialog(
fontWeight = FontWeight.Bold
)
Text(
"Общая настройка для всех VPN-профилей",
"Для системного VPN во всех профилях",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -29,7 +29,6 @@ import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.VpnKey
import androidx.compose.material.icons.filled.WarningAmber
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.HorizontalDivider
@@ -306,7 +305,7 @@ fun VkClientSettingsDialog(
fontWeight = FontWeight.Bold
)
Text(
"Настройка для текущего VPN-профиля",
"Настройка для текущего профиля подключения",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
@@ -21,7 +21,6 @@ import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.WarningAmber
import androidx.compose.material3.AlertDialogDefaults
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
@@ -0,0 +1,100 @@
package com.wdtt.plus.ui
import android.os.Build
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ButtonElevation
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.graphicsLayer
/**
* Filled button used throughout the app.
*
* Some MIUI builds keep the surrounding text style color when Material 3
* changes a button's content color. Icons then use the intended contrasting
* color, while labels remain almost indistinguishable from the background.
* The workaround is deliberately limited to Xiaomi-family firmware. Every
* other device receives Material's original content without another layout or
* color layer.
*/
@Composable
internal fun Button(
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
shape: Shape = ButtonDefaults.shape,
colors: ButtonColors = ButtonDefaults.buttonColors(),
elevation: ButtonElevation? = ButtonDefaults.buttonElevation(),
border: BorderStroke? = null,
contentPadding: PaddingValues = ButtonDefaults.ContentPadding,
interactionSource: MutableInteractionSource? = null,
content: @Composable RowScope.() -> Unit,
) {
val needsMiuiWorkaround = needsMiuiFilledButtonContrastWorkaround(
manufacturer = Build.MANUFACTURER.orEmpty(),
brand = Build.BRAND.orEmpty(),
)
androidx.compose.material3.Button(
onClick = onClick,
modifier = modifier,
enabled = enabled,
shape = shape,
colors = colors,
elevation = elevation,
border = border,
contentPadding = contentPadding,
interactionSource = interactionSource,
) {
if (!needsMiuiWorkaround) {
content()
} else {
val resolvedContentColor = if (enabled) colors.contentColor else colors.disabledContentColor
CompositionLocalProvider(
LocalContentColor provides resolvedContentColor,
LocalTextStyle provides LocalTextStyle.current.copy(color = resolvedContentColor),
) {
Row(
modifier = Modifier
.graphicsLayer {
compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen
}
.drawWithContent {
drawContent()
drawRect(
color = resolvedContentColor.copy(alpha = 1f),
blendMode = BlendMode.SrcIn,
)
},
verticalAlignment = Alignment.CenterVertically,
) {
content()
}
}
}
}
}
internal fun needsMiuiFilledButtonContrastWorkaround(
manufacturer: String,
brand: String,
): Boolean {
val normalizedManufacturer = manufacturer.trim().lowercase()
val normalizedBrand = brand.trim().lowercase()
return normalizedManufacturer in XIAOMI_DEVICE_NAMES ||
normalizedBrand in XIAOMI_DEVICE_NAMES
}
private val XIAOMI_DEVICE_NAMES = setOf("xiaomi", "redmi", "poco")
+1 -1
View File
@@ -47,7 +47,7 @@
android:layout_centerVertical="true"
android:background="@drawable/bg_widget_button_inactive"
android:src="@drawable/ic_tile_logo"
android:contentDescription="Toggle VPN"
android:contentDescription="Включить или отключить соединение"
android:padding="10dp"
android:scaleType="fitCenter" />
@@ -13,7 +13,7 @@
android:layout_width="42dp"
android:layout_height="42dp"
android:background="@drawable/bg_widget_button_inactive"
android:contentDescription="Включить или отключить VPN"
android:contentDescription="Включить или отключить соединение"
android:padding="9dp"
android:scaleType="fitCenter"
android:src="@drawable/ic_tile_logo" />