Выпуск WDTT Plus v16
This commit is contained in:
1 parent
3038b8ddc0
commit
4be5f36c88
102 files changed
+21554
-1427
No files matched your search
@@ -23,10 +23,20 @@
|
||||
<uses-feature
|
||||
android:name="android.hardware.camera.any"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.location"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.touchscreen"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.software.leanback"
|
||||
android:required="false" />
|
||||
|
||||
<application
|
||||
android:name=".WdttApplication"
|
||||
android:allowBackup="false"
|
||||
android:banner="@drawable/tv_banner"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="${appLabel}"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
@@ -42,6 +52,10 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES" />
|
||||
</intent-filter>
|
||||
@@ -121,14 +135,18 @@
|
||||
android:value="persistent_vpn_tunnel_transport" />
|
||||
</service>
|
||||
|
||||
<!--
|
||||
GoBackend добавляет свой VpnService из зависимости. WDTT Plus не
|
||||
реализует системный сценарий «Всегда включённый VPN»: он конфликтует
|
||||
с ручной передачей единственного VPN-слота другому приложению.
|
||||
-->
|
||||
<!-- SafeGoBackend retains upstream wg-go but does not probe ownership
|
||||
with prepare() outside an explicit user action. -->
|
||||
<service
|
||||
android:name="com.wireguard.android.backend.GoBackend$VpnService"
|
||||
tools:node="merge">
|
||||
tools:node="remove" />
|
||||
<service
|
||||
android:name=".SafeGoBackend$VpnService"
|
||||
android:exported="false"
|
||||
android:permission="android.permission.BIND_VPN_SERVICE">
|
||||
<intent-filter>
|
||||
<action android:name="android.net.VpnService" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
|
||||
android:value="false" />
|
||||
|
||||
@@ -2,14 +2,20 @@
|
||||
# ==============================================================================
|
||||
# WDTT Plus Server — Универсальный установщик для VPS
|
||||
# Поддержка: Debian 11+, Ubuntu 20.04+, CentOS/RHEL/Fedora/AlmaLinux/Rocky
|
||||
# Версия: 3.5 | Дата: 2026-07-30
|
||||
# Версия: 3.9 | Дата: 2026-09-02
|
||||
# NAT: MASQUERADE через iptables
|
||||
# WG: порт 56001 (не конфликтует с существующим WG на 51820)
|
||||
# DTLS: порт 56000
|
||||
# ==============================================================================
|
||||
set -uo pipefail
|
||||
set -euo pipefail
|
||||
|
||||
readonly SCRIPT_VERSION="3.5"
|
||||
readonly SCRIPT_VERSION="3.9"
|
||||
readonly WDTT_DEPLOY_CONTRACT_VERSION="1"
|
||||
readonly WDTT_SERVER_VERSION="16"
|
||||
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_CONTRACT_MARKER="WDTT deploy compatibility: 1"
|
||||
readonly LOG_FILE="/var/log/wdtt-install.log"
|
||||
readonly WG_PORT="${WDTT_WG_PORT:-56001}"
|
||||
readonly DTLS_PORT="${WDTT_DTLS_PORT:-56000}"
|
||||
@@ -20,12 +26,13 @@ readonly MAX_HANDSHAKES="${WDTT_MAX_HANDSHAKES:-32}"
|
||||
readonly HANDSHAKE_RATE="${WDTT_HANDSHAKE_RATE:-24}"
|
||||
readonly MAX_CLIENT_MBPS="${WDTT_MAX_CLIENT_MBPS:-0}"
|
||||
readonly WG_BACKEND="${WDTT_WG_BACKEND:-auto}"
|
||||
readonly WDTT_ARGS="${WDTT_ARGS:-}"
|
||||
readonly WDTT_PRESERVE_DATA="${WDTT_PRESERVE_DATA:-0}"
|
||||
readonly WDTT_IFACE="wdtt0"
|
||||
readonly WDTT_CONFIG_DIR="/etc/wdtt"
|
||||
readonly WDTT_ACCESS_DB="passwords.json"
|
||||
readonly WDTT_ACCESS_DB_PREVIOUS="passwords.json.previous"
|
||||
readonly WDTT_WG_KEYS="wg-keys.dat"
|
||||
readonly WDTT_STAGED_DB="${WDTT_STAGED_DB:-}"
|
||||
readonly IPT_COMMENT="WDTT_MANAGED"
|
||||
readonly IPT_MIRROR_COMMENT="WDTT_MIRRORED"
|
||||
|
||||
@@ -366,11 +373,34 @@ fw_cleanup_wdtt_rules() {
|
||||
fi
|
||||
}
|
||||
|
||||
cleanup_config_dir_keep_access_db() {
|
||||
secure_preserved_config() {
|
||||
[ -d "$WDTT_CONFIG_DIR" ] || return 0
|
||||
find "$WDTT_CONFIG_DIR" -mindepth 1 -maxdepth 1 ! -name "$WDTT_ACCESS_DB" ! -name "$WDTT_WG_KEYS" -exec rm -rf {} + 2>/dev/null || true
|
||||
[ -f "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" ] && chmod 600 "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" 2>/dev/null || true
|
||||
[ -f "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] && chmod 600 "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" 2>/dev/null || true
|
||||
[ ! -L "$WDTT_CONFIG_DIR" ] || die "$WDTT_CONFIG_DIR не должен быть символической ссылкой"
|
||||
local name path
|
||||
for name in "$WDTT_ACCESS_DB" "$WDTT_ACCESS_DB_PREVIOUS" "$WDTT_WG_KEYS" "outbound-profile.env"; do
|
||||
path="$WDTT_CONFIG_DIR/$name"
|
||||
[ -e "$path" ] || continue
|
||||
[ -f "$path" ] && [ ! -L "$path" ] || die "Небезопасный объект конфигурации: $path"
|
||||
chmod 600 "$path" || die "Не удалось защитить $path"
|
||||
done
|
||||
}
|
||||
|
||||
validate_deploy_data_mode() {
|
||||
local database="$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB"
|
||||
if [ -e "$database" ] && [ "$WDTT_PRESERVE_DATA" != "1" ]; then
|
||||
die "Найдена существующая база WDTT. Обновление разрешено только в режиме сохранения; явный сброс должен заранее удалить старую базу после подтверждения в приложении."
|
||||
fi
|
||||
if [ "$WDTT_PRESERVE_DATA" = "1" ]; then
|
||||
[ -f "$database" ] && [ ! -L "$database" ] && [ -s "$database" ] ||
|
||||
die "Режим сохранения требует обычный непустой passwords.json"
|
||||
secure_preserved_config
|
||||
fi
|
||||
if [ -n "$WDTT_STAGED_DB" ]; then
|
||||
[ -f "$WDTT_STAGED_DB" ] && [ ! -L "$WDTT_STAGED_DB" ] && [ -s "$WDTT_STAGED_DB" ] ||
|
||||
die "Подготовленная база WDTT отсутствует или небезопасна"
|
||||
[ "$(stat -c '%a' "$WDTT_STAGED_DB")" = "600" ] ||
|
||||
die "Подготовленная база WDTT должна иметь права 600"
|
||||
fi
|
||||
}
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════════
|
||||
@@ -384,9 +414,6 @@ wdtt_cleanup() {
|
||||
|
||||
systemctl unmask wdtt 2>/dev/null || true
|
||||
systemctl stop wdtt 2>/dev/null || true
|
||||
systemctl disable wdtt 2>/dev/null || true
|
||||
rm -f /etc/systemd/system/wdtt.service 2>/dev/null || true
|
||||
systemctl daemon-reload 2>/dev/null || true
|
||||
pkill -x wdtt-server 2>/dev/null || killall wdtt-server 2>/dev/null || true
|
||||
|
||||
# Удаляем только собственный интерфейс WDTT.
|
||||
@@ -396,12 +423,13 @@ wdtt_cleanup() {
|
||||
fw_cleanup_wdtt_rules "$(detect_wan_interface)"
|
||||
|
||||
if [ "$WDTT_PRESERVE_DATA" = "1" ]; then
|
||||
[ -f "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" ] && chmod 600 "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" 2>/dev/null || true
|
||||
[ -f "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" ] && chmod 600 "$WDTT_CONFIG_DIR/$WDTT_WG_KEYS" 2>/dev/null || true
|
||||
echo "✓ Режим обновления: конфигурация и данные сохранены"
|
||||
secure_preserved_config
|
||||
echo "✓ Режим обновления: всё содержимое /etc/wdtt сохранено"
|
||||
else
|
||||
systemctl disable wdtt 2>/dev/null || true
|
||||
rm -f /etc/systemd/system/wdtt.service 2>/dev/null || true
|
||||
systemctl daemon-reload 2>/dev/null || true
|
||||
rm -f /usr/local/bin/wdtt-server 2>/dev/null || true
|
||||
cleanup_config_dir_keep_access_db
|
||||
fi
|
||||
|
||||
echo "✓ Очистка завершена (база доступа сохранена)"
|
||||
@@ -482,7 +510,12 @@ setup_wdtt_binary() {
|
||||
echo "📦 Установка wdtt-server..."
|
||||
|
||||
if [ -f /tmp/wdtt-server ]; then
|
||||
[ ! -L /tmp/wdtt-server ] && [ -s /tmp/wdtt-server ] || die "/tmp/wdtt-server отсутствует или небезопасен"
|
||||
chmod +x /tmp/wdtt-server
|
||||
local staged_version
|
||||
staged_version="$(/tmp/wdtt-server --version 2>/dev/null | head -n 1 || true)"
|
||||
[ "$staged_version" = "$WDTT_SERVER_VERSION" ] ||
|
||||
die "Загружен wdtt-server несовместимой версии: ожидается $WDTT_SERVER_VERSION, получено ${staged_version:-не определено}"
|
||||
rm -f /usr/local/bin/.wdtt-server.new
|
||||
install -m 0755 /tmp/wdtt-server /usr/local/bin/.wdtt-server.new || die "Не удалось подготовить новый wdtt-server"
|
||||
mv -f /usr/local/bin/.wdtt-server.new /usr/local/bin/wdtt-server || die "Не удалось атомарно заменить wdtt-server"
|
||||
@@ -495,7 +528,23 @@ setup_wdtt_binary() {
|
||||
echo " Загрузите бинарник вручную в /usr/local/bin/wdtt-server"
|
||||
fi
|
||||
|
||||
if [ -x "$WDTT_SERVER_BINARY_PATH" ]; then
|
||||
local server_version
|
||||
server_version="$("$WDTT_SERVER_BINARY_PATH" --version 2>/dev/null | head -n 1 || true)"
|
||||
[ "$server_version" = "$WDTT_SERVER_VERSION" ] ||
|
||||
die "wdtt-server несовместимой версии: ожидается $WDTT_SERVER_VERSION, получено ${server_version:-не определено}"
|
||||
fi
|
||||
|
||||
mkdir -p "$WDTT_CONFIG_DIR"
|
||||
chmod 700 "$WDTT_CONFIG_DIR"
|
||||
if [ -n "$WDTT_STAGED_DB" ]; then
|
||||
install -m 0600 "$WDTT_STAGED_DB" "$WDTT_CONFIG_DIR/.passwords.json.new" ||
|
||||
die "Не удалось подготовить passwords.json"
|
||||
mv -f "$WDTT_CONFIG_DIR/.passwords.json.new" "$WDTT_CONFIG_DIR/$WDTT_ACCESS_DB" ||
|
||||
die "Не удалось атомарно установить passwords.json"
|
||||
rm -f "$WDTT_STAGED_DB"
|
||||
fi
|
||||
secure_preserved_config
|
||||
}
|
||||
|
||||
# ─── Systemd-сервис WDTT ─────────────────────────────────────────────────────
|
||||
@@ -503,7 +552,11 @@ setup_wdtt_service() {
|
||||
prog 0.75 "Сервис..."
|
||||
echo "🔧 Создание systemd-сервиса WDTT Plus..."
|
||||
|
||||
cat > /etc/systemd/system/wdtt.service << WDTTSVC
|
||||
local unit_tmp="/etc/systemd/system/.wdtt.service.new"
|
||||
rm -f "$unit_tmp"
|
||||
cat > "$unit_tmp" << WDTTSVC
|
||||
# ${WDTT_ANDROID_DEPLOY_MARKER}
|
||||
# ${WDTT_ANDROID_CONTRACT_MARKER}
|
||||
[Unit]
|
||||
Description=WDTT Plus Server
|
||||
After=network.target network-online.target
|
||||
@@ -513,7 +566,7 @@ Wants=network-online.target
|
||||
Type=simple
|
||||
ExecStartPre=-/usr/bin/env bash -c "ip link show ${WDTT_IFACE} >/dev/null 2>&1 && ip link del ${WDTT_IFACE} 2>/dev/null || true"
|
||||
ExecStartPre=-/usr/bin/env bash -c "if command -v iptables >/dev/null 2>&1; then iptables -C INPUT -p udp --dport ${DTLS_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${DTLS_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; iptables -C INPUT -p udp --dport ${WG_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p udp --dport ${WG_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; iptables -C INPUT -p tcp --dport ${SSH_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT 2>/dev/null || iptables -I INPUT -p tcp --dport ${SSH_PORT} -m comment --comment ${IPT_COMMENT} -j ACCEPT; fi"
|
||||
ExecStart=/usr/local/bin/wdtt-server -listen 0.0.0.0:${DTLS_PORT} -wg-port ${WG_PORT} -config-dir ${WDTT_CONFIG_DIR} -max-passwords ${MAX_PASSWORDS} -max-workers-per-access ${MAX_WORKERS_PER_ACCESS} -max-handshakes ${MAX_HANDSHAKES} -handshake-rate ${HANDSHAKE_RATE} -max-client-mbps ${MAX_CLIENT_MBPS} -wg-backend ${WG_BACKEND} ${WDTT_ARGS}
|
||||
ExecStart=${WDTT_SERVER_BINARY_PATH} -listen 0.0.0.0:${DTLS_PORT} -wg-port ${WG_PORT} -config-dir ${WDTT_CONFIG_DIR} -max-passwords ${MAX_PASSWORDS} -max-workers-per-access ${MAX_WORKERS_PER_ACCESS} -max-handshakes ${MAX_HANDSHAKES} -handshake-rate ${HANDSHAKE_RATE} -max-client-mbps ${MAX_CLIENT_MBPS} -wg-backend ${WG_BACKEND}
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
LimitNOFILE=65535
|
||||
@@ -522,6 +575,9 @@ LimitNOFILE=65535
|
||||
WantedBy=multi-user.target
|
||||
WDTTSVC
|
||||
|
||||
chmod 644 "$unit_tmp"
|
||||
mv -f "$unit_tmp" "$WDTT_SYSTEMD_UNIT_PATH" || die "Не удалось атомарно установить wdtt.service"
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl unmask wdtt >/dev/null 2>&1 || true
|
||||
systemctl enable wdtt >/dev/null 2>&1 || true
|
||||
@@ -559,6 +615,7 @@ start_wdtt() {
|
||||
echo "⚠️ Сервис wdtt не запустился. Статус: $status"
|
||||
echo " Последние логи:"
|
||||
journalctl -u wdtt -n 7 --no-pager 2>/dev/null | sed 's/^/ >> /'
|
||||
die "Сервис wdtt не прошёл проверку запуска"
|
||||
fi
|
||||
|
||||
echo " Логи: journalctl -u wdtt -f"
|
||||
@@ -582,7 +639,7 @@ do_uninstall() {
|
||||
fw_cleanup_wdtt_rules "$(detect_wan_interface)"
|
||||
|
||||
rm -f /usr/local/bin/wdtt-server
|
||||
cleanup_config_dir_keep_access_db
|
||||
secure_preserved_config
|
||||
rm -f /etc/sysctl.d/99-wdtt.conf
|
||||
sysctl --system >/dev/null 2>&1 || true
|
||||
|
||||
@@ -629,15 +686,21 @@ main() {
|
||||
mkdir -p "$(dirname "$LOG_FILE")"
|
||||
echo "=== WDTT Plus Installer v${SCRIPT_VERSION} — $(date) ===" >> "$LOG_FILE"
|
||||
|
||||
detect_os
|
||||
install_prerequisites
|
||||
require_runtime_tools
|
||||
detect_firewall
|
||||
|
||||
case "$action" in
|
||||
status|--status|-s) do_status ;;
|
||||
uninstall|--uninstall|-u) do_uninstall ;;
|
||||
status|--status|-s)
|
||||
do_status
|
||||
;;
|
||||
uninstall|--uninstall|-u)
|
||||
require_runtime_tools
|
||||
secure_preserved_config
|
||||
do_uninstall
|
||||
;;
|
||||
install|--install|-i|*)
|
||||
validate_deploy_data_mode
|
||||
detect_os
|
||||
install_prerequisites
|
||||
require_runtime_tools
|
||||
detect_firewall
|
||||
wdtt_cleanup
|
||||
setup_sysctl
|
||||
setup_nat_and_firewall
|
||||
|
||||
@@ -72,6 +72,21 @@ internal data class ClientDnsPathAssessment(
|
||||
val action: DeviceCheckAction?
|
||||
)
|
||||
|
||||
internal data class AndroidPrivateDnsState(
|
||||
val active: Boolean,
|
||||
val serverName: String? = null,
|
||||
) {
|
||||
val strict: Boolean
|
||||
get() = active && !serverName.isNullOrBlank()
|
||||
|
||||
val display: String
|
||||
get() = if (!active) {
|
||||
"выключен"
|
||||
} else {
|
||||
serverName?.takeIf(String::isNotBlank)?.let { "включён ($it)" } ?: "включён"
|
||||
}
|
||||
}
|
||||
|
||||
private const val NETWORK_PROBE_TIMEOUT_MS = 4_500L
|
||||
private const val SOCKET_TIMEOUT_MS = 3_500
|
||||
private val directExecutor = Executor { command -> command.run() }
|
||||
@@ -263,6 +278,14 @@ private suspend fun collectClientNetworkDiagnostics(
|
||||
.filter { it.success }
|
||||
.mapTo(linkedSetOf()) { it.label }
|
||||
val clientDnsAssessment = assessClientDnsPath(successfulClientDnsRoutes, systemPrimaryApiWorks)
|
||||
val privateDnsState = androidPrivateDnsState(diagnosticNetwork.linkProperties)
|
||||
val primaryDnsHasProblem = primaryDnsOk < primaryDnsResults.size
|
||||
val primaryHttpsHasProblem = primaryHttpsOk < primaryHttpsResults.size
|
||||
val privateDnsProblemItem = buildPrivateDnsProblemItem(
|
||||
state = privateDnsState,
|
||||
dnsProblem = primaryDnsHasProblem || clientDnsAssessment.severity == DeviceCheckSeverity.Error,
|
||||
httpsProblem = primaryHttpsHasProblem,
|
||||
)
|
||||
|
||||
val dnsItem = DeviceCheckItem(
|
||||
title = "DNS основного VKCalls на телефоне",
|
||||
@@ -270,10 +293,12 @@ private suspend fun collectClientNetworkDiagnostics(
|
||||
details = primaryDnsResults.joinToString(". ") { it.display() } + ". " +
|
||||
"Резервные legacy- и совместимые узлы: " +
|
||||
reserveDnsResults.joinToString(". ") { it.display() } + ".",
|
||||
recommendation = if (primaryDnsOk == primaryDnsResults.size) "" else
|
||||
"Быстрый VKCalls может быть недоступен. Проверьте системный или Private DNS и сеть оператора; приложение также попробует legacy-резерв.",
|
||||
severity = if (primaryDnsOk == primaryDnsResults.size) DeviceCheckSeverity.Ok else DeviceCheckSeverity.Warning,
|
||||
action = if (primaryDnsOk == primaryDnsResults.size) null else DeviceCheckAction.NetworkSettings
|
||||
recommendation = if (!primaryDnsHasProblem) "" else
|
||||
"Быстрый VKCalls может быть недоступен. Проверьте системный DNS, сеть оператора" +
|
||||
privateDnsRecommendationTail(privateDnsState) +
|
||||
"; приложение также попробует legacy-резерв.",
|
||||
severity = if (primaryDnsHasProblem) DeviceCheckSeverity.Warning else DeviceCheckSeverity.Ok,
|
||||
action = if (primaryDnsHasProblem) DeviceCheckAction.NetworkSettings else null
|
||||
)
|
||||
|
||||
val clientDnsItem = DeviceCheckItem(
|
||||
@@ -303,12 +328,14 @@ private suspend fun collectClientNetworkDiagnostics(
|
||||
ClientNetworkDiagnosticsReport(
|
||||
summaryLines = listOf(
|
||||
"Физическая сеть диагностики: ${networkPathSummary(diagnosticNetwork)}",
|
||||
"Android Private DNS: ${privateDnsState.display}",
|
||||
"DNS основного VKCalls: $primaryDnsOk/${primaryDnsResults.size}",
|
||||
"DNS клиента: ${clientDnsAssessment.status}; UDP $clientUdpOk/${clientUdp.size}, TCP $clientTcpOk/${clientTcp.size}",
|
||||
"HTTPS основного VKCalls: $primaryHttpsOk/${primaryHttpsResults.size}"
|
||||
),
|
||||
items = buildList {
|
||||
add(networkItem)
|
||||
privateDnsProblemItem?.let(::add)
|
||||
add(dnsItem)
|
||||
add(clientDnsItem)
|
||||
add(httpsItem)
|
||||
@@ -356,6 +383,45 @@ internal fun assessClientDnsPath(
|
||||
}
|
||||
}
|
||||
|
||||
internal fun androidPrivateDnsState(properties: LinkProperties?): AndroidPrivateDnsState =
|
||||
AndroidPrivateDnsState(
|
||||
active = properties?.isPrivateDnsActive == true,
|
||||
serverName = properties?.privateDnsServerName?.takeIf(String::isNotBlank),
|
||||
)
|
||||
|
||||
internal fun privateDnsRecommendationTail(state: AndroidPrivateDnsState): String =
|
||||
if (state.active) {
|
||||
", а также Android Private DNS"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
|
||||
internal fun buildPrivateDnsProblemItem(
|
||||
state: AndroidPrivateDnsState,
|
||||
dnsProblem: Boolean,
|
||||
httpsProblem: Boolean,
|
||||
): DeviceCheckItem? {
|
||||
if (!state.active || (!dnsProblem && !httpsProblem)) return null
|
||||
val problemText = when {
|
||||
dnsProblem && httpsProblem -> "DNS/HTTPS-проверки до VKCalls нестабильны"
|
||||
dnsProblem -> "DNS-проверки до VKCalls нестабильны"
|
||||
else -> "HTTPS-проверки до VKCalls нестабильны"
|
||||
}
|
||||
val modeText = if (state.strict) {
|
||||
"строгий режим с сервером ${state.serverName}"
|
||||
} else {
|
||||
"автоматический режим"
|
||||
}
|
||||
return DeviceCheckItem(
|
||||
title = "Android Private DNS",
|
||||
status = state.display,
|
||||
details = "На активной физической сети включён Private DNS ($modeText). $problemText. Private DNS может быть не причиной, но при блокировке или сбоях DoT он влияет на системный DNS Android.",
|
||||
recommendation = "Если подключение WDTT Plus или VKCalls нестабильно, откройте настройки сети Android и временно переключите «Частный DNS» в режим «Авто» или «Выкл», затем повторите диагностику.",
|
||||
severity = DeviceCheckSeverity.Warning,
|
||||
action = DeviceCheckAction.NetworkSettings,
|
||||
)
|
||||
}
|
||||
|
||||
private fun selectDiagnosticNetwork(context: Context, connectivityManager: ConnectivityManager): DiagnosticNetwork? {
|
||||
val activeNetwork = runCatching { connectivityManager.activeNetwork }.getOrNull()
|
||||
val activeCapabilities = activeNetwork?.let {
|
||||
|
||||
@@ -8,7 +8,6 @@ import android.content.pm.PackageManager
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.NetworkCapabilities
|
||||
import android.net.Uri
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.os.StatFs
|
||||
@@ -456,6 +455,7 @@ object DeviceCompatibility {
|
||||
workersPerHash: Int? = null
|
||||
): DeviceCompatibilityReport {
|
||||
val appContext = context.applicationContext
|
||||
val television = isTelevisionDevice(appContext)
|
||||
val items = buildList {
|
||||
add(androidVersionItem())
|
||||
add(abiItem())
|
||||
@@ -468,10 +468,10 @@ object DeviceCompatibility {
|
||||
|
||||
if (includeRuntimeChecks) {
|
||||
add(networkItem(appContext))
|
||||
add(vpnPermissionItem(appContext))
|
||||
add(vpnPermissionItem())
|
||||
add(tunnelStateItem())
|
||||
add(notificationPermissionItem(appContext))
|
||||
add(batteryItem(appContext))
|
||||
add(notificationPermissionItem(appContext, television))
|
||||
add(batteryItem(appContext, television))
|
||||
add(updateInstallPermissionItem(appContext))
|
||||
}
|
||||
}
|
||||
@@ -799,26 +799,14 @@ object DeviceCompatibility {
|
||||
}
|
||||
}
|
||||
|
||||
private fun vpnPermissionItem(context: Context): DeviceCheckItem {
|
||||
val granted = runCatching { VpnService.prepare(context) == null }.getOrDefault(false)
|
||||
return if (granted) {
|
||||
DeviceCheckItem(
|
||||
title = "VPN-разрешение",
|
||||
status = "выдано",
|
||||
details = "WDTT Plus уже может поднимать системный VPN-интерфейс.",
|
||||
severity = DeviceCheckSeverity.Ok,
|
||||
action = DeviceCheckAction.VpnSettings
|
||||
)
|
||||
} else {
|
||||
DeviceCheckItem(
|
||||
title = "VPN-разрешение",
|
||||
status = "будет запрошено при подключении",
|
||||
details = "Отсутствие VPN-разрешения сейчас не является ошибкой. Оно понадобится только при первом запуске туннеля.",
|
||||
recommendation = "Если подключение не стартует после нажатия «Подключить», подтвердите системный запрос VPN.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
action = DeviceCheckAction.VpnSettings
|
||||
)
|
||||
}
|
||||
private fun vpnPermissionItem(): DeviceCheckItem {
|
||||
return DeviceCheckItem(
|
||||
title = "VPN-разрешение",
|
||||
status = "проверяется только при подключении",
|
||||
details = "Диагностика не запрашивает и не меняет владельца системного VPN. При нажатии «Подключить» Android сам покажет запрос, если он нужен.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
action = DeviceCheckAction.VpnSettings
|
||||
)
|
||||
}
|
||||
|
||||
private fun tunnelStateItem(): DeviceCheckItem {
|
||||
@@ -850,7 +838,18 @@ object DeviceCompatibility {
|
||||
}
|
||||
}
|
||||
|
||||
private fun notificationPermissionItem(context: Context): DeviceCheckItem {
|
||||
private fun notificationPermissionItem(
|
||||
context: Context,
|
||||
television: Boolean,
|
||||
): DeviceCheckItem {
|
||||
if (television) {
|
||||
return DeviceCheckItem(
|
||||
title = "Уведомления",
|
||||
status = "телефонный запрос не требуется на TV",
|
||||
details = "WDTT Plus не показывает стартовый запрос уведомлений на Android TV. Системная foreground-служба VPN продолжает работать без этого диалога.",
|
||||
severity = DeviceCheckSeverity.Ok,
|
||||
)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
||||
return DeviceCheckItem(
|
||||
title = "Уведомления",
|
||||
@@ -881,7 +880,18 @@ object DeviceCompatibility {
|
||||
}
|
||||
}
|
||||
|
||||
private fun batteryItem(context: Context): DeviceCheckItem {
|
||||
private fun batteryItem(
|
||||
context: Context,
|
||||
television: Boolean,
|
||||
): DeviceCheckItem {
|
||||
if (television) {
|
||||
return DeviceCheckItem(
|
||||
title = "Фоновая работа",
|
||||
status = "управляется Android TV",
|
||||
details = "На TV приложение не открывает телефонный запрос исключения из оптимизации батареи при первом запуске. VPN работает как foreground-служба; состояние можно диагностировать отдельно при реальной проблеме со сном устройства.",
|
||||
severity = DeviceCheckSeverity.Info,
|
||||
)
|
||||
}
|
||||
val powerManager = runCatching { context.getSystemService(PowerManager::class.java) }.getOrNull()
|
||||
val ignored = runCatching {
|
||||
powerManager?.isIgnoringBatteryOptimizations(context.packageName)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
|
||||
internal fun isTelevisionUiMode(uiMode: Int): Boolean =
|
||||
uiMode and Configuration.UI_MODE_TYPE_MASK == Configuration.UI_MODE_TYPE_TELEVISION
|
||||
|
||||
internal fun shouldUseTelevisionControls(
|
||||
uiMode: Int,
|
||||
hasLeanbackFeature: Boolean,
|
||||
): Boolean = isTelevisionUiMode(uiMode) || hasLeanbackFeature
|
||||
|
||||
internal fun isTelevisionDevice(context: Context): Boolean =
|
||||
shouldUseTelevisionControls(
|
||||
uiMode = context.resources.configuration.uiMode,
|
||||
hasLeanbackFeature =
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK) ||
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK_ONLY),
|
||||
)
|
||||
|
||||
internal fun shouldShowPhonePermissionOnboarding(television: Boolean): Boolean = !television
|
||||
@@ -34,10 +34,14 @@ import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.layout.ExperimentalLayoutApi
|
||||
import androidx.compose.foundation.layout.FlowRow
|
||||
import androidx.compose.foundation.shape.GenericShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import kotlinx.coroutines.launch
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.BatterySaver
|
||||
@@ -57,7 +61,11 @@ import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.ExperimentalComposeUiApi
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
@@ -72,9 +80,13 @@ import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.zIndex
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
@@ -95,6 +107,10 @@ import com.wdtt.plus.ui.ExceptionsTab
|
||||
import com.wdtt.plus.ui.InfoTab
|
||||
import com.wdtt.plus.ui.AdminImportDialog
|
||||
import com.wdtt.plus.ui.TransferCenterDialog
|
||||
import com.wdtt.plus.ui.isTelevisionDevice
|
||||
import com.wdtt.plus.ui.remoteFocusOutline
|
||||
import com.wdtt.plus.ui.remoteHelpFocus
|
||||
import com.wdtt.plus.ui.televisionDialogWidth
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
@@ -1075,8 +1091,13 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
@Composable
|
||||
private fun RoleSelectionScreen(
|
||||
television: Boolean,
|
||||
onRoleSelected: (String) -> Unit
|
||||
) {
|
||||
val initialFocusRequester = remember { FocusRequester() }
|
||||
LaunchedEffect(television) {
|
||||
if (television) initialFocusRequester.requestFocus()
|
||||
}
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
AppBackdrop(modifier = Modifier.matchParentSize())
|
||||
Column(
|
||||
@@ -1117,7 +1138,8 @@ private fun RoleSelectionScreen(
|
||||
title = "Я - юзер",
|
||||
body = "Хочу подключаться бесплатно по ссылке WDTT или вручную, управлять VPN, исключениями и смотреть логи.",
|
||||
icon = Icons.Filled.VpnKey,
|
||||
onClick = { onRoleSelected("user") }
|
||||
onClick = { onRoleSelected("user") },
|
||||
modifier = Modifier.focusRequester(initialFocusRequester),
|
||||
)
|
||||
RoleChoiceButton(
|
||||
title = "Я - админ",
|
||||
@@ -1136,14 +1158,17 @@ private fun RoleChoiceButton(
|
||||
title: String,
|
||||
body: String,
|
||||
icon: ImageVector,
|
||||
onClick: () -> Unit
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
shape = RoundedCornerShape(18.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f)),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.remoteFocusOutline(RoundedCornerShape(18.dp))
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(14.dp),
|
||||
@@ -1408,6 +1433,7 @@ private fun MainScreen(
|
||||
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
|
||||
val view = LocalView.current
|
||||
val context = LocalContext.current
|
||||
val television = isTelevisionDevice()
|
||||
val density = LocalDensity.current
|
||||
val focusManager = LocalFocusManager.current
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
@@ -1557,6 +1583,7 @@ private fun MainScreen(
|
||||
|
||||
if (interfaceRole.isBlank()) {
|
||||
RoleSelectionScreen(
|
||||
television = television,
|
||||
onRoleSelected = { role ->
|
||||
scope.launch { settingsStore.saveInterfaceRole(role) }
|
||||
}
|
||||
@@ -1573,7 +1600,13 @@ private fun MainScreen(
|
||||
return
|
||||
}
|
||||
|
||||
if (!permissionOnboardingComplete) {
|
||||
LaunchedEffect(permissionOnboardingComplete, television) {
|
||||
if (!permissionOnboardingComplete && !shouldShowPhonePermissionOnboarding(television)) {
|
||||
settingsStore.savePermissionOnboardingComplete(true)
|
||||
}
|
||||
}
|
||||
|
||||
if (!permissionOnboardingComplete && shouldShowPhonePermissionOnboarding(television)) {
|
||||
PermissionOnboardingScreen(
|
||||
onComplete = {
|
||||
scope.launch { settingsStore.savePermissionOnboardingComplete(true) }
|
||||
@@ -2163,16 +2196,12 @@ private fun MainScreen(
|
||||
if (incomingProfileName.isNotBlank()) {
|
||||
Text("Название из подключения: «$incomingProfileName».")
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
repeat(3) { profile ->
|
||||
FilterChip(
|
||||
selected = plan.targetProfile == profile,
|
||||
enabled = profile !in plan.blockedProfiles,
|
||||
onClick = { onSelectWdttDeepLinkOverwriteProfile(profile) },
|
||||
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
||||
)
|
||||
}
|
||||
}
|
||||
ProfileReplacementChips(
|
||||
selectedProfile = plan.targetProfile,
|
||||
blockedProfiles = plan.blockedProfiles,
|
||||
profileNames = profileNames,
|
||||
onSelect = onSelectWdttDeepLinkOverwriteProfile,
|
||||
)
|
||||
if (plan.blockedProfiles.size == 3) {
|
||||
Text("Все профили защищены действующим удалённым доступом. Сначала освободите один из них.")
|
||||
} else {
|
||||
@@ -2197,6 +2226,37 @@ private fun MainScreen(
|
||||
}
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalLayoutApi::class)
|
||||
@Composable
|
||||
private fun ProfileReplacementChips(
|
||||
selectedProfile: Int,
|
||||
blockedProfiles: Set<Int>,
|
||||
profileNames: List<String>,
|
||||
onSelect: (Int) -> Unit,
|
||||
) {
|
||||
FlowRow(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
repeat(3) { profile ->
|
||||
FilterChip(
|
||||
selected = selectedProfile == profile,
|
||||
enabled = profile !in blockedProfiles,
|
||||
onClick = { onSelect(profile) },
|
||||
modifier = Modifier.widthIn(min = 108.dp, max = 220.dp),
|
||||
label = {
|
||||
Text(
|
||||
text = vpnProfileDisplayName(profile, profileNames),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WdttConnectActivationDialog(
|
||||
flow: WdttConnectFlow,
|
||||
@@ -2214,6 +2274,7 @@ private fun WdttConnectActivationDialog(
|
||||
onOpenFailureAction: (RemoteLaunchTarget) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
var manualHashes by rememberSaveable { mutableStateOf("") }
|
||||
var selectedHashMethod by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var helpMethod by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
@@ -2228,6 +2289,7 @@ private fun WdttConnectActivationDialog(
|
||||
canDismiss -> onDismiss()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.televisionDialogWidth(television),
|
||||
title = { Text("Подключение WDTT Plus") },
|
||||
text = {
|
||||
AnimatedContent(
|
||||
@@ -2301,16 +2363,12 @@ private fun WdttConnectActivationDialog(
|
||||
if (incomingName.isNotBlank()) {
|
||||
Text("Новый доступ: «$incomingName».")
|
||||
}
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
repeat(3) { profile ->
|
||||
FilterChip(
|
||||
selected = state.plan.targetProfile == profile,
|
||||
enabled = profile !in state.plan.blockedProfiles,
|
||||
onClick = { onSelectProfile(profile) },
|
||||
label = { Text(vpnProfileDisplayName(profile, profileNames)) }
|
||||
)
|
||||
}
|
||||
}
|
||||
ProfileReplacementChips(
|
||||
selectedProfile = state.plan.targetProfile,
|
||||
blockedProfiles = state.plan.blockedProfiles,
|
||||
profileNames = profileNames,
|
||||
onSelect = onSelectProfile,
|
||||
)
|
||||
Text(
|
||||
if (state.plan.blockedProfiles.size == 3) {
|
||||
"Все профили защищены действующим готовым доступом. " +
|
||||
@@ -2488,12 +2546,14 @@ private fun WdttConnectActivationDialog(
|
||||
}
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
},
|
||||
properties = DialogProperties(usePlatformDefaultWidth = !television),
|
||||
)
|
||||
|
||||
helpMethod?.let { method ->
|
||||
AlertDialog(
|
||||
onDismissRequest = { helpMethod = null },
|
||||
modifier = Modifier.televisionDialogWidth(television),
|
||||
title = {
|
||||
Text(
|
||||
when (method) {
|
||||
@@ -2525,7 +2585,8 @@ private fun WdttConnectActivationDialog(
|
||||
},
|
||||
confirmButton = {
|
||||
TextButton(onClick = { helpMethod = null }) { Text("Понятно") }
|
||||
}
|
||||
},
|
||||
properties = DialogProperties(usePlatformDefaultWidth = !television),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2555,21 +2616,29 @@ private fun HashMethodRow(
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
shape = RoundedCornerShape(10.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceVariant,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
|
||||
modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f)) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.remoteFocusOutline(RoundedCornerShape(8.dp))
|
||||
.clickable(onClick = onClick)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp)
|
||||
) {
|
||||
Text(title, fontWeight = FontWeight.SemiBold)
|
||||
Text(body, style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
IconButton(onClick = onHelp) {
|
||||
IconButton(
|
||||
onClick = onHelp,
|
||||
modifier = Modifier.remoteHelpFocus(),
|
||||
) {
|
||||
Icon(Icons.Filled.Info, contentDescription = "Как это работает")
|
||||
}
|
||||
}
|
||||
@@ -2611,6 +2680,7 @@ private fun SharedVkHashDialog(
|
||||
)
|
||||
}
|
||||
|
||||
@OptIn(ExperimentalComposeUiApi::class)
|
||||
@Composable
|
||||
private fun ProxyNavigationBar(
|
||||
navItems: List<NavItem>,
|
||||
@@ -2622,6 +2692,8 @@ private fun ProxyNavigationBar(
|
||||
onTabSelected: (Int) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val isDark = colors.background.luminance() < 0.22f
|
||||
val selectedColor = colors.primary
|
||||
@@ -2646,6 +2718,16 @@ private fun ProxyNavigationBar(
|
||||
}
|
||||
val indicatorIndex = remember { Animatable(selectedVisualIndex.toFloat()) }
|
||||
val dragVisualIndex = indicatorIndex.value
|
||||
val focusRequesters = remember(navItems.map(NavItem::id)) {
|
||||
List(navItems.size) { FocusRequester() }
|
||||
}
|
||||
|
||||
LaunchedEffect(television, navItems.map(NavItem::id)) {
|
||||
if (television && focusRequesters.isNotEmpty()) {
|
||||
inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||
focusRequesters[selectedVisualIndex].requestFocus()
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(selectedVisualIndex) {
|
||||
if (dragTargetIndex !in navItems.indices) {
|
||||
@@ -2702,6 +2784,7 @@ private fun ProxyNavigationBar(
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.focusGroup()
|
||||
.padding(horizontal = trackPadding, vertical = 6.dp)
|
||||
) {
|
||||
navItems.forEachIndexed { index, item ->
|
||||
@@ -2713,7 +2796,18 @@ private fun ProxyNavigationBar(
|
||||
.weight(1f)
|
||||
.fillMaxHeight()
|
||||
.clip(RoundedCornerShape(22.dp))
|
||||
.clickable { onTabSelected(item.id) },
|
||||
.focusRequester(focusRequesters[index])
|
||||
.onFocusChanged { state ->
|
||||
if (television && state.isFocused && item.id != selectedTab) {
|
||||
onTabSelected(item.id)
|
||||
}
|
||||
}
|
||||
.remoteFocusOutline(RoundedCornerShape(22.dp))
|
||||
.selectable(
|
||||
selected = item.id == selectedTab,
|
||||
role = Role.Tab,
|
||||
onClick = { onTabSelected(item.id) },
|
||||
),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.util.Base64
|
||||
|
||||
private const val NATIVE_STARTUP_CONFIG_PREFIX = "START_CONFIG|"
|
||||
|
||||
internal data class NativeClientStartupSecrets(
|
||||
val vkHashes: String,
|
||||
val connectionPassword: String = "",
|
||||
val customVkClientId: String = "",
|
||||
val customVkClientSecret: String = "",
|
||||
)
|
||||
|
||||
internal fun nativeClientStartupConfigLine(secrets: NativeClientStartupSecrets): String {
|
||||
val json = JSONObject()
|
||||
.put("vk_hashes", secrets.vkHashes)
|
||||
.put("connection_password", secrets.connectionPassword)
|
||||
.put("custom_vk_client_id", secrets.customVkClientId)
|
||||
.put("custom_vk_client_secret", secrets.customVkClientSecret)
|
||||
.toString()
|
||||
val encoded = Base64.getUrlEncoder()
|
||||
.withoutPadding()
|
||||
.encodeToString(json.toByteArray(Charsets.UTF_8))
|
||||
return NATIVE_STARTUP_CONFIG_PREFIX + encoded
|
||||
}
|
||||
@@ -64,17 +64,22 @@ class QuickToggleTileService : TileService() {
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
runCatching {
|
||||
when (
|
||||
val running = TunnelManager.running.value
|
||||
val trustedWifiWaiting = TrustedWifiManager.state.value.waiting
|
||||
val action = if (running || trustedWifiWaiting) {
|
||||
TunnelToggleAction.STOP
|
||||
} else {
|
||||
tunnelToggleAction(
|
||||
running = TunnelManager.running.value,
|
||||
trustedWifiWaiting = TrustedWifiManager.state.value.waiting,
|
||||
running = false,
|
||||
trustedWifiWaiting = false,
|
||||
vpnPermissionRequired = VpnService.prepare(this) != null,
|
||||
)
|
||||
) {
|
||||
}
|
||||
when (action) {
|
||||
TunnelToggleAction.STOP -> {
|
||||
// Состояние плитки изменится после фактической остановки службы.
|
||||
startService(
|
||||
Intent(this, TunnelService::class.java).apply { action = "STOP" }
|
||||
Intent(this, TunnelService::class.java).apply { this.action = "STOP" }
|
||||
)
|
||||
}
|
||||
TunnelToggleAction.REQUEST_VPN_PERMISSION -> {
|
||||
|
||||
@@ -0,0 +1,510 @@
|
||||
/*
|
||||
* Based on WireGuard Android GoBackend (Copyright 2017-2025 WireGuard LLC).
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
package com.wdtt.plus;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Build;
|
||||
import android.os.ParcelFileDescriptor;
|
||||
import android.system.OsConstants;
|
||||
import android.util.Log;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.collection.ArraySet;
|
||||
|
||||
import com.wireguard.android.backend.Backend;
|
||||
import com.wireguard.android.backend.BackendException;
|
||||
import com.wireguard.android.backend.GoBackend;
|
||||
import com.wireguard.android.backend.Statistics;
|
||||
import com.wireguard.android.backend.Tunnel;
|
||||
import com.wireguard.android.util.SharedLibraryLoader;
|
||||
import com.wireguard.config.Config;
|
||||
import com.wireguard.config.InetEndpoint;
|
||||
import com.wireguard.config.InetNetwork;
|
||||
import com.wireguard.config.Peer;
|
||||
import com.wireguard.crypto.Key;
|
||||
import com.wireguard.crypto.KeyFormatException;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.net.InetAddress;
|
||||
import java.util.Collections;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
/**
|
||||
* WireGuard Go backend with non-intrusive automatic restore semantics.
|
||||
*
|
||||
* <p>It is derived from the exact GoBackend bundled by tunnel 1.0.20260102.
|
||||
* The only intentional behavioural differences are that an UP never invokes
|
||||
* {@link android.net.VpnService#prepare(Context)} and that {@link VpnService}
|
||||
* reports {@link VpnService#onRevoke()} to the owner. Android's establish()
|
||||
* atomically returns {@code null} when this app is no longer prepared, so an
|
||||
* automatic resume cannot take the VPN slot from another application.</p>
|
||||
*/
|
||||
public final class SafeGoBackend implements Backend {
|
||||
private static final int DNS_RESOLUTION_RETRIES = 10;
|
||||
private static final String TAG = "WDTT/SafeGoBackend";
|
||||
private static CompletableFuture<VpnService> vpnService = new CompletableFuture<>();
|
||||
|
||||
private final Context context;
|
||||
@Nullable private Config currentConfig;
|
||||
@Nullable private Tunnel currentTunnel;
|
||||
private int currentTunnelHandle = -1;
|
||||
@Nullable private Runnable revocationListener;
|
||||
|
||||
public SafeGoBackend(final Context context) {
|
||||
SharedLibraryLoader.loadSharedLibrary(context, "wg-go");
|
||||
this.context = context.getApplicationContext();
|
||||
}
|
||||
|
||||
public void setRevocationListener(@Nullable final Runnable listener) {
|
||||
revocationListener = listener;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getRunningTunnelNames() {
|
||||
if (currentTunnel == null) return Collections.emptySet();
|
||||
final Set<String> tunnels = new ArraySet<>();
|
||||
tunnels.add(currentTunnel.getName());
|
||||
return tunnels;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Tunnel.State getState(final Tunnel tunnel) {
|
||||
return currentTunnel == tunnel ? Tunnel.State.UP : Tunnel.State.DOWN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statistics getStatistics(final Tunnel tunnel) throws Exception {
|
||||
final Statistics stats = StatisticsBridge.create();
|
||||
if (tunnel != currentTunnel || currentTunnelHandle == -1) return stats;
|
||||
final String config = NativeBridge.getConfig(currentTunnelHandle);
|
||||
if (config == null) return stats;
|
||||
|
||||
Key key = null;
|
||||
long rx = 0;
|
||||
long tx = 0;
|
||||
long latestHandshakeMs = 0;
|
||||
for (final String line : config.split("\\n")) {
|
||||
if (line.startsWith("public_key=")) {
|
||||
if (key != null) StatisticsBridge.add(stats, key, rx, tx, latestHandshakeMs);
|
||||
key = null;
|
||||
rx = 0;
|
||||
tx = 0;
|
||||
latestHandshakeMs = 0;
|
||||
try {
|
||||
key = Key.fromHex(line.substring(11));
|
||||
} catch (final KeyFormatException ignored) {
|
||||
// Keep parsing: a malformed peer must not hide other peers.
|
||||
}
|
||||
} else if (key != null && line.startsWith("rx_bytes=")) {
|
||||
try {
|
||||
rx = Long.parseLong(line.substring(9));
|
||||
} catch (final NumberFormatException ignored) {
|
||||
rx = 0;
|
||||
}
|
||||
} else if (key != null && line.startsWith("tx_bytes=")) {
|
||||
try {
|
||||
tx = Long.parseLong(line.substring(9));
|
||||
} catch (final NumberFormatException ignored) {
|
||||
tx = 0;
|
||||
}
|
||||
} else if (key != null && line.startsWith("last_handshake_time_sec=")) {
|
||||
try {
|
||||
latestHandshakeMs += Long.parseLong(line.substring(24)) * 1000;
|
||||
} catch (final NumberFormatException ignored) {
|
||||
latestHandshakeMs = 0;
|
||||
}
|
||||
} else if (key != null && line.startsWith("last_handshake_time_nsec=")) {
|
||||
try {
|
||||
latestHandshakeMs += Long.parseLong(line.substring(25)) / 1_000_000;
|
||||
} catch (final NumberFormatException ignored) {
|
||||
latestHandshakeMs = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (key != null) StatisticsBridge.add(stats, key, rx, tx, latestHandshakeMs);
|
||||
return stats;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVersion() throws Exception {
|
||||
return NativeBridge.version();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAlwaysOn() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return false;
|
||||
return vpnService.get(0, TimeUnit.NANOSECONDS).isAlwaysOn();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLockdownEnabled() throws ExecutionException, InterruptedException, TimeoutException {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return false;
|
||||
return vpnService.get(0, TimeUnit.NANOSECONDS).isLockdownEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Tunnel.State setState(
|
||||
final Tunnel tunnel,
|
||||
Tunnel.State state,
|
||||
@Nullable final Config config
|
||||
) throws Exception {
|
||||
final Tunnel.State originalState = getState(tunnel);
|
||||
if (state == Tunnel.State.TOGGLE) {
|
||||
state = originalState == Tunnel.State.UP ? Tunnel.State.DOWN : Tunnel.State.UP;
|
||||
}
|
||||
if (state == originalState && tunnel == currentTunnel && config == currentConfig) {
|
||||
return originalState;
|
||||
}
|
||||
|
||||
if (state == Tunnel.State.UP) {
|
||||
final Config originalConfig = currentConfig;
|
||||
final Tunnel originalTunnel = currentTunnel;
|
||||
if (currentTunnel != null) setStateInternal(currentTunnel, null, Tunnel.State.DOWN);
|
||||
try {
|
||||
setStateInternal(tunnel, config, Tunnel.State.UP);
|
||||
} catch (final Exception error) {
|
||||
if (originalTunnel != null) {
|
||||
try {
|
||||
setStateInternal(originalTunnel, originalConfig, Tunnel.State.UP);
|
||||
} catch (final Exception restoreError) {
|
||||
error.addSuppressed(restoreError);
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
} else if (state == Tunnel.State.DOWN && tunnel == currentTunnel) {
|
||||
setStateInternal(tunnel, null, Tunnel.State.DOWN);
|
||||
}
|
||||
return getState(tunnel);
|
||||
}
|
||||
|
||||
private void setStateInternal(
|
||||
final Tunnel tunnel,
|
||||
@Nullable final Config config,
|
||||
final Tunnel.State state
|
||||
) throws Exception {
|
||||
Log.i(TAG, "Bringing tunnel " + tunnel.getName() + ' ' + state);
|
||||
if (state == Tunnel.State.UP) {
|
||||
if (config == null) throw new BackendException(BackendException.Reason.TUNNEL_MISSING_CONFIG);
|
||||
|
||||
final VpnService service = requireVpnService();
|
||||
service.setOwner(this);
|
||||
if (currentTunnelHandle != -1) {
|
||||
Log.w(TAG, "Tunnel already up");
|
||||
return;
|
||||
}
|
||||
|
||||
resolveEndpoints(config);
|
||||
final String goConfig = config.toWgUserspaceString();
|
||||
final android.net.VpnService.Builder builder = service.getBuilder();
|
||||
builder.setSession(tunnel.getName());
|
||||
for (final String app : config.getInterface().getExcludedApplications()) {
|
||||
builder.addDisallowedApplication(app);
|
||||
}
|
||||
for (final String app : config.getInterface().getIncludedApplications()) {
|
||||
builder.addAllowedApplication(app);
|
||||
}
|
||||
for (final InetNetwork address : config.getInterface().getAddresses()) {
|
||||
builder.addAddress(address.getAddress(), address.getMask());
|
||||
}
|
||||
for (final InetAddress dnsServer : config.getInterface().getDnsServers()) {
|
||||
builder.addDnsServer(dnsServer.getHostAddress());
|
||||
}
|
||||
for (final String domain : config.getInterface().getDnsSearchDomains()) {
|
||||
builder.addSearchDomain(domain);
|
||||
}
|
||||
boolean sawDefaultRoute = false;
|
||||
for (final Peer peer : config.getPeers()) {
|
||||
for (final InetNetwork allowedIp : peer.getAllowedIps()) {
|
||||
if (allowedIp.getMask() == 0) sawDefaultRoute = true;
|
||||
builder.addRoute(allowedIp.getAddress(), allowedIp.getMask());
|
||||
}
|
||||
}
|
||||
if (!(sawDefaultRoute && config.getPeers().size() == 1)) {
|
||||
builder.allowFamily(OsConstants.AF_INET);
|
||||
builder.allowFamily(OsConstants.AF_INET6);
|
||||
}
|
||||
builder.setMtu(config.getInterface().getMtu().orElse(1280));
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) builder.setMetered(false);
|
||||
service.setUnderlyingNetworks(null);
|
||||
builder.setBlocking(true);
|
||||
|
||||
try (ParcelFileDescriptor tun = builder.establish()) {
|
||||
if (tun == null) {
|
||||
service.stopSelf();
|
||||
throw new VpnSlotUnavailableException();
|
||||
}
|
||||
currentTunnelHandle = NativeBridge.turnOn(tunnel.getName(), tun.detachFd(), goConfig);
|
||||
}
|
||||
if (currentTunnelHandle < 0) {
|
||||
throw new BackendException(
|
||||
BackendException.Reason.GO_ACTIVATION_ERROR_CODE,
|
||||
currentTunnelHandle
|
||||
);
|
||||
}
|
||||
currentTunnel = tunnel;
|
||||
currentConfig = config;
|
||||
service.protect(NativeBridge.getSocketV4(currentTunnelHandle));
|
||||
service.protect(NativeBridge.getSocketV6(currentTunnelHandle));
|
||||
} else {
|
||||
if (currentTunnelHandle == -1) {
|
||||
Log.w(TAG, "Tunnel already down");
|
||||
return;
|
||||
}
|
||||
final int handleToClose = currentTunnelHandle;
|
||||
currentTunnel = null;
|
||||
currentTunnelHandle = -1;
|
||||
currentConfig = null;
|
||||
NativeBridge.turnOff(handleToClose);
|
||||
try {
|
||||
vpnService.get(0, TimeUnit.NANOSECONDS).stopSelf();
|
||||
} catch (final TimeoutException ignored) {
|
||||
// Service may already be stopping after an external revoke.
|
||||
}
|
||||
}
|
||||
tunnel.onStateChange(state);
|
||||
}
|
||||
|
||||
private VpnService requireVpnService() throws BackendException {
|
||||
if (!vpnService.isDone()) {
|
||||
Log.d(TAG, "Requesting to start VpnService");
|
||||
context.startService(new Intent(context, VpnService.class));
|
||||
}
|
||||
try {
|
||||
return vpnService.get(2, TimeUnit.SECONDS);
|
||||
} catch (final TimeoutException error) {
|
||||
final BackendException result = new BackendException(
|
||||
BackendException.Reason.UNABLE_TO_START_VPN
|
||||
);
|
||||
result.initCause(error);
|
||||
throw result;
|
||||
} catch (final InterruptedException error) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new BackendException(BackendException.Reason.UNABLE_TO_START_VPN);
|
||||
} catch (final ExecutionException error) {
|
||||
final BackendException result = new BackendException(
|
||||
BackendException.Reason.UNABLE_TO_START_VPN
|
||||
);
|
||||
result.initCause(error);
|
||||
throw result;
|
||||
}
|
||||
}
|
||||
|
||||
private static void resolveEndpoints(final Config config) throws Exception {
|
||||
dnsRetry:
|
||||
for (int attempt = 0; attempt < DNS_RESOLUTION_RETRIES; ++attempt) {
|
||||
for (final Peer peer : config.getPeers()) {
|
||||
final InetEndpoint endpoint = peer.getEndpoint().orElse(null);
|
||||
if (endpoint == null || endpoint.getResolved().orElse(null) != null) continue;
|
||||
if (attempt == DNS_RESOLUTION_RETRIES - 1) {
|
||||
throw new BackendException(
|
||||
BackendException.Reason.DNS_RESOLUTION_FAILURE,
|
||||
endpoint.getHost()
|
||||
);
|
||||
}
|
||||
Log.w(TAG, "DNS host \"" + endpoint.getHost() + "\" failed to resolve; trying again");
|
||||
Thread.sleep(1000);
|
||||
continue dnsRetry;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void handleServiceDestroyed() {
|
||||
final Tunnel tunnel = currentTunnel;
|
||||
if (tunnel == null) return;
|
||||
final int handleToClose = currentTunnelHandle;
|
||||
currentTunnel = null;
|
||||
currentTunnelHandle = -1;
|
||||
currentConfig = null;
|
||||
if (handleToClose != -1) {
|
||||
try {
|
||||
NativeBridge.turnOff(handleToClose);
|
||||
} catch (final Exception error) {
|
||||
Log.w(TAG, "Unable to stop wg-go after VpnService destruction", error);
|
||||
}
|
||||
}
|
||||
tunnel.onStateChange(Tunnel.State.DOWN);
|
||||
}
|
||||
|
||||
private void notifySystemRevoked() {
|
||||
final Runnable listener = revocationListener;
|
||||
if (listener != null && currentTunnel != null) listener.run();
|
||||
}
|
||||
|
||||
private static synchronized void resetVpnServiceFuture() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
vpnService = vpnService.newIncompleteFuture();
|
||||
} else {
|
||||
vpnService = new CompletableFuture<>();
|
||||
}
|
||||
}
|
||||
|
||||
/** Raised when Android atomically refuses an automatic establish attempt. */
|
||||
public static final class VpnSlotUnavailableException extends Exception {
|
||||
public VpnSlotUnavailableException() {
|
||||
super("Android VPN slot is not available to WDTT Plus");
|
||||
}
|
||||
}
|
||||
|
||||
/** Android service paired with this backend. */
|
||||
public static class VpnService extends android.net.VpnService {
|
||||
@Nullable private SafeGoBackend owner;
|
||||
|
||||
public android.net.VpnService.Builder getBuilder() {
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
vpnService.complete(this);
|
||||
super.onCreate();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onRevoke() {
|
||||
final SafeGoBackend currentOwner = owner;
|
||||
if (currentOwner != null) currentOwner.notifySystemRevoked();
|
||||
super.onRevoke();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
final SafeGoBackend currentOwner = owner;
|
||||
if (currentOwner != null) currentOwner.handleServiceDestroyed();
|
||||
resetVpnServiceFuture();
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
public void setOwner(final SafeGoBackend owner) {
|
||||
this.owner = owner;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The dependency's JNI exports are named for GoBackend. Keeping this small
|
||||
* bridge lets this class reuse the exact audited native library instead of
|
||||
* shipping a second wg-go binary.
|
||||
*/
|
||||
private static final class NativeBridge {
|
||||
private static final Method GET_CONFIG = method("wgGetConfig", int.class);
|
||||
private static final Method GET_SOCKET_V4 = method("wgGetSocketV4", int.class);
|
||||
private static final Method GET_SOCKET_V6 = method("wgGetSocketV6", int.class);
|
||||
private static final Method TURN_OFF = method("wgTurnOff", int.class);
|
||||
private static final Method TURN_ON = method("wgTurnOn", String.class, int.class, String.class);
|
||||
private static final Method VERSION = method("wgVersion");
|
||||
|
||||
private static Method method(final String name, final Class<?>... parameters) {
|
||||
try {
|
||||
final Method method = GoBackend.class.getDeclaredMethod(name, parameters);
|
||||
method.setAccessible(true);
|
||||
return method;
|
||||
} catch (final ReflectiveOperationException error) {
|
||||
throw new IllegalStateException("WireGuard native bridge is incompatible", error);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable static String getConfig(final int handle) throws Exception {
|
||||
return (String) invoke(GET_CONFIG, handle);
|
||||
}
|
||||
|
||||
static int getSocketV4(final int handle) throws Exception {
|
||||
return (Integer) invoke(GET_SOCKET_V4, handle);
|
||||
}
|
||||
|
||||
static int getSocketV6(final int handle) throws Exception {
|
||||
return (Integer) invoke(GET_SOCKET_V6, handle);
|
||||
}
|
||||
|
||||
static void turnOff(final int handle) throws Exception {
|
||||
invoke(TURN_OFF, handle);
|
||||
}
|
||||
|
||||
static int turnOn(final String name, final int fd, final String settings) throws Exception {
|
||||
return (Integer) invoke(TURN_ON, name, fd, settings);
|
||||
}
|
||||
|
||||
static String version() throws Exception {
|
||||
return (String) invoke(VERSION);
|
||||
}
|
||||
|
||||
private static Object invoke(final Method method, final Object... arguments) throws Exception {
|
||||
try {
|
||||
return method.invoke(null, arguments);
|
||||
} catch (final IllegalAccessException error) {
|
||||
throw new IllegalStateException("WireGuard native bridge is inaccessible", error);
|
||||
} catch (final InvocationTargetException error) {
|
||||
final Throwable cause = error.getCause();
|
||||
if (cause instanceof Exception) throw (Exception) cause;
|
||||
if (cause instanceof Error) throw (Error) cause;
|
||||
throw new IllegalStateException("WireGuard native bridge failed", cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Statistics has package-private construction in the pinned tunnel library. */
|
||||
private static final class StatisticsBridge {
|
||||
private static final Constructor<Statistics> CONSTRUCTOR = constructor();
|
||||
private static final Method ADD = addMethod();
|
||||
|
||||
private static Constructor<Statistics> constructor() {
|
||||
try {
|
||||
final Constructor<Statistics> constructor = Statistics.class.getDeclaredConstructor();
|
||||
constructor.setAccessible(true);
|
||||
return constructor;
|
||||
} catch (final ReflectiveOperationException error) {
|
||||
throw new IllegalStateException("WireGuard statistics bridge is incompatible", error);
|
||||
}
|
||||
}
|
||||
|
||||
private static Method addMethod() {
|
||||
try {
|
||||
final Method method = Statistics.class.getDeclaredMethod(
|
||||
"add", Key.class, long.class, long.class, long.class
|
||||
);
|
||||
method.setAccessible(true);
|
||||
return method;
|
||||
} catch (final ReflectiveOperationException error) {
|
||||
throw new IllegalStateException("WireGuard statistics bridge is incompatible", error);
|
||||
}
|
||||
}
|
||||
|
||||
static Statistics create() throws Exception {
|
||||
try {
|
||||
return CONSTRUCTOR.newInstance();
|
||||
} catch (final InstantiationException | IllegalAccessException error) {
|
||||
throw new IllegalStateException("WireGuard statistics bridge is inaccessible", error);
|
||||
} catch (final InvocationTargetException error) {
|
||||
throw new IllegalStateException("WireGuard statistics bridge failed", error.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
static void add(
|
||||
final Statistics statistics,
|
||||
final Key key,
|
||||
final long rx,
|
||||
final long tx,
|
||||
final long handshake
|
||||
) throws Exception {
|
||||
try {
|
||||
ADD.invoke(statistics, key, rx, tx, handshake);
|
||||
} catch (final IllegalAccessException error) {
|
||||
throw new IllegalStateException("WireGuard statistics bridge is inaccessible", error);
|
||||
} catch (final InvocationTargetException error) {
|
||||
final Throwable cause = error.getCause();
|
||||
if (cause instanceof Exception) throw (Exception) cause;
|
||||
if (cause instanceof Error) throw (Error) cause;
|
||||
throw new IllegalStateException("WireGuard statistics bridge failed", cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@ import com.jcraft.jsch.ChannelExec
|
||||
import com.jcraft.jsch.Session
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.util.Base64
|
||||
|
||||
data class ServerAdminTarget(
|
||||
val host: String,
|
||||
@@ -158,9 +160,65 @@ data class ServerAdminActionResult(
|
||||
val createdClient: ServerClientInfo?
|
||||
)
|
||||
|
||||
data class ServerBackupPolicyInfo(
|
||||
val enabled: Boolean,
|
||||
val intervalHours: Int,
|
||||
val retentionCount: Int
|
||||
)
|
||||
|
||||
data class ServerStoredBackupInfo(
|
||||
val id: String,
|
||||
val createdAt: Long,
|
||||
val reason: String,
|
||||
val serverVersion: String,
|
||||
val passwordCount: Int,
|
||||
val deviceCount: Int,
|
||||
val sizeBytes: Long,
|
||||
val sha256: String,
|
||||
val valid: Boolean,
|
||||
val error: String,
|
||||
val contentMetadataAvailable: Boolean,
|
||||
val hasWireGuardKeys: Boolean,
|
||||
val hasBackupPolicy: Boolean,
|
||||
val outboundProfileMode: String
|
||||
)
|
||||
|
||||
data class ServerBackupManagerInfo(
|
||||
val policy: ServerBackupPolicyInfo,
|
||||
val lastAttemptAt: Long,
|
||||
val lastSuccessAt: Long,
|
||||
val lastBackupId: String,
|
||||
val lastError: String,
|
||||
val nextRunAt: Long,
|
||||
val totalBytes: Long,
|
||||
val validCount: Int,
|
||||
val brokenCount: Int,
|
||||
val backups: List<ServerStoredBackupInfo>
|
||||
)
|
||||
|
||||
data class ServerStoredBackupFile(
|
||||
val path: String,
|
||||
val mode: Int,
|
||||
val size: Long,
|
||||
val sha256: String,
|
||||
val data: ByteArray
|
||||
)
|
||||
|
||||
data class ServerStoredBackupDocument(
|
||||
val id: String,
|
||||
val createdAt: Long,
|
||||
val reason: String,
|
||||
val serverVersion: String,
|
||||
val passwordCount: Int,
|
||||
val deviceCount: Int,
|
||||
val files: List<ServerStoredBackupFile>
|
||||
)
|
||||
|
||||
object ServerAdminClient {
|
||||
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 ->
|
||||
@@ -333,6 +391,81 @@ object ServerAdminClient {
|
||||
suspend fun resetTraffic(target: ServerAdminTarget): ServerAdminActionResult =
|
||||
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)) }
|
||||
}
|
||||
|
||||
suspend fun configureBackups(
|
||||
target: ServerAdminTarget,
|
||||
enabled: Boolean,
|
||||
intervalHours: Int,
|
||||
retentionCount: Int
|
||||
): ServerBackupManagerInfo = withContext(Dispatchers.IO) {
|
||||
require(intervalHours in 6..168) { "Интервал должен быть от 6 до 168 часов" }
|
||||
require(retentionCount in 2..90) { "Количество копий должно быть от 2 до 90" }
|
||||
withSession(target) { ssh ->
|
||||
parseBackupStatus(
|
||||
callAdmin(
|
||||
ssh,
|
||||
target,
|
||||
listOf(
|
||||
"backup-configure",
|
||||
"--enabled", enabled.toString(),
|
||||
"--interval-hours", intervalHours.toString(),
|
||||
"--retention", retentionCount.toString()
|
||||
),
|
||||
BACKUP_TIMEOUT
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun createBackup(
|
||||
target: ServerAdminTarget,
|
||||
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)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun deleteBackup(target: ServerAdminTarget, id: String): ServerBackupManagerInfo = withContext(Dispatchers.IO) {
|
||||
requireBackupId(id)
|
||||
withSession(target) { ssh ->
|
||||
parseBackupStatus(
|
||||
callAdmin(
|
||||
ssh,
|
||||
target,
|
||||
listOf("backup-delete", "--id", id, "--confirm", "УДАЛИТЬ"),
|
||||
BACKUP_TIMEOUT
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun restart(target: ServerAdminTarget): ServerAdminActionResult =
|
||||
withContext(Dispatchers.IO) {
|
||||
withSession(target) { ssh ->
|
||||
@@ -368,18 +501,21 @@ object ServerAdminClient {
|
||||
}
|
||||
}
|
||||
|
||||
private fun callAdmin(ssh: AdminSshClient, target: ServerAdminTarget, args: List<String>): JSONObject {
|
||||
val command = buildString {
|
||||
append("/usr/local/bin/wdtt-server admin")
|
||||
append(" --config-dir /etc/wdtt")
|
||||
append(" --main-password ")
|
||||
append(shellQuote(target.mainPassword))
|
||||
args.forEach {
|
||||
append(' ')
|
||||
append(shellQuote(it))
|
||||
}
|
||||
}
|
||||
val output = ssh.exec(rootCommand(command), ADMIN_TIMEOUT)
|
||||
private fun callAdmin(
|
||||
ssh: AdminSshClient,
|
||||
target: ServerAdminTarget,
|
||||
args: List<String>,
|
||||
timeout: Long = ADMIN_TIMEOUT
|
||||
): JSONObject {
|
||||
val request = JSONObject()
|
||||
.put("main_password", target.mainPassword)
|
||||
.put("args", JSONArray(args))
|
||||
.toString()
|
||||
val output = ssh.execRootWithStdin(
|
||||
command = "/usr/local/bin/wdtt-server admin --config-dir /etc/wdtt --request-stdin",
|
||||
stdinPayload = "$request\n",
|
||||
timeout = timeout
|
||||
)
|
||||
val json = extractJson(output)
|
||||
if (!json.optBoolean("ok", false)) {
|
||||
throw IllegalStateException(friendlyAdminError(json.optString("message", output)))
|
||||
@@ -387,6 +523,125 @@ object ServerAdminClient {
|
||||
return json
|
||||
}
|
||||
|
||||
private fun requireBackupId(id: String) {
|
||||
require(Regex("^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{12}$").matches(id)) {
|
||||
"Некорректный идентификатор резервной копии"
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseBackupStatus(response: JSONObject): ServerBackupManagerInfo {
|
||||
val status = response.optJSONObject("backup_status")
|
||||
?: throw IllegalStateException("сервер не вернул состояние резервного копирования")
|
||||
val policy = status.optJSONObject("policy") ?: JSONObject()
|
||||
val state = status.optJSONObject("state") ?: JSONObject()
|
||||
val backups = buildList {
|
||||
val array = status.optJSONArray("backups") ?: return@buildList
|
||||
for (index in 0 until array.length()) {
|
||||
array.optJSONObject(index)?.let { add(parseBackupInfo(it)) }
|
||||
}
|
||||
}
|
||||
return ServerBackupManagerInfo(
|
||||
policy = ServerBackupPolicyInfo(
|
||||
enabled = policy.optBoolean("enabled", false),
|
||||
intervalHours = policy.optInt("interval_hours", 24).coerceIn(6, 168),
|
||||
retentionCount = policy.optInt("retention_count", 14).coerceIn(2, 90)
|
||||
),
|
||||
lastAttemptAt = state.optLong("last_attempt_at", 0L),
|
||||
lastSuccessAt = state.optLong("last_success_at", 0L),
|
||||
lastBackupId = state.optString("last_backup_id", ""),
|
||||
lastError = state.optString("last_error", "").take(240),
|
||||
nextRunAt = status.optLong("next_run_at", 0L),
|
||||
totalBytes = status.optLong("total_bytes", 0L).coerceAtLeast(0L),
|
||||
validCount = status.optInt("valid_count", 0).coerceAtLeast(0),
|
||||
brokenCount = status.optInt("broken_count", 0).coerceAtLeast(0),
|
||||
backups = backups
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseBackupInfo(json: JSONObject): ServerStoredBackupInfo = ServerStoredBackupInfo(
|
||||
id = json.optString("id", ""),
|
||||
createdAt = json.optLong("created_at", 0L),
|
||||
reason = json.optString("reason", "").take(40),
|
||||
serverVersion = json.optString("server_version", "").take(32),
|
||||
passwordCount = json.optInt("password_count", 0).coerceIn(0, 500),
|
||||
deviceCount = json.optInt("device_count", 0).coerceIn(0, 2048),
|
||||
sizeBytes = json.optLong("size_bytes", 0L).coerceAtLeast(0L),
|
||||
sha256 = json.optString("sha256", "").lowercase(),
|
||||
valid = json.optBoolean("valid", false),
|
||||
error = json.optString("error", "").take(240),
|
||||
contentMetadataAvailable = json.optBoolean("content_metadata", false),
|
||||
hasWireGuardKeys = json.optBoolean("has_wireguard_keys", false),
|
||||
hasBackupPolicy = json.optBoolean("has_backup_policy", false),
|
||||
outboundProfileMode = json.optString("outbound_profile_mode", "").takeIf {
|
||||
it in setOf("direct", "external_proxy", "tun_interface", "warp_free", "imported_wg", "wireguard_vps", "configured")
|
||||
}.orEmpty()
|
||||
)
|
||||
|
||||
internal fun parseBackupDocument(json: JSONObject): ServerStoredBackupDocument {
|
||||
require(json.optString("format") == "wdtt-server-snapshot") { "неподдерживаемый формат серверной копии" }
|
||||
val version = json.optInt("version", 0)
|
||||
require(version in 1..3) { "неподдерживаемая версия серверной копии" }
|
||||
val id = json.optString("id")
|
||||
requireBackupId(id)
|
||||
var total = 0L
|
||||
val seen = mutableSetOf<String>()
|
||||
val files = buildList {
|
||||
val array = json.optJSONArray("files") ?: throw IllegalArgumentException("в серверной копии нет файлов")
|
||||
require(array.length() in 2..4) { "некорректное число файлов в серверной копии" }
|
||||
for (index in 0 until array.length()) {
|
||||
val item = array.getJSONObject(index)
|
||||
val path = item.getString("path")
|
||||
require(path in setOf("passwords.json", "wg-keys.dat", "outbound-profile.env", "backup-policy.json") && seen.add(path)) {
|
||||
"недопустимый файл в серверной копии"
|
||||
}
|
||||
val size = item.getLong("size")
|
||||
val limit = when (path) {
|
||||
"passwords.json" -> 5_000_000L
|
||||
"wg-keys.dat" -> 4096L
|
||||
"outbound-profile.env" -> 2L * 1024 * 1024
|
||||
else -> 64L * 1024
|
||||
}
|
||||
require(item.optInt("mode", 0) == 384) { "небезопасные права файла $path" }
|
||||
require(size in 1..limit) { "некорректный размер файла $path" }
|
||||
val encoded = item.getString("data_b64")
|
||||
require(encoded.length <= (limit * 4 / 3 + 8).toInt()) { "файл $path слишком большой" }
|
||||
val data = Base64.getDecoder().decode(encoded)
|
||||
require(data.size.toLong() == size) { "размер файла $path не совпал" }
|
||||
val expected = item.getString("sha256").lowercase()
|
||||
require(Regex("^[0-9a-f]{64}$").matches(expected)) { "нет контрольной суммы файла $path" }
|
||||
require(java.security.MessageDigest.getInstance("SHA-256").digest(data).joinToString("") { "%02x".format(it) } == expected) {
|
||||
"контрольная сумма файла $path не совпала"
|
||||
}
|
||||
total += size
|
||||
require(total <= MAX_BACKUP_DOCUMENT_BYTES) { "серверная копия слишком большая" }
|
||||
add(
|
||||
ServerStoredBackupFile(
|
||||
path = path,
|
||||
mode = item.optInt("mode", 0),
|
||||
size = size,
|
||||
sha256 = expected,
|
||||
data = data
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
require(files.any { it.path == "passwords.json" } && files.any { it.path == "wg-keys.dat" }) {
|
||||
"в серверной копии нет базы или WireGuard-ключей"
|
||||
}
|
||||
require(version < 3 || files.any { it.path == "backup-policy.json" }) {
|
||||
"в серверной копии нет настроек резервного копирования"
|
||||
}
|
||||
return ServerStoredBackupDocument(
|
||||
id = id,
|
||||
createdAt = json.optLong("created_at", 0L),
|
||||
reason = json.optString("reason", ""),
|
||||
serverVersion = json.optString("server_version", ""),
|
||||
passwordCount = json.optInt("password_count", 0),
|
||||
deviceCount = json.optInt("device_count", 0),
|
||||
files = files
|
||||
)
|
||||
}
|
||||
|
||||
private fun actionFromResponse(json: JSONObject): ServerAdminActionResult {
|
||||
val restartRequired = json.optBoolean("restart_required", false)
|
||||
if (restartRequired) {
|
||||
@@ -643,10 +898,31 @@ internal fun buildAdminProfilePatchArgs(
|
||||
}
|
||||
|
||||
private class AdminSshClient(private val session: Session, private val sudoPassword: String) {
|
||||
fun exec(command: String, timeout: Long): String {
|
||||
companion object {
|
||||
private const val MAX_COMMAND_OUTPUT_CHARS = 16_000_000
|
||||
}
|
||||
|
||||
fun execRootWithStdin(command: String, stdinPayload: String, timeout: Long): String {
|
||||
val isRoot = session.userName == "root"
|
||||
if (!isRoot) {
|
||||
exec("sudo -S -p '' -v", 20_000L, sudoPassword + "\n")
|
||||
}
|
||||
val quoted = "'" + command.replace("'", "'\"'\"'") + "'"
|
||||
val rootCommand = if (isRoot) {
|
||||
"bash -c $quoted"
|
||||
} else {
|
||||
"sudo -n bash -c $quoted"
|
||||
}
|
||||
return exec(rootCommand, timeout, stdinPayload)
|
||||
}
|
||||
|
||||
fun exec(command: String, timeout: Long): String = exec(command, timeout, null)
|
||||
|
||||
private fun exec(command: String, timeout: Long, stdinPayload: String?): String {
|
||||
if (!session.isConnected) throw IllegalStateException("SSH-сессия разорвана")
|
||||
var channel: ChannelExec? = null
|
||||
val result = StringBuilder()
|
||||
val stdout = StringBuilder()
|
||||
val stderr = StringBuilder()
|
||||
try {
|
||||
channel = session.openChannel("exec") as ChannelExec
|
||||
channel.setCommand(command)
|
||||
@@ -654,12 +930,17 @@ private class AdminSshClient(private val session: Session, private val sudoPassw
|
||||
val input = channel.inputStream
|
||||
val err = channel.errStream
|
||||
channel.connect(15_000)
|
||||
if (command.contains("sudo -S")) {
|
||||
outStream.write("$sudoPassword\n".toByteArray())
|
||||
if (stdinPayload != null) {
|
||||
outStream.write(stdinPayload.toByteArray(Charsets.UTF_8))
|
||||
outStream.flush()
|
||||
} else if (command.contains("sudo -S")) {
|
||||
outStream.write("$sudoPassword\n".toByteArray(Charsets.UTF_8))
|
||||
outStream.flush()
|
||||
}
|
||||
val reader = input.bufferedReader()
|
||||
val errReader = err.bufferedReader()
|
||||
val stdoutBuffer = CharArray(8 * 1024)
|
||||
val stderrBuffer = CharArray(4 * 1024)
|
||||
val started = System.currentTimeMillis()
|
||||
while (!channel.isClosed || reader.ready() || errReader.ready()) {
|
||||
if (System.currentTimeMillis() - started > timeout) {
|
||||
@@ -667,16 +948,34 @@ private class AdminSshClient(private val session: Session, private val sudoPassw
|
||||
throw IllegalStateException("timeout")
|
||||
}
|
||||
if (reader.ready()) {
|
||||
reader.readLine()?.let { result.appendLine(cleanShellLine(it)) }
|
||||
val read = reader.read(stdoutBuffer)
|
||||
if (read > 0) {
|
||||
require(stdout.length + stderr.length + read <= MAX_COMMAND_OUTPUT_CHARS) {
|
||||
"ответ сервера превышает безопасный размер"
|
||||
}
|
||||
stdout.append(stdoutBuffer, 0, read)
|
||||
}
|
||||
}
|
||||
if (errReader.ready()) {
|
||||
errReader.readLine()
|
||||
?.takeIf { !it.contains("password for", ignoreCase = true) }
|
||||
?.let { result.appendLine(cleanShellLine(it)) }
|
||||
val read = errReader.read(stderrBuffer)
|
||||
if (read > 0) {
|
||||
require(stdout.length + stderr.length + read <= MAX_COMMAND_OUTPUT_CHARS) {
|
||||
"ответ сервера превышает безопасный размер"
|
||||
}
|
||||
stderr.append(stderrBuffer, 0, read)
|
||||
}
|
||||
}
|
||||
if (!reader.ready() && !errReader.ready()) Thread.sleep(80)
|
||||
}
|
||||
val output = result.toString().trim()
|
||||
val cleanStdout = cleanShellOutput(stdout.toString()).trim()
|
||||
val cleanStderr = cleanShellOutput(stderr.toString())
|
||||
.lineSequence()
|
||||
.filterNot { it.contains("password for", ignoreCase = true) }
|
||||
.joinToString("\n")
|
||||
.trim()
|
||||
val output = listOf(cleanStdout, cleanStderr)
|
||||
.filter(String::isNotBlank)
|
||||
.joinToString("\n")
|
||||
if (channel.exitStatus != 0) {
|
||||
if (output.startsWith("{") && output.endsWith("}")) return output
|
||||
throw IllegalStateException(output.ifBlank { "команда завершилась с кодом ${channel.exitStatus}" })
|
||||
@@ -690,8 +989,8 @@ private class AdminSshClient(private val session: Session, private val sudoPassw
|
||||
}
|
||||
}
|
||||
|
||||
private fun cleanShellLine(line: String): String =
|
||||
line.replace(Regex("\u001B\\[[;\\d]*m"), "")
|
||||
private fun cleanShellOutput(value: String): String =
|
||||
value.replace(Regex("\u001B\\[[;\\d]*m"), "")
|
||||
}
|
||||
|
||||
private fun String.thirdPortOrDefault(default: Int): Int =
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
/** Версии приложения, для которых выпускалась новая обязательная серверная часть. */
|
||||
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15)
|
||||
internal val SERVER_MIGRATION_LEVELS = intArrayOf(2, 3, 5, 6, 7, 12, 14, 15, 16)
|
||||
|
||||
data class ServerMigrationState(
|
||||
val pendingLevel: Int,
|
||||
@@ -65,7 +65,6 @@ internal fun resolveServerMigrationInitialization(
|
||||
pendingLevel = maxOf(pendingLevel, currentRequiredLevel)
|
||||
}
|
||||
}
|
||||
|
||||
return ServerMigrationInitialization(
|
||||
lastSeenAppVersionCode = maxOf(storedLastSeenAppVersionCode ?: 0, currentVersionCode),
|
||||
pendingLevel = pendingLevel,
|
||||
|
||||
@@ -733,6 +733,8 @@ class SettingsStore(context: Context) {
|
||||
private val WHITELIST_APPS = stringPreferencesKey("whitelist_apps")
|
||||
private val BLACKLIST_ADDRESSES = stringPreferencesKey("blacklist_addresses")
|
||||
private val WHITELIST_ADDRESSES = stringPreferencesKey("whitelist_addresses")
|
||||
private val VPN_APP_LISTS_VISIBLE_VK_MIGRATED =
|
||||
booleanPreferencesKey("vpn_app_lists_visible_vk_migrated")
|
||||
|
||||
// ═══ Theme Mode ═══
|
||||
private val THEME_MODE = stringPreferencesKey("theme_mode") // "system", "light", "dark"
|
||||
@@ -2336,7 +2338,8 @@ class SettingsStore(context: Context) {
|
||||
prefs[getProfileKey(SECONDARY_VK_HASH, profile)] = item.optString("secondaryVkHash")
|
||||
prefs[getProfileKey(VK_HASH_NEXT_SLOT, profile)] = 0
|
||||
prefs.remove(getProfileKey(EXCLUDED_APPS, profile))
|
||||
prefs[getProfileKey(WORKERS_PER_HASH, profile)] = item.optInt("workersPerHash", 18).coerceIn(1, 128)
|
||||
prefs[getProfileKey(WORKERS_PER_HASH, profile)] =
|
||||
item.optInt("workersPerHash", 18).coerceIn(1, 128)
|
||||
val importedProfileMaxWorkers = item.optInt("profileMaxWorkers", 0)
|
||||
if (
|
||||
importedProfileMaxWorkers in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
|
||||
@@ -3781,6 +3784,7 @@ class SettingsStore(context: Context) {
|
||||
|
||||
private suspend fun migrateVpnAppLists() {
|
||||
dataStore.edit { prefs ->
|
||||
val migrateVisibleVkBypass = prefs[VPN_APP_LISTS_VISIBLE_VK_MIGRATED] != true
|
||||
for (profile in 0 until VPN_PROFILE_COUNT) {
|
||||
val legacyKey = getProfileKey(EXCLUDED_APPS, profile)
|
||||
val legacyPackages = prefs[legacyKey].orEmpty()
|
||||
@@ -3808,8 +3812,19 @@ class SettingsStore(context: Context) {
|
||||
).joinToString(",")
|
||||
if (stored != sanitized) prefs[key] = sanitized
|
||||
}
|
||||
if (migrateVisibleVkBypass) {
|
||||
val blacklistKey = getProfileKey(BLACKLIST_APPS, profile)
|
||||
prefs[blacklistKey] = sanitizeVpnRoutingPackages(
|
||||
decodeStoredVpnPackages(prefs[blacklistKey].orEmpty()) +
|
||||
LEGACY_DEFAULT_BYPASSED_VPN_PACKAGES,
|
||||
appContext.packageName,
|
||||
).joinToString(",")
|
||||
}
|
||||
if (prefs[legacyKey] != null) prefs.remove(legacyKey)
|
||||
}
|
||||
if (migrateVisibleVkBypass) {
|
||||
prefs[VPN_APP_LISTS_VISIBLE_VK_MIGRATED] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -23,8 +23,8 @@ private const val SERVER_BACKUP_KIND = "server-backup"
|
||||
private const val PBKDF2_ITERATIONS = 210_000
|
||||
private const val KEY_BITS = 256
|
||||
private const val GCM_TAG_BITS = 128
|
||||
private const val MAX_TRANSFER_DOCUMENT_CHARS = 12_000_000
|
||||
private const val MAX_TRANSFER_PLAINTEXT_BYTES = 8_000_000
|
||||
private const val MAX_TRANSFER_DOCUMENT_CHARS = 24_000_000
|
||||
private const val MAX_TRANSFER_PLAINTEXT_BYTES = 16_000_000
|
||||
|
||||
data class AdminTransferPreview(
|
||||
val createdAt: Long,
|
||||
@@ -173,7 +173,7 @@ object WdttTransferCodec {
|
||||
val iterations = json.optInt("iterations", 0)
|
||||
require(iterations in 100_000..1_000_000) { "Некорректные параметры защиты файла." }
|
||||
val data = json.getString("data")
|
||||
require(data.length <= 10_700_000) { "Файл передачи слишком большой." }
|
||||
require(data.length <= MAX_TRANSFER_DOCUMENT_CHARS) { "Файл передачи слишком большой." }
|
||||
val salt = runCatching { Base64.getDecoder().decode(json.getString("salt")) }
|
||||
.getOrElse { throw IllegalArgumentException("Файл передачи повреждён.") }
|
||||
val iv = runCatching { Base64.getDecoder().decode(json.getString("iv")) }
|
||||
|
||||
@@ -72,12 +72,59 @@ internal fun shouldUseVkCallsPreflight(
|
||||
|
||||
internal fun vkCallsPreflightCooldownForLog(line: String): Long = when {
|
||||
line.contains("[VKCalls] VK временно ограничил анонимный вход", true) -> 60_000L
|
||||
line.contains("[VKCalls] VKCalls запросил CAPTCHA", true) -> 120_000L
|
||||
line.contains("[VKCalls] preflight не сработал", true) &&
|
||||
line.contains("временно не повторяем", true) -> 45_000L
|
||||
// CAPTCHA and ordinary network failures are scoped to one join link in
|
||||
// the native client. Persisting either as an Android-wide cooldown made a
|
||||
// later native restart skip modern VKCalls for every independent hash and
|
||||
// created a cascade of legacy CAPTCHA requests. Only a confirmed flood is
|
||||
// shared by the public IP and must survive a quick process restart.
|
||||
else -> 0L
|
||||
}
|
||||
|
||||
internal data class VkCallsLogPresentation(
|
||||
val key: String,
|
||||
val message: String,
|
||||
val warning: Boolean = false,
|
||||
)
|
||||
|
||||
internal fun classifyVkCallsLog(line: String, isError: Boolean = false): VkCallsLogPresentation? {
|
||||
if (!line.contains("[VKCalls]", true)) return null
|
||||
val text = line.substringAfter("[VKCalls]", line).trim()
|
||||
return when {
|
||||
text.contains("TURN credentials получены", true) ->
|
||||
VkCallsLogPresentation("vkcalls_ok", "[VKCalls] Основной бескапчевый провайдер сработал ✓")
|
||||
text.contains("preflight не сработал", true) ||
|
||||
text.contains("временно ограничил", true) ||
|
||||
text.contains("временно пропущен", true) ||
|
||||
text.contains("две современные анонимные сессии запросили CAPTCHA", true) ->
|
||||
VkCallsLogPresentation(
|
||||
"vkcalls_fallback",
|
||||
"[VKCalls] Основной провайдер временно недоступен — пробуем совместимый резерв",
|
||||
)
|
||||
text.contains("продолжаем резервную legacy-цепочку", true) ->
|
||||
VkCallsLogPresentation(
|
||||
"vkcalls_fallback",
|
||||
"[VKCalls] Основной провайдер временно недоступен — пробуем совместимый резерв",
|
||||
)
|
||||
text.contains("пробуем совместимый резерв", true) ->
|
||||
VkCallsLogPresentation(
|
||||
"vkcalls_api_fallback",
|
||||
"[VKCalls] Основной API-домен не ответил — пробуем совместимый резерв",
|
||||
)
|
||||
text.contains(Regex("""preflight\s+\d+/\d+""")) ||
|
||||
text.equals("preflight", ignoreCase = true) ->
|
||||
VkCallsLogPresentation("vkcalls_start", "[VKCalls] Пробуем основной бескапчевый провайдер...")
|
||||
text.contains("первая анонимная сессия не принята", true) ->
|
||||
VkCallsLogPresentation(
|
||||
"vkcalls_retry",
|
||||
"[VKCalls] Повторяем проверку с новой анонимной сессией...",
|
||||
)
|
||||
isError ->
|
||||
VkCallsLogPresentation("vkcalls_status", "[VKCalls] $text", warning = true)
|
||||
else ->
|
||||
VkCallsLogPresentation("vkcalls_status", "[VKCalls] $text")
|
||||
}
|
||||
}
|
||||
|
||||
internal fun boundedVkCallsPreflightCooldownUntil(
|
||||
untilMs: Long,
|
||||
nowMs: Long = System.currentTimeMillis(),
|
||||
@@ -106,6 +153,24 @@ enum class NetworkRecoveryAction {
|
||||
StopVpn
|
||||
}
|
||||
|
||||
internal fun shouldDeferRepeatedTransportErrorStop(
|
||||
line: String,
|
||||
refusedCount: Int,
|
||||
threshold: Int = 400,
|
||||
): Boolean {
|
||||
if (refusedCount < threshold) return false
|
||||
val lower = line.lowercase(Locale.ROOT)
|
||||
return "connection refused" in lower ||
|
||||
"timeout" in lower ||
|
||||
"timed out" in lower ||
|
||||
"таймаут" in lower ||
|
||||
"тайм-аут" in lower ||
|
||||
"network is unreachable" in lower ||
|
||||
"network unreachable" in lower ||
|
||||
"no route to host" in lower ||
|
||||
"enetunreach" in lower
|
||||
}
|
||||
|
||||
internal fun stableNetworkRecoveryAction(@Suppress("UNUSED_PARAMETER") completedAttempts: Int): NetworkRecoveryAction =
|
||||
NetworkRecoveryAction.SoftRestart
|
||||
|
||||
@@ -142,6 +207,34 @@ internal fun shouldResetNetworkRecoveryFromStats(
|
||||
(trafficChanged || !statsTrafficStagnant)
|
||||
}
|
||||
|
||||
internal data class TrafficSignatureDelta(
|
||||
val initializeBaseline: Boolean,
|
||||
val downstreamChanged: Boolean,
|
||||
val upstreamChanged: Boolean,
|
||||
) {
|
||||
val trafficChanged: Boolean
|
||||
get() = downstreamChanged || upstreamChanged
|
||||
}
|
||||
|
||||
internal fun classifyTrafficSignatureDelta(
|
||||
previousDownstream: String,
|
||||
previousUpstream: String,
|
||||
currentDownstream: String,
|
||||
currentUpstream: String,
|
||||
): TrafficSignatureDelta {
|
||||
val currentKnown = currentDownstream.isNotBlank() && currentUpstream.isNotBlank()
|
||||
if (!currentKnown) return TrafficSignatureDelta(false, false, false)
|
||||
|
||||
val baselineKnown = previousDownstream.isNotBlank() && previousUpstream.isNotBlank()
|
||||
if (!baselineKnown) return TrafficSignatureDelta(true, false, false)
|
||||
|
||||
return TrafficSignatureDelta(
|
||||
initializeBaseline = false,
|
||||
downstreamChanged = currentDownstream != previousDownstream,
|
||||
upstreamChanged = currentUpstream != previousUpstream,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun hasFreshTransportHeartbeat(
|
||||
running: Boolean,
|
||||
activeWorkers: Int,
|
||||
@@ -196,6 +289,38 @@ internal fun shouldReconnectTunnelAfterWake(
|
||||
confirmedNetworkFailure: Boolean,
|
||||
): Boolean = activeWorkers <= 0 || confirmedNetworkFailure
|
||||
|
||||
internal enum class WakeRescueAction {
|
||||
HEALTHY,
|
||||
WAIT_FOR_PROBE,
|
||||
RECONNECT,
|
||||
}
|
||||
|
||||
internal fun decideWakeRescueAction(
|
||||
freshTransportPath: Boolean,
|
||||
activeWorkers: Int,
|
||||
confirmedNetworkFailure: Boolean,
|
||||
finalCheck: Boolean,
|
||||
): WakeRescueAction = when {
|
||||
freshTransportPath -> WakeRescueAction.HEALTHY
|
||||
finalCheck || shouldReconnectTunnelAfterWake(activeWorkers, confirmedNetworkFailure) ->
|
||||
WakeRescueAction.RECONNECT
|
||||
else -> WakeRescueAction.WAIT_FOR_PROBE
|
||||
}
|
||||
|
||||
internal fun wakeRecoveryReferenceAt(
|
||||
lastDeviceWakeAtMs: Long,
|
||||
nowMs: Long,
|
||||
maxAgeMs: Long = 60_000L,
|
||||
): Long = if (
|
||||
lastDeviceWakeAtMs > 0L &&
|
||||
nowMs >= lastDeviceWakeAtMs &&
|
||||
nowMs - lastDeviceWakeAtMs <= maxAgeMs
|
||||
) {
|
||||
lastDeviceWakeAtMs
|
||||
} else {
|
||||
nowMs
|
||||
}
|
||||
|
||||
internal fun shouldObserveTunnelHealth(
|
||||
deviceInteractive: Boolean,
|
||||
wakeRecoveryGraceActive: Boolean,
|
||||
@@ -581,7 +706,7 @@ private const val STABLE_RECOVERY_GRACE_MS = 10 * 60_000L
|
||||
private const val STABLE_RECOVERY_RETRY_MS = 10 * 60_000L
|
||||
private const val STABLE_ZERO_WORKERS_GRACE_MS = 15 * 60_000L
|
||||
private const val STAGNANT_ACTIVE_TRAFFIC_MS = 20 * 60_000L
|
||||
private const val WAKE_RECOVERY_GRACE_MS = 90_000L
|
||||
private const val WAKE_RECOVERY_GRACE_MS = 60_000L
|
||||
|
||||
object TunnelManager {
|
||||
private const val VK_CALLS_RUNTIME_PREFERENCES = "tunnel_runtime"
|
||||
@@ -637,6 +762,8 @@ object TunnelManager {
|
||||
private var lastUnderlyingNetworkChangeAtMs = 0L
|
||||
private var networkTransitionGraceUntilMs = 0L
|
||||
private var wakeRecoveryGraceUntilMs = 0L
|
||||
@Volatile
|
||||
private var lastDeviceWakeStartedAtMs = 0L
|
||||
private var lastNetworkSettleRestartAtMs = 0L
|
||||
private var lastStableNetworkIssueLogAtMs = 0L
|
||||
private val sessionTraffic = TunnelSessionTrafficAccumulator()
|
||||
@@ -655,6 +782,7 @@ object TunnelManager {
|
||||
val config = MutableStateFlow<String?>(null)
|
||||
val stats = MutableStateFlow("Ожидание данных...")
|
||||
val activeWorkers = MutableStateFlow(0)
|
||||
val vpnInterfaceUp = MutableStateFlow(false)
|
||||
val connectionIssue = MutableStateFlow<ConnectionIssue?>(null)
|
||||
val vpnSlotYieldRequested = MutableStateFlow(false)
|
||||
|
||||
@@ -991,7 +1119,8 @@ object TunnelManager {
|
||||
val hasFreshActiveWorkers = activeWorkers.value > 0 &&
|
||||
lastActiveAtMs > recoverableNetworkErrorAtMs &&
|
||||
now - lastActiveAtMs < 2 * 60_000L
|
||||
if (!hardFailure && hasFreshActiveWorkers && !isStatsTrafficStagnant(now)) return null
|
||||
val statsTrafficStagnant = isStatsTrafficStagnant(now)
|
||||
if (!hardFailure && hasFreshActiveWorkers && !statsTrafficStagnant) return null
|
||||
|
||||
if (now - recoverableNetworkErrorAtMs < stableRecoveryGraceMs(hardFailure)) return null
|
||||
if (now - lastRecoveryAtMs < stableRecoveryRetryMs(hardFailure)) return null
|
||||
@@ -1110,6 +1239,15 @@ object TunnelManager {
|
||||
)
|
||||
}
|
||||
|
||||
fun noteVpnRoutingEvent(key: String, message: String) {
|
||||
updateLog(
|
||||
key = "vpn_routing_$key",
|
||||
message = "[МАРШРУТИЗАЦИЯ] $message",
|
||||
priority = 10,
|
||||
isError = false,
|
||||
)
|
||||
}
|
||||
|
||||
fun noteVpnDnsEvent(key: String, message: String, warning: Boolean = false) {
|
||||
val logKey = "vpn_dns_$key"
|
||||
val text = "[DNS VPN] $message"
|
||||
@@ -1311,7 +1449,7 @@ object TunnelManager {
|
||||
val cmd = mutableListOf(
|
||||
binaryPath,
|
||||
"-peer", params.peer,
|
||||
"-vk", hashList.joinToString(","),
|
||||
"-startup-config-stdin=true",
|
||||
"-n", totalWorkers.toString(),
|
||||
"-listen", "127.0.0.1:${params.port}"
|
||||
)
|
||||
@@ -1412,13 +1550,7 @@ object TunnelManager {
|
||||
cmd.add("-device-info")
|
||||
cmd.add(buildDeviceInfoJson(appContext))
|
||||
|
||||
cmd.add("-password")
|
||||
cmd.add(params.connectionPassword)
|
||||
|
||||
if (
|
||||
params.managedConfigFirstStart &&
|
||||
params.profileMaxWorkers >= TUNNEL_WORKERS_PER_GROUP
|
||||
) {
|
||||
if (params.configFirstStart) {
|
||||
cmd.add("-config-first-start=true")
|
||||
if (totalWorkers == TUNNEL_WORKERS_PER_GROUP) {
|
||||
cmd.add("-hash-fallback=true")
|
||||
@@ -1434,15 +1566,23 @@ object TunnelManager {
|
||||
|
||||
val env = pb.environment()
|
||||
env["LD_LIBRARY_PATH"] = context.applicationInfo.nativeLibraryDir
|
||||
if (params.customVkCredentialsEnabled) {
|
||||
env["WDTT_CUSTOM_VK_CLIENT_ID"] = params.customVkClientId
|
||||
env["WDTT_CUSTOM_VK_CLIENT_SECRET"] = params.customVkClientSecret
|
||||
} else {
|
||||
env.remove("WDTT_CUSTOM_VK_CLIENT_ID")
|
||||
env.remove("WDTT_CUSTOM_VK_CLIENT_SECRET")
|
||||
}
|
||||
env.remove("WDTT_CUSTOM_VK_CLIENT_ID")
|
||||
env.remove("WDTT_CUSTOM_VK_CLIENT_SECRET")
|
||||
|
||||
process = pb.start()
|
||||
val startupLine = nativeClientStartupConfigLine(
|
||||
NativeClientStartupSecrets(
|
||||
vkHashes = hashList.joinToString(","),
|
||||
connectionPassword = params.connectionPassword,
|
||||
customVkClientId = if (params.customVkCredentialsEnabled) params.customVkClientId else "",
|
||||
customVkClientSecret = if (params.customVkCredentialsEnabled) params.customVkClientSecret else "",
|
||||
)
|
||||
)
|
||||
synchronized(processInputLock) {
|
||||
val startedProcess = process ?: error("Нативный клиент не запущен")
|
||||
startedProcess.outputStream.write("$startupLine\n".toByteArray(Charsets.UTF_8))
|
||||
startedProcess.outputStream.flush()
|
||||
}
|
||||
processStartedAtMs = System.currentTimeMillis()
|
||||
wrapAuthTimeoutCount = 0
|
||||
resetStatsLivenessState()
|
||||
@@ -1735,8 +1875,19 @@ object TunnelManager {
|
||||
lineTrim.contains("timeout", true) ||
|
||||
isHardNetworkFailure(lineTrim) -> {
|
||||
refusedCount++
|
||||
if (refusedCount >= 400) {
|
||||
handleCriticalError("Критическое отсутствие сети (400+ таймаутов). Отключение.")
|
||||
if (shouldDeferRepeatedTransportErrorStop(lineTrim, refusedCount)) {
|
||||
refusedCount = 0
|
||||
noteRecoverableNetworkIssue(
|
||||
"Сеть временно недоступна",
|
||||
"Транспорт получил много сетевых таймаутов. WDTT Plus попробует восстановить соединение автоматически; если сеть не вернётся, VPN будет остановлен позже безопасным recovery-механизмом.",
|
||||
hardFailure = isHardNetworkFailure(lineTrim),
|
||||
confirmedUserTrafficFailure = true,
|
||||
)
|
||||
updateWarningLog(
|
||||
"network_timeout_recovery_deferred",
|
||||
"[СЕТЬ] Много таймаутов транспорта; мгновенный стоп отложен, включён recovery.",
|
||||
80,
|
||||
)
|
||||
return@forEachLine
|
||||
}
|
||||
}
|
||||
@@ -1764,15 +1915,22 @@ object TunnelManager {
|
||||
|
||||
val downSignature = trafficSignature(statsDownTrafficRegex, msg)
|
||||
val upSignature = trafficSignature(statsUpTrafficRegex, msg)
|
||||
val trafficKnown = downSignature.isNotBlank() && upSignature.isNotBlank()
|
||||
val downstreamChanged = trafficKnown && downSignature != lastStatsDownTrafficSignature
|
||||
val upstreamChanged = trafficKnown && upSignature != lastStatsUpTrafficSignature
|
||||
val trafficChanged = downstreamChanged || upstreamChanged
|
||||
if (trafficKnown && lastDownstreamTrafficChangedAtMs == 0L) {
|
||||
val trafficDelta = classifyTrafficSignatureDelta(
|
||||
previousDownstream = lastStatsDownTrafficSignature,
|
||||
previousUpstream = lastStatsUpTrafficSignature,
|
||||
currentDownstream = downSignature,
|
||||
currentUpstream = upSignature,
|
||||
)
|
||||
val downstreamChanged = trafficDelta.downstreamChanged
|
||||
val upstreamChanged = trafficDelta.upstreamChanged
|
||||
val trafficChanged = trafficDelta.trafficChanged
|
||||
if (trafficDelta.initializeBaseline) {
|
||||
// Первая строка статистики — только исходная точка.
|
||||
// Она не доказывает, что после пробуждения пришёл новый
|
||||
// пакет, поэтому не обновляем liveness-время до реального
|
||||
// изменения соответствующего счётчика.
|
||||
lastStatsDownTrafficSignature = downSignature
|
||||
lastStatsUpTrafficSignature = upSignature
|
||||
lastDownstreamTrafficChangedAtMs = now
|
||||
lastUpstreamTrafficChangedAtMs = now
|
||||
} else if (trafficChanged) {
|
||||
if (downstreamChanged) {
|
||||
lastStatsDownTrafficSignature = downSignature
|
||||
@@ -1895,20 +2053,12 @@ object TunnelManager {
|
||||
}
|
||||
}
|
||||
lineTrim.contains("[VKCalls]", true) -> {
|
||||
when {
|
||||
lineTrim.contains("TURN credentials получены", true) ->
|
||||
updateLog("vkcalls_ok", "[VKCalls] Основной бескапчевый провайдер сработал ✓", 2, false)
|
||||
lineTrim.contains("preflight не сработал", true) ||
|
||||
lineTrim.contains("временно ограничил", true) ||
|
||||
lineTrim.contains("временно пропущен", true) ->
|
||||
updateLog("vkcalls_fallback", "[VKCalls] Основной провайдер временно недоступен — пробуем совместимый резерв", 20, false)
|
||||
lineTrim.contains("пробуем совместимый резерв", true) ->
|
||||
updateLog("vkcalls_api_fallback", "[VKCalls] Основной API-домен не ответил — пробуем совместимый резерв", 20, false)
|
||||
lineTrim.endsWith("[VKCalls] preflight", true) ->
|
||||
updateLog("vkcalls_start", "[VKCalls] Пробуем основной бескапчевый провайдер...", 2, false)
|
||||
else -> {
|
||||
if (isError) updateWarningLog("vkcalls_status", lineTrim, 20)
|
||||
else updateLog("vkcalls_status", lineTrim, 20, false)
|
||||
val presentation = classifyVkCallsLog(lineTrim, isError)
|
||||
if (presentation != null) {
|
||||
if (presentation.warning) {
|
||||
updateWarningLog(presentation.key, presentation.message, 20)
|
||||
} else {
|
||||
updateLog(presentation.key, presentation.message, 20, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2430,7 +2580,7 @@ object TunnelManager {
|
||||
resetStatsLivenessState()
|
||||
noteSessionTransportRestart()
|
||||
val restartDelayMs = transportRecoveryPolicy(
|
||||
params.managedConfigFirstStart
|
||||
params.configFirstStart
|
||||
).processRestartDelayMs
|
||||
scope.launch {
|
||||
killProcess()
|
||||
@@ -2550,6 +2700,9 @@ object TunnelManager {
|
||||
|
||||
fun noteDeviceWakeStarted(now: Long = System.currentTimeMillis()) {
|
||||
if (!running.value) return
|
||||
// Запоминаем границу до команды native-процессу: быстрый pong может
|
||||
// прийти раньше, чем TunnelService успеет создать rescue-задачу.
|
||||
lastDeviceWakeStartedAtMs = now
|
||||
resetNetworkRecoveryState()
|
||||
sendTransportLifecycleCommand("DEVICE_WAKE")
|
||||
wakeRecoveryGraceUntilMs = now + WAKE_RECOVERY_GRACE_MS
|
||||
@@ -2562,6 +2715,13 @@ object TunnelManager {
|
||||
)
|
||||
}
|
||||
|
||||
fun wakeRecoveryReferenceAt(now: Long = System.currentTimeMillis()): Long =
|
||||
wakeRecoveryReferenceAt(
|
||||
lastDeviceWakeAtMs = lastDeviceWakeStartedAtMs,
|
||||
nowMs = now,
|
||||
maxAgeMs = WAKE_RECOVERY_GRACE_MS,
|
||||
)
|
||||
|
||||
fun connectionIssueTitleForNotification(now: Long = System.currentTimeMillis()): String? {
|
||||
val issue = connectionIssue.value ?: return null
|
||||
if (!running.value) return null
|
||||
@@ -2804,8 +2964,10 @@ object TunnelManager {
|
||||
process = null
|
||||
if (proc != null) {
|
||||
try {
|
||||
proc.outputStream.write("STOP\n".toByteArray(Charsets.UTF_8))
|
||||
proc.outputStream.flush()
|
||||
synchronized(processInputLock) {
|
||||
proc.outputStream.write("STOP\n".toByteArray(Charsets.UTF_8))
|
||||
proc.outputStream.flush()
|
||||
}
|
||||
} catch (_: Exception) {}
|
||||
try { proc.waitFor(1500, java.util.concurrent.TimeUnit.MILLISECONDS) } catch (_: Exception) {}
|
||||
if (proc.isAlive) {
|
||||
@@ -2930,6 +3092,10 @@ object TunnelManager {
|
||||
}
|
||||
}
|
||||
|
||||
fun noteVpnInterfaceState(up: Boolean) {
|
||||
vpnInterfaceUp.value = up
|
||||
}
|
||||
|
||||
fun scheduleWireGuardReload(profileIndex: Int, delayMs: Long = 250L) {
|
||||
if (!shouldReloadWireGuardRouting(running.value, activeTunnelProfile.value, profileIndex)) return
|
||||
wireGuardReloadJob?.cancel()
|
||||
@@ -3055,21 +3221,23 @@ object TunnelManager {
|
||||
}
|
||||
|
||||
private fun writeCaptchaResult(expectedProcess: Process, requestId: String, result: String) {
|
||||
if (process !== expectedProcess || !expectedProcess.isAlive) return
|
||||
try {
|
||||
val payload = if (requestId.isBlank()) result else "$requestId|$result"
|
||||
val line = "CAPTCHA_RESULT|$payload\n"
|
||||
expectedProcess.outputStream.write(line.toByteArray(Charsets.UTF_8))
|
||||
expectedProcess.outputStream.flush()
|
||||
} catch (e: Exception) {
|
||||
// Остановка туннеля может закрыть stdin между проверкой isAlive и записью.
|
||||
// Это штатная гонка завершения, а не ошибка подключения пользователя.
|
||||
if (process === expectedProcess && expectedProcess.isAlive) {
|
||||
updateWarningLog(
|
||||
"captcha_write_err",
|
||||
"[КАПЧА] Нативный клиент не принял результат: ${e.message ?: e::class.simpleName}",
|
||||
5
|
||||
)
|
||||
synchronized(processInputLock) {
|
||||
if (process !== expectedProcess || !expectedProcess.isAlive) return
|
||||
try {
|
||||
val payload = if (requestId.isBlank()) result else "$requestId|$result"
|
||||
val line = "CAPTCHA_RESULT|$payload\n"
|
||||
expectedProcess.outputStream.write(line.toByteArray(Charsets.UTF_8))
|
||||
expectedProcess.outputStream.flush()
|
||||
} catch (e: Exception) {
|
||||
// Остановка туннеля может закрыть stdin между проверкой isAlive и записью.
|
||||
// Это штатная гонка завершения, а не ошибка подключения пользователя.
|
||||
if (process === expectedProcess && expectedProcess.isAlive) {
|
||||
updateWarningLog(
|
||||
"captcha_write_err",
|
||||
"[КАПЧА] Нативный клиент не принял результат: ${e.message ?: e::class.simpleName}",
|
||||
5
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3118,7 +3286,7 @@ data class TunnelParams(
|
||||
val customVkClientId: String = "",
|
||||
val customVkClientSecret: String = "",
|
||||
val profileMaxWorkers: Int = 0,
|
||||
val managedConfigFirstStart: Boolean = false,
|
||||
val configFirstStart: Boolean = true,
|
||||
val profileIndex: Int = 0,
|
||||
)
|
||||
|
||||
|
||||
@@ -47,7 +47,8 @@ private const val TUNNEL_ALERT_NOTIFICATION_ID = 2
|
||||
private const val NETWORK_CHANGE_SETTLE_MS = 90_000L
|
||||
private const val NETWORK_RETURN_SETTLE_MS = 45_000L
|
||||
private const val NETWORK_LOSS_GRACE_MS = 2 * 60_000L
|
||||
private const val WAKE_RESCUE_GRACE_MS = 60_000L
|
||||
private const val WAKE_RESCUE_FIRST_CHECK_MS = 20_000L
|
||||
private const val WAKE_RESCUE_FINAL_CHECK_DELAY_MS = 25_000L
|
||||
private const val TIMER_RESUME_TRANSPORT_CONFIRM_MS = 75_000L
|
||||
private const val TIMER_RESUME_TRANSPORT_WAKE_LOCK_TIMEOUT_MS =
|
||||
TIMER_RESUME_TRANSPORT_CONFIRM_MS + 15_000L
|
||||
@@ -495,8 +496,8 @@ class TunnelService : Service() {
|
||||
customVkClientId = intent.getStringExtra("custom_vk_client_id") ?: "",
|
||||
customVkClientSecret = intent.getStringExtra("custom_vk_client_secret") ?: "",
|
||||
profileMaxWorkers = intent.getIntExtra("profile_max_workers", 0),
|
||||
managedConfigFirstStart =
|
||||
intent.getBooleanExtra(MANAGED_CONFIG_FIRST_START_EXTRA, false),
|
||||
configFirstStart =
|
||||
intent.getBooleanExtra(CONFIG_FIRST_START_EXTRA, true),
|
||||
profileIndex = intent.getIntExtra(TUNNEL_PROFILE_INDEX_EXTRA, 0).coerceIn(0, 2),
|
||||
)
|
||||
requestTunnelStart(params)
|
||||
@@ -1701,33 +1702,47 @@ class TunnelService : Service() {
|
||||
|
||||
private fun scheduleWakeRescueCheck() {
|
||||
if (!AMNEZIA_STYLE_RECOVERY || !TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return
|
||||
val wakeStartedAt = System.currentTimeMillis()
|
||||
val wakeStartedAt = TunnelManager.wakeRecoveryReferenceAt()
|
||||
wakeRescueJob?.cancel()
|
||||
wakeRescueJob = TunnelManager.scope.launch(Dispatchers.Main) {
|
||||
delay(WAKE_RESCUE_GRACE_MS)
|
||||
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
|
||||
val confirmedNetworkFailure = TunnelManager.hasConfirmedNetworkFailureSince(wakeStartedAt)
|
||||
val shouldReconnect = shouldReconnectTunnelAfterWake(
|
||||
activeWorkers = TunnelManager.activeWorkers.value,
|
||||
confirmedNetworkFailure = confirmedNetworkFailure,
|
||||
)
|
||||
if (TunnelManager.hasFreshTunnelActivitySince(wakeStartedAt)) {
|
||||
TunnelManager.noteWakeRescueHealthy()
|
||||
} else if (shouldReconnect) {
|
||||
TunnelManager.noteWakeRescueReconnect()
|
||||
updateNotification("Восстановление транспорта после сна...")
|
||||
TunnelManager.restartTransport(
|
||||
reason = "[СОН] После пробуждения нет рабочих каналов или ответа на пользовательский трафик. Мягко переподключаем транспорт без пересоздания VPN.",
|
||||
minIntervalMs = WAKE_RESCUE_GRACE_MS,
|
||||
force = true,
|
||||
delay(WAKE_RESCUE_FIRST_CHECK_MS)
|
||||
var finalCheck = false
|
||||
while (isActive) {
|
||||
if (!TunnelManager.running.value || isTunnelPaused || TunnelManager.isCaptchaInProgress()) return@launch
|
||||
val action = decideWakeRescueAction(
|
||||
freshTransportPath = TunnelManager.hasFreshTransportPathSince(wakeStartedAt),
|
||||
activeWorkers = TunnelManager.activeWorkers.value,
|
||||
confirmedNetworkFailure = TunnelManager.hasConfirmedNetworkFailureSince(wakeStartedAt),
|
||||
finalCheck = finalCheck,
|
||||
)
|
||||
} else {
|
||||
// Выход из сна сам по себе не является доказательством поломки:
|
||||
// Android и оператор могут на короткое время задержать вывод статистики.
|
||||
// Не перезапускаем ни native-транспорт, ни системный VPN-интерфейс.
|
||||
TunnelManager.noteWakeRescueDeferred()
|
||||
when (action) {
|
||||
WakeRescueAction.HEALTHY -> {
|
||||
TunnelManager.noteWakeRescueHealthy()
|
||||
updateNotification(buildTunnelNotificationText())
|
||||
return@launch
|
||||
}
|
||||
WakeRescueAction.WAIT_FOR_PROBE -> {
|
||||
// Положительное число воркеров после Doze может быть
|
||||
// устаревшим. Даём немедленному native keepalive ещё одно
|
||||
// короткое окно, но больше не откладываем решение навсегда.
|
||||
TunnelManager.noteWakeRescueDeferred()
|
||||
updateNotification(buildTunnelNotificationText())
|
||||
finalCheck = true
|
||||
delay(WAKE_RESCUE_FINAL_CHECK_DELAY_MS)
|
||||
}
|
||||
WakeRescueAction.RECONNECT -> {
|
||||
TunnelManager.noteWakeRescueReconnect()
|
||||
updateNotification("Восстановление транспорта после сна...")
|
||||
TunnelManager.restartTransport(
|
||||
reason = "[СОН] После пробуждения сервер не подтвердил свежий двусторонний канал. Мягко переподключаем транспорт без пересоздания VPN.",
|
||||
minIntervalMs = WAKE_RESCUE_FIRST_CHECK_MS + WAKE_RESCUE_FINAL_CHECK_DELAY_MS,
|
||||
force = true,
|
||||
)
|
||||
updateNotification(buildTunnelNotificationText())
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
}
|
||||
updateNotification(buildTunnelNotificationText())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2070,19 +2085,6 @@ class TunnelService : Service() {
|
||||
scheduleTrustedWifiResumeRetry()
|
||||
return
|
||||
}
|
||||
if (android.net.VpnService.prepare(applicationContext) != null) {
|
||||
val status = "VPN-разрешение недоступно. Откройте WDTT Plus для восстановления."
|
||||
releaseTrustedWifiTransitionWakeLock()
|
||||
TunnelManager.noteTrustedWifiEvent(
|
||||
"resume_permission",
|
||||
"Android не дал повторно занять VPN-слот; требуется открыть приложение.",
|
||||
warning = true
|
||||
)
|
||||
TrustedWifiManager.setStatus(status)
|
||||
withContext(Dispatchers.Main) { updateNotification(status) }
|
||||
return
|
||||
}
|
||||
|
||||
val params = lastStartParams ?: buildTunnelParamsFromSettings(applicationContext)
|
||||
if (params == null) {
|
||||
val status = "Не удалось прочитать профиль VPN. Откройте WDTT Plus."
|
||||
@@ -2337,7 +2339,7 @@ class TunnelService : Service() {
|
||||
TunnelManager.noteUnderlyingNetworkChanged(
|
||||
"Android подтвердил рабочую сеть",
|
||||
graceMs = transportRecoveryPolicy(
|
||||
lastStartParams?.managedConfigFirstStart == true
|
||||
lastStartParams?.configFirstStart == true
|
||||
).networkSettleDelayMs,
|
||||
replaceGrace = false
|
||||
)
|
||||
@@ -2365,7 +2367,7 @@ class TunnelService : Service() {
|
||||
return
|
||||
}
|
||||
val recoveryPolicy = transportRecoveryPolicy(
|
||||
lastStartParams?.managedConfigFirstStart == true
|
||||
lastStartParams?.configFirstStart == true
|
||||
)
|
||||
if (!shouldStartUnderlyingNetworkCheck(
|
||||
checkPending = stableNetworkReconnectPending,
|
||||
@@ -2764,11 +2766,6 @@ class TunnelService : Service() {
|
||||
val helper = WireGuardHelper(applicationContext)
|
||||
val startupWindow = System.currentTimeMillis() - TunnelManager.processStartedAtMs < INITIAL_VPN_START_GRACE_MS
|
||||
val captchaActive = TunnelManager.isCaptchaInProgress()
|
||||
if (!startupWindow && !captchaActive && android.net.VpnService.prepare(applicationContext) != null) {
|
||||
Log.w("TunnelService", "VPN-разрешение WDTT Plus отозвано или слот передан другому VPN. Выключаем WDTT Plus.")
|
||||
stopTunnel(TunnelStopReason.VpnSlotTransferred)
|
||||
break
|
||||
}
|
||||
// Не полагаемся только на broadcast: после глубокого сна первая
|
||||
// итерация службы иногда выполняется раньше ACTION_SCREEN_ON.
|
||||
observeDeviceInteractiveState(deviceInteractive)
|
||||
|
||||
@@ -4,7 +4,7 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
internal const val TUNNEL_PROFILE_INDEX_EXTRA = "profile_index"
|
||||
internal const val MANAGED_CONFIG_FIRST_START_EXTRA = "managed_config_first_start"
|
||||
internal const val CONFIG_FIRST_START_EXTRA = "config_first_start"
|
||||
internal const val DEFAULT_RT_TURN_SNI = "ya.ru"
|
||||
|
||||
internal fun normalizeRtTurnSni(value: String): String? {
|
||||
@@ -41,9 +41,9 @@ internal data class TransportRecoveryPolicy(
|
||||
)
|
||||
|
||||
internal fun transportRecoveryPolicy(
|
||||
managedConfigFirstStart: Boolean,
|
||||
configFirstStart: Boolean,
|
||||
): TransportRecoveryPolicy {
|
||||
val processRestartDelayMs = if (managedConfigFirstStart) 250L else 2_500L
|
||||
val processRestartDelayMs = if (configFirstStart) 250L else 2_500L
|
||||
return TransportRecoveryPolicy(
|
||||
networkSettleDelayMs = 15_000L,
|
||||
reconnectMinIntervalMs = 2 * 60_000L,
|
||||
@@ -79,12 +79,13 @@ internal fun displayedTunnelProfile(
|
||||
selectedProfile
|
||||
}.coerceIn(0, 2)
|
||||
|
||||
internal fun shouldUseManagedConfigFirstStart(
|
||||
remoteManaged: Boolean,
|
||||
profileMaxWorkers: Int,
|
||||
): Boolean = remoteManaged &&
|
||||
profileMaxWorkers in TUNNEL_WORKERS_PER_GROUP..APP_MAX_WORKERS &&
|
||||
profileMaxWorkers % TUNNEL_WORKERS_PER_GROUP == 0
|
||||
/**
|
||||
* WireGuard configuration is mandatory for every profile, not only for a
|
||||
* remotely managed profile with a worker limit. Starting data workers before
|
||||
* GETCONF succeeds can otherwise report an active transport while Android has
|
||||
* no VPN interface and user traffic is still going directly over Wi-Fi.
|
||||
*/
|
||||
internal fun shouldUseConfigFirstStart(): Boolean = true
|
||||
|
||||
suspend fun buildTunnelParamsFromSettings(
|
||||
context: Context,
|
||||
@@ -101,10 +102,7 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
||||
saved.workersPerHash,
|
||||
saved.profileMaxWorkers
|
||||
)
|
||||
val managedConfigFirstStart = shouldUseManagedConfigFirstStart(
|
||||
remoteManaged = saved.remoteManaged,
|
||||
profileMaxWorkers = saved.profileMaxWorkers,
|
||||
)
|
||||
val configFirstStart = shouldUseConfigFirstStart()
|
||||
val linkParts = saved.link
|
||||
.takeIf { saved.linkMode }
|
||||
?.let { WdttDeepLink.validate(it).parts }
|
||||
@@ -133,7 +131,7 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
||||
customVkClientId = saved.customVkClientId,
|
||||
customVkClientSecret = saved.customVkClientSecret,
|
||||
profileMaxWorkers = saved.profileMaxWorkers,
|
||||
managedConfigFirstStart = managedConfigFirstStart,
|
||||
configFirstStart = configFirstStart,
|
||||
profileIndex = saved.profileIndex,
|
||||
)
|
||||
} else {
|
||||
@@ -169,7 +167,7 @@ internal fun buildTunnelParams(saved: TunnelProfileSnapshot): TunnelParams? {
|
||||
customVkClientId = saved.customVkClientId,
|
||||
customVkClientSecret = saved.customVkClientSecret,
|
||||
profileMaxWorkers = saved.profileMaxWorkers,
|
||||
managedConfigFirstStart = managedConfigFirstStart,
|
||||
configFirstStart = configFirstStart,
|
||||
profileIndex = saved.profileIndex,
|
||||
)
|
||||
}
|
||||
@@ -200,7 +198,7 @@ suspend fun buildTunnelStartIntentFromSettings(context: Context): Intent? {
|
||||
putExtra("custom_vk_client_id", params.customVkClientId)
|
||||
putExtra("custom_vk_client_secret", params.customVkClientSecret)
|
||||
putExtra("profile_max_workers", params.profileMaxWorkers)
|
||||
putExtra(MANAGED_CONFIG_FIRST_START_EXTRA, params.managedConfigFirstStart)
|
||||
putExtra(CONFIG_FIRST_START_EXTRA, params.configFirstStart)
|
||||
putExtra(TUNNEL_PROFILE_INDEX_EXTRA, params.profileIndex)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import java.net.IDN
|
||||
|
||||
internal const val MAX_VPN_ADDRESS_RULES = 128
|
||||
internal const val MAX_VPN_ADDRESS_IMPORT_BYTES = 1024 * 1024
|
||||
private const val MAX_VPN_ROUTING_APP_PACKAGES = 5_000
|
||||
private const val MAX_WIREGUARD_ALLOWED_IPS = 4096
|
||||
private const val MAX_EFFECTIVE_IPV4_PREFIXES = 128
|
||||
private const val IPV4_BITS = 32
|
||||
@@ -69,16 +70,25 @@ internal data class VpnRoutingDocument(
|
||||
val whitelistAddresses: List<VpnAddressRule>,
|
||||
)
|
||||
|
||||
internal fun encodeVpnRoutingDocument(document: VpnRoutingDocument): String =
|
||||
JSONObject().apply {
|
||||
internal fun encodeVpnRoutingDocument(document: VpnRoutingDocument): String {
|
||||
val blacklistApps = normalizeVpnRoutingDocumentPackages(document.blacklistApps)
|
||||
val whitelistApps = normalizeVpnRoutingDocumentPackages(document.whitelistApps)
|
||||
val blacklistAddresses = normalizeVpnRoutingDocumentAddresses(document.blacklistAddresses)
|
||||
val whitelistAddresses = normalizeVpnRoutingDocumentAddresses(document.whitelistAddresses)
|
||||
val encoded = JSONObject().apply {
|
||||
put("format", "wdtt-plus-routing")
|
||||
put("version", 1)
|
||||
put("isWhitelist", document.isWhitelist)
|
||||
put("blacklistApps", JSONArray(document.blacklistApps.distinct().sorted()))
|
||||
put("whitelistApps", JSONArray(document.whitelistApps.distinct().sorted()))
|
||||
put("blacklistAddresses", JSONArray(encodeVpnAddressRules(document.blacklistAddresses)))
|
||||
put("whitelistAddresses", JSONArray(encodeVpnAddressRules(document.whitelistAddresses)))
|
||||
put("blacklistApps", JSONArray(blacklistApps))
|
||||
put("whitelistApps", JSONArray(whitelistApps))
|
||||
put("blacklistAddresses", JSONArray(encodeVpnAddressRules(blacklistAddresses)))
|
||||
put("whitelistAddresses", JSONArray(encodeVpnAddressRules(whitelistAddresses)))
|
||||
}.toString(2)
|
||||
require(encoded.toByteArray(Charsets.UTF_8).size <= MAX_VPN_ADDRESS_IMPORT_BYTES) {
|
||||
"Маршрутизация слишком большая для экспорта. Сократите списки приложений."
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
|
||||
internal fun decodeVpnRoutingDocument(raw: String): VpnRoutingDocument {
|
||||
require(raw.toByteArray(Charsets.UTF_8).size <= MAX_VPN_ADDRESS_IMPORT_BYTES) {
|
||||
@@ -157,7 +167,23 @@ internal fun normalizeVpnAddressRules(rawValue: String): List<VpnAddressRule> {
|
||||
entries.forEachIndexed { index, entry ->
|
||||
val range = parseIpv4Range(entry)
|
||||
val normalized = if (range == null) {
|
||||
listOf(normalizeVpnAddressRule(entry))
|
||||
runCatching {
|
||||
val rule = normalizeVpnAddressRule(entry)
|
||||
require(
|
||||
rule.type != VpnAddressType.DOMAIN || '.' in rule.value
|
||||
) {
|
||||
"Одноуровневое имя не подходит: это доменная зона или неполный адрес. " +
|
||||
"Укажите точный домен с точкой, например example.ru. " +
|
||||
"Зоны .ru и маски *.ru пока не поддерживаются."
|
||||
}
|
||||
listOf(rule)
|
||||
}
|
||||
.getOrElse { error ->
|
||||
throw IllegalArgumentException(
|
||||
"Строка ${index + 1}: ${error.message ?: "некорректный адрес."}",
|
||||
error,
|
||||
)
|
||||
}
|
||||
} else if (range.first == range.last) {
|
||||
listOf(VpnAddressRule(VpnAddressType.IP, formatIpv4(range.first)))
|
||||
} else {
|
||||
@@ -175,9 +201,13 @@ internal fun normalizeVpnAddressRules(rawValue: String): List<VpnAddressRule> {
|
||||
return rules.distinct()
|
||||
}
|
||||
|
||||
internal fun encodeVpnAddressRules(rules: List<VpnAddressRule>): String =
|
||||
JSONArray().apply {
|
||||
rules.distinct().take(MAX_VPN_ADDRESS_RULES).forEach { rule ->
|
||||
internal fun encodeVpnAddressRules(rules: List<VpnAddressRule>): String {
|
||||
val distinctRules = rules.distinct()
|
||||
require(distinctRules.size <= MAX_VPN_ADDRESS_RULES) {
|
||||
"В одном списке может быть не больше $MAX_VPN_ADDRESS_RULES адресов."
|
||||
}
|
||||
return JSONArray().apply {
|
||||
distinctRules.forEach { rule ->
|
||||
put(
|
||||
JSONObject()
|
||||
.put("type", rule.type.storedValue)
|
||||
@@ -185,6 +215,7 @@ internal fun encodeVpnAddressRules(rules: List<VpnAddressRule>): String =
|
||||
)
|
||||
}
|
||||
}.toString()
|
||||
}
|
||||
|
||||
internal fun decodeVpnAddressRules(raw: String): List<VpnAddressRule> {
|
||||
if (raw.isBlank()) return emptyList()
|
||||
@@ -328,7 +359,9 @@ private fun extractBareHostWithPort(rawValue: String): String? {
|
||||
private fun parseVpnPackagesJson(root: JSONObject, key: String): List<String> {
|
||||
val array = root.optJSONArray(key)
|
||||
?: throw IllegalArgumentException("В файле нет списка $key.")
|
||||
require(array.length() <= 5_000) { "Список приложений в файле слишком большой." }
|
||||
require(array.length() <= MAX_VPN_ROUTING_APP_PACKAGES) {
|
||||
"Список приложений в файле слишком большой."
|
||||
}
|
||||
// В Android встречается системный пакет `android` без точки, поэтому формат
|
||||
// должен принимать и его: файл, созданный самим приложением, обязан импортироваться.
|
||||
val packagePattern = Regex("[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z0-9_]+)*")
|
||||
@@ -343,6 +376,38 @@ private fun parseVpnPackagesJson(root: JSONObject, key: String): List<String> {
|
||||
}.distinct().sorted()
|
||||
}
|
||||
|
||||
private fun normalizeVpnRoutingDocumentPackages(packages: List<String>): List<String> {
|
||||
val normalized = packages.map(String::trim).distinct().sorted()
|
||||
require(normalized.size <= MAX_VPN_ROUTING_APP_PACKAGES) {
|
||||
"Список приложений слишком большой для экспорта."
|
||||
}
|
||||
val packagePattern = Regex("[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z0-9_]+)*")
|
||||
normalized.forEachIndexed { index, packageName ->
|
||||
require(packageName.length in 1..255 && packagePattern.matches(packageName)) {
|
||||
"Некорректный пакет приложения в записи №${index + 1}."
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
private fun normalizeVpnRoutingDocumentAddresses(
|
||||
rules: List<VpnAddressRule>,
|
||||
): List<VpnAddressRule> {
|
||||
val normalized = rules.mapIndexed { index, rule ->
|
||||
runCatching { normalizeVpnAddressRule(rule.value, rule.type) }
|
||||
.getOrElse { error ->
|
||||
throw IllegalArgumentException(
|
||||
"Некорректный адрес в записи №${index + 1}: ${error.message ?: "ошибка правила."}",
|
||||
error,
|
||||
)
|
||||
}
|
||||
}.distinct()
|
||||
require(normalized.size <= MAX_VPN_ADDRESS_RULES) {
|
||||
"В одном экспортируемом списке может быть не больше $MAX_VPN_ADDRESS_RULES адресов."
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
private fun parseVpnAddressRulesJson(root: JSONObject, key: String): List<VpnAddressRule> {
|
||||
val array = root.optJSONArray(key)
|
||||
?: throw IllegalArgumentException("В файле нет списка $key.")
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package com.wdtt.plus
|
||||
|
||||
internal val ALWAYS_BYPASSED_VPN_PACKAGES = setOf(
|
||||
internal val LEGACY_DEFAULT_BYPASSED_VPN_PACKAGES = setOf(
|
||||
"com.vkontakte.android",
|
||||
"com.vk.calls"
|
||||
"com.vk.calls",
|
||||
)
|
||||
|
||||
internal val ALWAYS_BYPASSED_VPN_PACKAGES: Set<String> = emptySet()
|
||||
|
||||
internal fun isAlwaysBypassedVpnPackage(packageName: String, ownPackageName: String): Boolean {
|
||||
return packageName == ownPackageName || packageName in ALWAYS_BYPASSED_VPN_PACKAGES
|
||||
}
|
||||
|
||||
@@ -76,16 +76,21 @@ class VpnWidgetProvider : AppWidgetProvider() {
|
||||
super.onReceive(context, intent)
|
||||
if (intent.action == ACTION_WIDGET_TOGGLE) {
|
||||
runCatching {
|
||||
when (
|
||||
val running = TunnelManager.running.value
|
||||
val trustedWifiWaiting = TrustedWifiManager.state.value.waiting
|
||||
val action = if (running || trustedWifiWaiting) {
|
||||
TunnelToggleAction.STOP
|
||||
} else {
|
||||
tunnelToggleAction(
|
||||
running = TunnelManager.running.value,
|
||||
trustedWifiWaiting = TrustedWifiManager.state.value.waiting,
|
||||
running = false,
|
||||
trustedWifiWaiting = false,
|
||||
vpnPermissionRequired = VpnService.prepare(context) != null,
|
||||
)
|
||||
) {
|
||||
}
|
||||
when (action) {
|
||||
TunnelToggleAction.STOP -> {
|
||||
context.startService(
|
||||
Intent(context, TunnelService::class.java).apply { action = "STOP" }
|
||||
Intent(context, TunnelService::class.java).apply { this.action = "STOP" }
|
||||
)
|
||||
updateAllWidgets(context)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.wdtt.plus
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.wireguard.android.backend.GoBackend
|
||||
import com.wireguard.android.backend.Tunnel
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
@@ -17,9 +16,9 @@ internal fun shouldClearPhantomVpn(activeTunnelProfile: Int?): Boolean =
|
||||
|
||||
class WdttApplication : Application() {
|
||||
@Volatile
|
||||
private var backendInstance: GoBackend? = null
|
||||
private var backendInstance: SafeGoBackend? = null
|
||||
|
||||
val backend: GoBackend
|
||||
val backend: SafeGoBackend
|
||||
get() = getBackend(this)
|
||||
|
||||
override fun onCreate() {
|
||||
@@ -82,9 +81,24 @@ class WdttApplication : Application() {
|
||||
}
|
||||
}
|
||||
|
||||
fun getBackend(context: Context): GoBackend {
|
||||
fun getBackend(context: Context): SafeGoBackend {
|
||||
return backendInstance ?: synchronized(this) {
|
||||
backendInstance ?: GoBackend(context.applicationContext).also { backendInstance = it }
|
||||
backendInstance ?: SafeGoBackend(context.applicationContext).also { backend ->
|
||||
backend.setRevocationListener {
|
||||
TunnelManager.onWireGuardInterfaceDropped(vpnSlotTransferred = true)
|
||||
runCatching {
|
||||
startService(
|
||||
android.content.Intent(this@WdttApplication, TunnelService::class.java).apply {
|
||||
action = ACTION_VPN_SLOT_REVOKED
|
||||
},
|
||||
)
|
||||
}.onFailure { error ->
|
||||
Log.w("WdttApp", "Не удалось передать отзыв VPN foreground-службе", error)
|
||||
}
|
||||
}
|
||||
backendInstance = backend
|
||||
backend
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,9 +2,7 @@ package com.wdtt.plus
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.util.Log
|
||||
import com.wireguard.android.backend.GoBackend
|
||||
import com.wireguard.android.backend.Tunnel
|
||||
import com.wireguard.config.Config
|
||||
import com.wireguard.config.Interface
|
||||
@@ -50,6 +48,7 @@ class WireGuardHelper(context: Context) {
|
||||
if (isCurrentTunnel) {
|
||||
sharedTunnel = null
|
||||
sharedConfigFingerprint = null
|
||||
TunnelManager.noteVpnInterfaceState(false)
|
||||
}
|
||||
if (isCurrentTunnel && !suppressDownCallback) {
|
||||
onExternalDown?.invoke()
|
||||
@@ -63,10 +62,6 @@ class WireGuardHelper(context: Context) {
|
||||
|
||||
private suspend fun startTunnelLocked(configString: String) = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
if (VpnService.prepare(appContext) != null) {
|
||||
throw IllegalStateException("VPN-разрешение не выдано")
|
||||
}
|
||||
|
||||
val parsedConfig = Config.parse(ByteArrayInputStream(configString.toByteArray(Charsets.UTF_8)))
|
||||
|
||||
val builder = Interface.Builder()
|
||||
@@ -172,6 +167,21 @@ class WireGuardHelper(context: Context) {
|
||||
allowedIps = effectiveAllowedIps,
|
||||
)
|
||||
|
||||
val routingMode = if (isWhitelist) "белый список" else "чёрный список"
|
||||
val appRuleCount = selectedPackages.count {
|
||||
!isAlwaysBypassedVpnPackage(it, appContext.packageName)
|
||||
}
|
||||
val fullIpv4Tunnel = routedAllowedIps.contains("0.0.0.0/0")
|
||||
TunnelManager.noteVpnRoutingEvent(
|
||||
key = "applied_${dnsSettings.profileIndex}_${isWhitelist}_${appRuleCount}_${addressRules.size}_${routedAllowedIps.size}",
|
||||
message = buildString {
|
||||
append("«$profileLabel»: $routingMode; правил приложений: $appRuleCount, ")
|
||||
append("правил адресов: ${addressRules.size}, маршрутов VPN: ${routedAllowedIps.size}; ")
|
||||
append(if (fullIpv4Tunnel) "IPv4 идёт через VPN полностью" else "действует раздельная маршрутизация")
|
||||
if (routing.blocksAllApps) append("; пустой белый список блокирует пользовательский трафик")
|
||||
},
|
||||
)
|
||||
|
||||
val newInterface = builder.build()
|
||||
|
||||
val peerBuilder = Peer.Builder()
|
||||
@@ -225,6 +235,7 @@ class WireGuardHelper(context: Context) {
|
||||
updatedConfig = finalConfig,
|
||||
)
|
||||
) {
|
||||
TunnelManager.noteVpnInterfaceState(true)
|
||||
Log.d("WG", "WireGuard config unchanged; keeping the current VPN interface")
|
||||
return@withContext
|
||||
}
|
||||
@@ -255,8 +266,13 @@ class WireGuardHelper(context: Context) {
|
||||
}
|
||||
sharedTunnel = nextTunnel
|
||||
sharedConfigFingerprint = wireGuardConfigFingerprint(finalConfig)
|
||||
TunnelManager.noteVpnInterfaceState(true)
|
||||
Log.d("WG", "WireGuard tunnel started successfully")
|
||||
} catch (e: Exception) {
|
||||
val stillUp = sharedTunnel?.let { tunnel ->
|
||||
runCatching { backend.getState(tunnel) == Tunnel.State.UP }.getOrDefault(false)
|
||||
} ?: false
|
||||
TunnelManager.noteVpnInterfaceState(stillUp)
|
||||
val detailed = "WireGuard start failed: ${e.readableMessage()}; ${configString.describeWireGuardConfig()}"
|
||||
Log.e("WG", detailed)
|
||||
e.printStackTrace()
|
||||
@@ -332,61 +348,27 @@ class WireGuardHelper(context: Context) {
|
||||
sharedConfigFingerprint = null
|
||||
Log.d("WG", "WireGuard tunnel stopped")
|
||||
}
|
||||
TunnelManager.noteVpnInterfaceState(false)
|
||||
} catch (e: Exception) {
|
||||
val stillUp = sharedTunnel?.let { tunnel ->
|
||||
runCatching { backend.getState(tunnel) == Tunnel.State.UP }.getOrDefault(false)
|
||||
} ?: false
|
||||
TunnelManager.noteVpnInterfaceState(stillUp)
|
||||
Log.e("WG", "Failed to stop WireGuard: ${e.readableMessage()}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun notifyWireGuardInterfaceDropped() {
|
||||
val slotTransferred = isVpnSlotTransferred()
|
||||
TunnelManager.onWireGuardInterfaceDropped(slotTransferred)
|
||||
if (slotTransferred) {
|
||||
requestVpnSlotHandoverStop()
|
||||
return
|
||||
}
|
||||
|
||||
// При смене VPN Android может уничтожить старый VpnService чуть раньше,
|
||||
// чем обновит владельца разрешения. Несколько коротких проверок закрывают
|
||||
// эту гонку, не добавляя постоянного polling: ветка выполняется только
|
||||
// после внешнего DOWN-сигнала от WireGuard.
|
||||
TunnelManager.scope.launch {
|
||||
repeat(20) {
|
||||
delay(250L)
|
||||
if (isVpnSlotTransferred()) {
|
||||
TunnelManager.onWireGuardInterfaceDropped(vpnSlotTransferred = true)
|
||||
requestVpnSlotHandoverStop()
|
||||
return@launch
|
||||
}
|
||||
}
|
||||
}
|
||||
// SafeGoBackend.onRevoke is the authoritative external-revocation
|
||||
// signal. A bare DOWN can also be a transient loss after sleep.
|
||||
TunnelManager.onWireGuardInterfaceDropped(vpnSlotTransferred = false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Не полагаемся только на StateFlow: callback WireGuard приходит в момент,
|
||||
* когда Android уже передаёт единственный VPN-слот. Доставляем сигнал в
|
||||
* работающую foreground-службу сразу, чтобы она закрыла нативный клиент и
|
||||
* не смогла запустить WireGuard повторно в этой сессии.
|
||||
*/
|
||||
private fun requestVpnSlotHandoverStop() {
|
||||
runCatching {
|
||||
appContext.startService(
|
||||
Intent(appContext, TunnelService::class.java).apply {
|
||||
action = ACTION_VPN_SLOT_REVOKED
|
||||
}
|
||||
)
|
||||
}.onFailure {
|
||||
Log.w("WG", "Не удалось немедленно передать остановку VPN-службе: ${it.readableMessage()}")
|
||||
}
|
||||
}
|
||||
|
||||
private fun isVpnSlotTransferred(): Boolean =
|
||||
runCatching { VpnService.prepare(appContext) != null }.getOrDefault(false)
|
||||
|
||||
private suspend fun ensureGoBackendServiceStarted() {
|
||||
withContext(Dispatchers.Main) {
|
||||
runCatching {
|
||||
val intent = Intent(appContext, GoBackend.VpnService::class.java)
|
||||
val intent = Intent(appContext, SafeGoBackend.VpnService::class.java)
|
||||
appContext.startService(intent)
|
||||
}.onFailure {
|
||||
Log.w("WG", "GoBackend service warmup failed: ${it.readableMessage()}")
|
||||
@@ -402,6 +384,10 @@ class WireGuardHelper(context: Context) {
|
||||
backend.setState(nextTunnel, Tunnel.State.UP, finalConfig)
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
if (shouldYieldVpnSlotAfterSafeEstablishFailure(e)) {
|
||||
notifyVpnSlotUnavailable()
|
||||
throw e
|
||||
}
|
||||
lastError = e
|
||||
Log.w("WG", "WireGuard UP attempt ${attempt + 1}/3 failed: ${e.readableMessage()}")
|
||||
runCatching { backend.setState(nextTunnel, Tunnel.State.DOWN, null) }
|
||||
@@ -412,6 +398,19 @@ class WireGuardHelper(context: Context) {
|
||||
throw lastError ?: IllegalStateException("WireGuard UP failed")
|
||||
}
|
||||
|
||||
private fun notifyVpnSlotUnavailable() {
|
||||
TunnelManager.onWireGuardInterfaceDropped(vpnSlotTransferred = true)
|
||||
runCatching {
|
||||
appContext.startService(
|
||||
Intent(appContext, TunnelService::class.java).apply {
|
||||
action = ACTION_VPN_SLOT_REVOKED
|
||||
},
|
||||
)
|
||||
}.onFailure { error ->
|
||||
Log.w("WG", "Не удалось остановить WDTT после безопасного отказа Android", error)
|
||||
}
|
||||
}
|
||||
|
||||
private fun Throwable.readableMessage(): String {
|
||||
val text = message ?: localizedMessage
|
||||
return if (text.isNullOrBlank()) this::class.java.simpleName else "${this::class.java.simpleName}: $text"
|
||||
@@ -446,3 +445,7 @@ internal fun wireGuardConfigFingerprint(config: Config): String =
|
||||
MessageDigest.getInstance("SHA-256")
|
||||
.digest(config.toWgQuickString().toByteArray(Charsets.UTF_8))
|
||||
.joinToString(separator = "") { byte -> "%02x".format(byte.toInt() and 0xff) }
|
||||
|
||||
internal fun shouldYieldVpnSlotAfterSafeEstablishFailure(error: Throwable): Boolean =
|
||||
generateSequence(error) { it.cause }
|
||||
.any { it is SafeGoBackend.VpnSlotUnavailableException }
|
||||
File diff suppressed because it is too large.
Load diff
@@ -59,6 +59,8 @@ fun DeviceCompatibilityDialog(
|
||||
onCopy: (() -> Unit)? = null,
|
||||
onAction: ((DeviceCheckAction) -> Unit)? = null
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
val visibleItems = remember(report) {
|
||||
report.items.ifEmpty {
|
||||
listOf(
|
||||
@@ -96,7 +98,8 @@ fun DeviceCompatibilityDialog(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(20.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
) {
|
||||
Row(
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ApplicationInfo
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ResolveInfo
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.gestures.Orientation
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.gestures.rememberScrollableState
|
||||
@@ -95,6 +100,7 @@ import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.compose.LifecycleResumeEffect
|
||||
@@ -284,22 +290,17 @@ fun ExceptionsTab(
|
||||
val visibleInstalledApps = if (showSystemAppsOpt == true) {
|
||||
appsList
|
||||
} else {
|
||||
appsList.filter {
|
||||
!it.isSystem ||
|
||||
it.packageName in selectedPackages ||
|
||||
it.packageName == "com.google.android.youtube" ||
|
||||
it.packageName == "com.android.vending"
|
||||
}
|
||||
visibleAppsWithSystemSelected(appsList, selectedPackages)
|
||||
}
|
||||
val visibleApps = unavailableSelectedApps + visibleInstalledApps
|
||||
if (appSearchQuery.isBlank()) {
|
||||
visibleApps
|
||||
val queryFilteredApps = if (appSearchQuery.isBlank()) {
|
||||
unavailableSelectedApps + visibleInstalledApps
|
||||
} else {
|
||||
visibleApps.filter {
|
||||
(unavailableSelectedApps + visibleInstalledApps).filter {
|
||||
it.name.contains(appSearchQuery, ignoreCase = true) ||
|
||||
it.packageName.contains(appSearchQuery, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
sortAppsForRoutingList(queryFilteredApps, selectedPackages)
|
||||
}
|
||||
}
|
||||
val filteredAddresses = remember(addressRules, addressSearchQuery, addressFilter) {
|
||||
@@ -404,6 +405,7 @@ fun ExceptionsTab(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.focusGroup()
|
||||
.nestedScroll(collapsingHeaderConnection)
|
||||
.padding(horizontal = 16.dp),
|
||||
) {
|
||||
@@ -744,7 +746,7 @@ private fun RoutingModeCard(
|
||||
Text("Режим списка", fontWeight = FontWeight.SemiBold)
|
||||
IconButton(
|
||||
onClick = onHelp,
|
||||
modifier = Modifier.size(30.dp),
|
||||
modifier = Modifier.size(30.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
@@ -788,6 +790,11 @@ private fun AppsRoutingHeader(
|
||||
CompactControlSurface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteToggleableRow(
|
||||
value = showSystemApps ?: false,
|
||||
enabled = showSystemApps != null,
|
||||
onValueChange = onShowSystemChanged,
|
||||
)
|
||||
.then(sectionSwipeModifier),
|
||||
) {
|
||||
Text(
|
||||
@@ -798,7 +805,7 @@ private fun AppsRoutingHeader(
|
||||
)
|
||||
Switch(
|
||||
checked = showSystemApps ?: false,
|
||||
onCheckedChange = onShowSystemChanged,
|
||||
onCheckedChange = null,
|
||||
enabled = showSystemApps != null,
|
||||
modifier = Modifier.heightIn(max = 42.dp),
|
||||
)
|
||||
@@ -838,7 +845,10 @@ private fun AppsRoutingHeader(
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton(onClick = onQuickHelp, modifier = Modifier.size(38.dp)) {
|
||||
IconButton(
|
||||
onClick = onQuickHelp,
|
||||
modifier = Modifier.size(38.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Инструкция по быстрым исключениям",
|
||||
@@ -957,6 +967,7 @@ private fun AddressesRoutingHeader(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(RoutingControlHeight)
|
||||
.remoteFocusOutline(RoundedCornerShape(16.dp))
|
||||
.then(sectionSwipeModifier),
|
||||
shape = RoundedCornerShape(16.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
@@ -989,7 +1000,10 @@ private fun AddressesRoutingHeader(
|
||||
maxLines = 2,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onHelp) {
|
||||
IconButton(
|
||||
onClick = onHelp,
|
||||
modifier = Modifier.remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Инструкция по адресам",
|
||||
@@ -1038,9 +1052,11 @@ private fun AddAddressDialog(
|
||||
) {
|
||||
var value by rememberSaveable { mutableStateOf("") }
|
||||
var error by rememberSaveable { mutableStateOf("") }
|
||||
val previewRules = remember(value) {
|
||||
if (value.isBlank()) null else runCatching { normalizeVpnAddressRules(value) }.getOrNull()
|
||||
val previewResult = remember(value) {
|
||||
if (value.isBlank()) null else runCatching { normalizeVpnAddressRules(value) }
|
||||
}
|
||||
val previewRules = previewResult?.getOrNull()
|
||||
val validationError = previewResult?.exceptionOrNull()?.message.orEmpty()
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = {
|
||||
@@ -1052,7 +1068,10 @@ private fun AddAddressDialog(
|
||||
"Добавить адрес",
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = "Закрыть добавление адреса",
|
||||
@@ -1063,7 +1082,8 @@ private fun AddAddressDialog(
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Text(
|
||||
"Введите домен, ссылку сайта, IPv4, подсеть CIDR или диапазон IPv4. " +
|
||||
"Введите точный домен, ссылку сайта, IPv4, подсеть CIDR или диапазон IPv4. " +
|
||||
"Доменные зоны (.ru) и маски (*.ru) не поддерживаются. " +
|
||||
"Несколько значений добавляйте с новой строки.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
)
|
||||
@@ -1080,10 +1100,11 @@ private fun AddAddressDialog(
|
||||
singleLine = false,
|
||||
minLines = 3,
|
||||
maxLines = 6,
|
||||
isError = error.isNotBlank(),
|
||||
isError = error.isNotBlank() || validationError.isNotBlank(),
|
||||
supportingText = {
|
||||
when {
|
||||
error.isNotBlank() -> Text(error)
|
||||
validationError.isNotBlank() -> Text(validationError)
|
||||
previewRules?.size == 1 -> Text(
|
||||
"Будет добавлено как: ${previewRules.single().type.label}"
|
||||
)
|
||||
@@ -1101,6 +1122,8 @@ private fun AddAddressDialog(
|
||||
onClick = {
|
||||
if (value.isBlank()) {
|
||||
error = "Введите адрес."
|
||||
} else if (validationError.isNotBlank()) {
|
||||
error = validationError
|
||||
} else {
|
||||
onAdd(value) { message -> error = message }
|
||||
}
|
||||
@@ -1112,6 +1135,8 @@ private fun AddAddressDialog(
|
||||
|
||||
@Composable
|
||||
private fun RoutingHelpDialog(help: RoutingHelp, onDismiss: () -> Unit) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
val title: String
|
||||
val body: String
|
||||
when (help) {
|
||||
@@ -1129,11 +1154,12 @@ private fun RoutingHelpDialog(help: RoutingHelp, onDismiss: () -> Unit) {
|
||||
|
||||
RoutingHelp.ADDRESSES -> {
|
||||
title = "Маршрутизация адресов"
|
||||
body = "В ЧС выбранные адреса идут напрямую, в БС — только выбранные адреса идут через VPN. Можно вставить несколько строк: точные домены, ссылки, домены или IPv4 с портом, отдельные IPv4, подсети CIDR и диапазоны IPv4. Порт удаляется, а диапазон преобразуется в минимальный набор подсетей. Домен при запуске VPN преобразуется в его текущие IPv4-адреса, поэтому после смены DNS-адресов перезапустите VPN. Маска *.example.org не равна DNS-имени и требует отдельного DNS-перехватчика; обычный WireGuard принимает только IP-маршруты, поэтому такие маски и IPv6 сейчас не применяются. Если в БС заполнены приложения и адреса, через VPN пойдёт трафик выбранных приложений к выбранным адресам."
|
||||
body = "В ЧС выбранные адреса идут напрямую, в БС — только выбранные адреса идут через VPN. Можно вставить несколько строк: точные домены, ссылки, домены или IPv4 с портом, отдельные IPv4, подсети CIDR и диапазоны IPv4. Порт удаляется, а диапазон преобразуется в минимальный набор подсетей. Домен при запуске VPN преобразуется в его текущие IPv4-адреса, поэтому после смены DNS-адресов перезапустите VPN. Значение ru обозначает доменную зону, а не все сайты .ru. Доменные зоны и маски *.example.org требуют отдельного DNS-перехватчика; обычный WireGuard принимает только IP-маршруты, поэтому такие правила и IPv6 сейчас не применяются. Если в БС заполнены приложения и адреса, через VPN пойдёт трафик выбранных приложений к выбранным адресам."
|
||||
}
|
||||
}
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
modifier = Modifier.televisionDialogWidth(television),
|
||||
title = {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -1143,7 +1169,10 @@ private fun RoutingHelpDialog(help: RoutingHelp, onDismiss: () -> Unit) {
|
||||
title,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = "Закрыть инструкцию",
|
||||
@@ -1155,11 +1184,13 @@ private fun RoutingHelpDialog(help: RoutingHelp, onDismiss: () -> Unit) {
|
||||
Text(
|
||||
body,
|
||||
modifier = Modifier
|
||||
.heightIn(max = 360.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
.heightIn(max = if (television) 520.dp else 360.dp)
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
)
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text("Понятно") } },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = !television),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1282,7 +1313,9 @@ private fun AddressRow(rule: VpnAddressRule, onRemove: () -> Unit) {
|
||||
VpnAddressType.SUBNET -> Icons.Default.Hub
|
||||
}
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteFocusOutline(RoundedCornerShape(14.dp)),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
@@ -1336,7 +1369,9 @@ private fun EmptyListMessage(text: String) {
|
||||
fun AppRow(app: AppItem, isSelected: Boolean, onClick: () -> Unit) {
|
||||
Surface(
|
||||
onClick = onClick,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteFocusOutline(RoundedCornerShape(14.dp)),
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
color = MaterialTheme.colorScheme.surfaceContainerHighest,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
@@ -1403,21 +1438,98 @@ private fun String.toVpnPackageSet(): Set<String> =
|
||||
|
||||
private fun loadInstalledApps(context: Context): List<AppItem> {
|
||||
val packageManager = context.packageManager
|
||||
return packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
|
||||
val appsByPackage = linkedMapOf<String, ApplicationInfo>()
|
||||
|
||||
fun addApp(app: ApplicationInfo?) {
|
||||
if (app == null) return
|
||||
if (isAlwaysBypassedVpnPackage(app.packageName, context.packageName)) return
|
||||
appsByPackage.putIfAbsent(app.packageName, app)
|
||||
}
|
||||
|
||||
packageManager.getInstalledApplicationsCompat()
|
||||
.forEach(::addApp)
|
||||
|
||||
val launcherIntent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
packageManager.queryIntentActivitiesCompat(launcherIntent)
|
||||
.forEach { resolveInfo ->
|
||||
val app = resolveInfo.activityInfo?.applicationInfo
|
||||
if (app != null) {
|
||||
addApp(app)
|
||||
}
|
||||
}
|
||||
|
||||
QuickExclusionExactPackages
|
||||
.forEach { packageName -> addApp(packageManager.getApplicationInfoCompat(packageName)) }
|
||||
|
||||
return appsByPackage.values
|
||||
.asSequence()
|
||||
.filterNot { isAlwaysBypassedVpnPackage(it.packageName, context.packageName) }
|
||||
.map { app ->
|
||||
AppItem(
|
||||
name = app.loadLabel(packageManager).toString(),
|
||||
packageName = app.packageName,
|
||||
icon = runCatching { app.loadIcon(packageManager).toBitmap().asImageBitmap() }.getOrNull(),
|
||||
isSystem = app.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM != 0,
|
||||
isSystem = isVpnRoutingSystemApp(app.packageName, app.flags),
|
||||
)
|
||||
}
|
||||
.sortedBy { it.name.lowercase() }
|
||||
.toList()
|
||||
}
|
||||
|
||||
internal fun isVpnRoutingSystemApp(packageName: String, flags: Int): Boolean {
|
||||
val systemFlags = ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP
|
||||
if (flags and systemFlags == 0) return false
|
||||
return packageName !in QuickExclusionExactPackages
|
||||
}
|
||||
|
||||
internal fun visibleAppsWithSystemSelected(
|
||||
apps: List<AppItem>,
|
||||
selectedPackages: Set<String>,
|
||||
): List<AppItem> = apps.filter {
|
||||
!it.isSystem || it.packageName in selectedPackages
|
||||
}
|
||||
|
||||
internal fun sortAppsForRoutingList(
|
||||
apps: List<AppItem>,
|
||||
selectedPackages: Set<String>,
|
||||
): List<AppItem> = apps.sortedWith(
|
||||
compareBy<AppItem>(
|
||||
{ it.packageName !in selectedPackages },
|
||||
{ it.name.lowercase() },
|
||||
{ it.packageName.lowercase() },
|
||||
),
|
||||
)
|
||||
|
||||
private fun PackageManager.getInstalledApplicationsCompat(): List<ApplicationInfo> =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
getInstalledApplications(
|
||||
PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA.toLong()),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
getInstalledApplications(PackageManager.GET_META_DATA)
|
||||
}
|
||||
|
||||
private fun PackageManager.getApplicationInfoCompat(packageName: String): ApplicationInfo? =
|
||||
runCatching {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
getApplicationInfo(
|
||||
packageName,
|
||||
PackageManager.ApplicationInfoFlags.of(PackageManager.GET_META_DATA.toLong()),
|
||||
)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
getApplicationInfo(packageName, PackageManager.GET_META_DATA)
|
||||
}
|
||||
}.getOrNull()
|
||||
|
||||
private fun PackageManager.queryIntentActivitiesCompat(intent: Intent): List<ResolveInfo> =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
queryIntentActivities(intent, PackageManager.ResolveInfoFlags.of(0L))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
queryIntentActivities(intent, 0)
|
||||
}
|
||||
|
||||
private suspend fun writeRoutingFile(context: Context, uri: Uri, text: String) =
|
||||
withContext(Dispatchers.IO) {
|
||||
context.contentResolver.openOutputStream(uri, "wt")?.bufferedWriter(Charsets.UTF_8)?.use {
|
||||
|
||||
@@ -18,6 +18,7 @@ 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.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
@@ -217,6 +218,12 @@ 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)
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
@@ -229,6 +236,7 @@ fun FloatingToolbar(
|
||||
onClick = { isExpanded = !isExpanded },
|
||||
modifier = Modifier
|
||||
.offset { IntOffset(animatedTabXPx.roundToInt(), offsetY.roundToInt()) }
|
||||
.remoteCompactFocus(tabShape)
|
||||
.onGloballyPositioned { coordinates ->
|
||||
tabHeightPx = coordinates.size.height.toFloat()
|
||||
}
|
||||
@@ -242,10 +250,7 @@ fun FloatingToolbar(
|
||||
}
|
||||
)
|
||||
},
|
||||
shape = if (isRightSide)
|
||||
RoundedCornerShape(topStart = 14.dp, bottomStart = 14.dp)
|
||||
else
|
||||
RoundedCornerShape(topEnd = 14.dp, bottomEnd = 14.dp),
|
||||
shape = tabShape,
|
||||
color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.9f),
|
||||
shadowElevation = 0.dp,
|
||||
tonalElevation = 0.dp,
|
||||
@@ -282,6 +287,7 @@ fun FloatingToolbar(
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.fillMaxWidth()
|
||||
.focusGroup()
|
||||
.animateContentSize(animationSpec = spring(stiffness = Spring.StiffnessMediumLow))
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp)
|
||||
@@ -324,6 +330,7 @@ fun FloatingToolbar(
|
||||
modifier = Modifier
|
||||
.widthIn(min = 72.dp, max = 180.dp)
|
||||
.clip(profileShape)
|
||||
.remoteFocusOutline(profileShape)
|
||||
.combinedClickable(
|
||||
onClick = {
|
||||
onActiveProfileChange(profile)
|
||||
@@ -378,11 +385,12 @@ fun FloatingToolbar(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.remoteFocusOutline(RoundedCornerShape(8.dp))
|
||||
.clickable {
|
||||
enableTrustedWifiAfterSetup = false
|
||||
showTrustedWifiSettings = true
|
||||
}
|
||||
.padding(end = 10.dp)
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp)
|
||||
) {
|
||||
Text(
|
||||
"Доверенные сети Wi‑Fi",
|
||||
@@ -426,19 +434,24 @@ fun FloatingToolbar(
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.scale(0.85f)
|
||||
modifier = Modifier.remoteSwitchFocus().scale(0.85f)
|
||||
)
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clickable { showSleepTimerSettings = true }
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Column(modifier = Modifier.weight(1f).padding(end = 10.dp)) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.remoteFocusOutline(RoundedCornerShape(8.dp))
|
||||
.clickable { showSleepTimerSettings = true }
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp)
|
||||
) {
|
||||
Text(
|
||||
"Экономия батареи во сне",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
@@ -511,7 +524,7 @@ fun FloatingToolbar(
|
||||
}
|
||||
}
|
||||
},
|
||||
modifier = Modifier.scale(0.85f)
|
||||
modifier = Modifier.remoteSwitchFocus().scale(0.85f)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -556,7 +569,7 @@ fun FloatingToolbar(
|
||||
}
|
||||
},
|
||||
enabled = adminModeAllowed,
|
||||
modifier = Modifier.scale(0.85f)
|
||||
modifier = Modifier.remoteSwitchFocus(enabled = adminModeAllowed).scale(0.85f)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -623,7 +636,7 @@ fun FloatingToolbar(
|
||||
checked = showDynamicColorOn,
|
||||
onCheckedChange = { onDynamicColorChange(it) },
|
||||
enabled = supportsDynamicColor,
|
||||
modifier = Modifier.scale(0.8f)
|
||||
modifier = Modifier.remoteSwitchFocus(enabled = supportsDynamicColor).scale(0.8f)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -679,7 +692,9 @@ fun FloatingToolbar(
|
||||
onClick = { onFingerprintChange(fp) },
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
color = if (selected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
|
||||
modifier = Modifier.weight(1f)
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.remoteFocusOutline(RoundedCornerShape(8.dp))
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.padding(vertical = 10.dp),
|
||||
@@ -711,6 +726,7 @@ fun FloatingToolbar(
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteFocusOutline(RoundedCornerShape(8.dp))
|
||||
.clickable { showVkClientSettings = true }
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
@@ -1121,7 +1137,9 @@ private fun ThemeOption(
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = if (selected) MaterialTheme.colorScheme.primaryContainer
|
||||
else MaterialTheme.colorScheme.surface,
|
||||
modifier = modifier.height(42.dp)
|
||||
modifier = modifier
|
||||
.height(42.dp)
|
||||
.remoteFocusOutline(RoundedCornerShape(24.dp), focusedScale = 1.04f)
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -1151,6 +1169,7 @@ fun PaletteCircle(
|
||||
.size(30.dp)
|
||||
.clip(CircleShape)
|
||||
.background(Color(colorHex))
|
||||
.remoteCompactFocus(CircleShape)
|
||||
.clickable { onClick(paletteId) }
|
||||
.then(
|
||||
if (isSelected) Modifier.border(3.dp, MaterialTheme.colorScheme.primary, CircleShape)
|
||||
|
||||
@@ -9,7 +9,6 @@ import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.os.PowerManager
|
||||
import android.os.StatFs
|
||||
@@ -32,6 +31,7 @@ import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
@@ -522,6 +522,7 @@ fun InfoTab(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.fillMaxWidth()
|
||||
.focusGroup()
|
||||
.padding(start = 16.dp, end = 16.dp, top = 0.dp, bottom = 28.dp)
|
||||
.verticalScroll(infoScrollState),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
@@ -985,6 +986,7 @@ private fun QuestionDestinationDialog(
|
||||
onGitHubClick: () -> Unit,
|
||||
onRemoteActionClick: (RemoteUiAction) -> Unit,
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
@@ -998,7 +1000,11 @@ private fun QuestionDestinationDialog(
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
tonalElevation = 8.dp,
|
||||
shadowElevation = 18.dp,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(max = 560.dp),
|
||||
modifier = (if (television) {
|
||||
Modifier.televisionDialogWidth(television)
|
||||
} else {
|
||||
Modifier.fillMaxWidth()
|
||||
}).heightIn(max = 560.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(20.dp),
|
||||
@@ -1796,6 +1802,7 @@ private fun ExpandableSectionCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(24.dp))
|
||||
.remoteFocusOutline(RoundedCornerShape(24.dp))
|
||||
.clickable(onClick = onToggle)
|
||||
.padding(vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
@@ -1873,6 +1880,7 @@ private fun InfoActionTile(
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = modifier
|
||||
.clip(RoundedCornerShape(24.dp))
|
||||
.remoteFocusOutline(RoundedCornerShape(24.dp))
|
||||
.clickable(onClick = onClick)
|
||||
) {
|
||||
Column(
|
||||
@@ -1918,6 +1926,7 @@ private fun WideActionTile(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(24.dp))
|
||||
.remoteFocusOutline(RoundedCornerShape(24.dp))
|
||||
.clickable(onClick = onClick)
|
||||
) {
|
||||
Row(
|
||||
@@ -1970,6 +1979,7 @@ private fun ProjectLinkRow(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(24.dp))
|
||||
.remoteFocusOutline(RoundedCornerShape(24.dp))
|
||||
.clickable(onClick = onClick)
|
||||
) {
|
||||
Row(
|
||||
@@ -2156,7 +2166,7 @@ private suspend fun buildSupportReportSummary(context: Context, settingsStore: S
|
||||
val updateInstallPermission = diagnosticText {
|
||||
context.packageManager.canRequestPackageInstalls()
|
||||
}
|
||||
val vpnPermission = diagnosticText { VpnService.prepare(context) == null }
|
||||
val vpnPermission = "проверяется только при явном подключении"
|
||||
val displayMetrics = context.resources.displayMetrics
|
||||
val screenSummary = diagnosticText {
|
||||
"${displayMetrics.widthPixels}×${displayMetrics.heightPixels}, " +
|
||||
|
||||
@@ -6,6 +6,7 @@ import android.content.Context
|
||||
import android.widget.Toast
|
||||
import androidx.compose.animation.core.*
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
@@ -50,7 +51,7 @@ fun LogsTab(
|
||||
firstVisibleItemScrollOffset
|
||||
)
|
||||
|
||||
Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
|
||||
Column(modifier = Modifier.fillMaxSize().focusGroup().padding(16.dp)) {
|
||||
// Toolbar
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
@@ -85,7 +86,15 @@ fun LogsTab(
|
||||
verticalArrangement = Arrangement.spacedBy(0.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteToggleableRow(value = loggingEnabled) { enabled ->
|
||||
scope.launch {
|
||||
settingsStore.saveLoggingEnabled(enabled)
|
||||
if (!enabled) TunnelManager.clearLogs()
|
||||
}
|
||||
}
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
@@ -98,14 +107,7 @@ fun LogsTab(
|
||||
)
|
||||
Switch(
|
||||
checked = loggingEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
scope.launch {
|
||||
settingsStore.saveLoggingEnabled(enabled)
|
||||
if (!enabled) {
|
||||
TunnelManager.clearLogs()
|
||||
}
|
||||
}
|
||||
}
|
||||
onCheckedChange = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -171,7 +173,10 @@ fun LogLine(entry: LogEntry, sessionActive: Boolean) {
|
||||
)
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteReadableItem(RoundedCornerShape(8.dp))
|
||||
.padding(horizontal = 4.dp, vertical = 4.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Surface(
|
||||
|
||||
@@ -29,6 +29,7 @@ internal val QuickExclusionExactPackages = setOf(
|
||||
|
||||
// Соцсети, связь и магазины приложений
|
||||
"com.vkontakte.android",
|
||||
"com.vk.calls",
|
||||
"com.vk.im",
|
||||
"com.vk.vkvideo",
|
||||
"ru.vk.music",
|
||||
|
||||
@@ -118,13 +118,19 @@ internal fun RtNetworkSettingsDialog(
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
IconButton(onClick = onShowRtHelp) {
|
||||
IconButton(
|
||||
onClick = onShowRtHelp,
|
||||
modifier = Modifier.remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Инструкция по режиму Сеть РТ",
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
@@ -196,7 +202,7 @@ internal fun RtNetworkSettingsDialog(
|
||||
Text("MASQUE", fontWeight = FontWeight.SemiBold)
|
||||
IconButton(
|
||||
onClick = onShowMasqueHelp,
|
||||
modifier = Modifier.size(32.dp),
|
||||
modifier = Modifier.size(32.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
@@ -215,6 +221,7 @@ internal fun RtNetworkSettingsDialog(
|
||||
checked = rtMasque,
|
||||
enabled = controlsEnabled,
|
||||
onCheckedChange = onRtMasqueChange,
|
||||
modifier = Modifier.remoteSwitchFocus(enabled = controlsEnabled),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -230,7 +237,7 @@ internal fun RtNetworkSettingsDialog(
|
||||
Text("Через сервер", fontWeight = FontWeight.SemiBold)
|
||||
IconButton(
|
||||
onClick = onShowServerHelp,
|
||||
modifier = Modifier.size(32.dp),
|
||||
modifier = Modifier.size(32.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
@@ -253,6 +260,9 @@ internal fun RtNetworkSettingsDialog(
|
||||
checked = rtMasqueServerBootstrap,
|
||||
enabled = controlsEnabled && rtMasque && serverAccess.available,
|
||||
onCheckedChange = onServerBootstrapChange,
|
||||
modifier = Modifier.remoteSwitchFocus(
|
||||
enabled = controlsEnabled && rtMasque && serverAccess.available,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -620,6 +620,7 @@ fun ServerClientsSection(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(RoundedCornerShape(24.dp))
|
||||
.remoteFocusOutline(RoundedCornerShape(24.dp))
|
||||
.clickable {
|
||||
val willExpand = !expanded
|
||||
onExpandedChange(willExpand)
|
||||
@@ -766,6 +767,7 @@ fun ServerClientsSection(
|
||||
modifier = Modifier
|
||||
.width(if (activeFilterCount > 0) 72.dp else 56.dp)
|
||||
.requiredHeight(56.dp)
|
||||
.remoteFocusOutline(RoundedCornerShape(18.dp))
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
@@ -2246,7 +2248,9 @@ private fun StatusChip(status: String) {
|
||||
"expired" -> MaterialTheme.colorScheme.onErrorContainer
|
||||
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
},
|
||||
modifier = Modifier.size(30.dp)
|
||||
modifier = Modifier
|
||||
.size(30.dp)
|
||||
.remoteFocusOutline(CircleShape)
|
||||
) {
|
||||
Box(contentAlignment = Alignment.Center) {
|
||||
Icon(
|
||||
@@ -2507,6 +2511,8 @@ private fun ClientImportConfirmDialog(
|
||||
onDismiss: () -> Unit,
|
||||
onConfirm: () -> Unit
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
val expired = payload.expiresAt > 0 && payload.expiresAt <= System.currentTimeMillis() / 1000L
|
||||
val errors = buildList {
|
||||
if (passwordConflict) add("На новом сервере уже есть клиент с таким паролем.")
|
||||
@@ -2521,7 +2527,9 @@ private fun ClientImportConfirmDialog(
|
||||
title = { DialogTitle("Проверка импорта", onDismiss) },
|
||||
text = {
|
||||
Column(
|
||||
modifier = Modifier.verticalScroll(rememberScrollState()),
|
||||
modifier = Modifier
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
InfoLine("Клиент", payload.label.ifBlank { "Без имени" })
|
||||
|
||||
@@ -22,6 +22,8 @@ import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.focusGroup
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.layout.*
|
||||
@@ -64,6 +66,11 @@ import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.input.pointer.PointerEventPass
|
||||
import androidx.compose.ui.input.pointer.PointerEventType
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
@@ -73,6 +80,10 @@ import androidx.compose.ui.text.TextLinkStyles
|
||||
import androidx.compose.ui.text.buildAnnotatedString
|
||||
import androidx.compose.ui.text.rememberTextMeasurer
|
||||
import androidx.compose.ui.text.withLink
|
||||
import androidx.compose.ui.semantics.ProgressBarRangeInfo
|
||||
import androidx.compose.ui.semantics.progressBarRangeInfo
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.semantics.setProgress
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
@@ -101,7 +112,8 @@ import com.wdtt.plus.DEFAULT_VK_CLIENT_IDS
|
||||
import com.wdtt.plus.DEFAULT_RT_TURN_SNI
|
||||
import com.wdtt.plus.ManlCaptchaWebViewManager
|
||||
import com.wdtt.plus.MainActivity
|
||||
import com.wdtt.plus.MANAGED_CONFIG_FIRST_START_EXTRA
|
||||
import com.wdtt.plus.CONFIG_FIRST_START_EXTRA
|
||||
import com.wdtt.plus.NativeClientStartupSecrets
|
||||
import com.wdtt.plus.RemoteContinuation
|
||||
import com.wdtt.plus.RemoteContinuationLauncher
|
||||
import com.wdtt.plus.RemoteActionCatalogGateway
|
||||
@@ -120,7 +132,8 @@ import com.wdtt.plus.TUNNEL_PROFILE_INDEX_EXTRA
|
||||
import com.wdtt.plus.VpnDnsSettingsSnapshot
|
||||
import com.wdtt.plus.normalizeTunnelWorkerCount
|
||||
import com.wdtt.plus.normalizeRtTurnSni
|
||||
import com.wdtt.plus.shouldUseManagedConfigFirstStart
|
||||
import com.wdtt.plus.nativeClientStartupConfigLine
|
||||
import com.wdtt.plus.shouldUseConfigFirstStart
|
||||
import com.wdtt.plus.TrustedWifiManager
|
||||
import com.wdtt.plus.VkJoinLink
|
||||
import com.wdtt.plus.WDTTColors
|
||||
@@ -370,6 +383,7 @@ fun SettingsTabContent(
|
||||
|
||||
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
|
||||
val activeWorkers by TunnelManager.activeWorkers.collectAsStateWithLifecycle()
|
||||
val vpnInterfaceUp by TunnelManager.vpnInterfaceUp.collectAsStateWithLifecycle()
|
||||
val warpResetBlockedMessage = "Для сброса отключите VPN"
|
||||
val tunnelTransition by TunnelManager.transition.collectAsStateWithLifecycle()
|
||||
val trustedWifiState by TrustedWifiManager.state.collectAsStateWithLifecycle()
|
||||
@@ -660,11 +674,8 @@ fun SettingsTabContent(
|
||||
putExtra("custom_vk_client_secret", customVkClientSecret)
|
||||
putExtra("profile_max_workers", profileMaxWorkers)
|
||||
putExtra(
|
||||
MANAGED_CONFIG_FIRST_START_EXTRA,
|
||||
shouldUseManagedConfigFirstStart(
|
||||
remoteManaged = remoteManagedProfile,
|
||||
profileMaxWorkers = profileMaxWorkers,
|
||||
),
|
||||
CONFIG_FIRST_START_EXTRA,
|
||||
shouldUseConfigFirstStart(),
|
||||
)
|
||||
putExtra(TUNNEL_PROFILE_INDEX_EXTRA, activeProfile)
|
||||
}
|
||||
@@ -1145,6 +1156,7 @@ fun SettingsTabContent(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.focusGroup()
|
||||
.verticalScroll(scrollState)
|
||||
.padding(16.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
@@ -1324,6 +1336,7 @@ fun SettingsTabContent(
|
||||
waiting = trustedWifiWaiting,
|
||||
transition = tunnelTransition,
|
||||
activeWorkers = activeWorkers,
|
||||
vpnInterfaceUp = vpnInterfaceUp,
|
||||
targetWorkers = currentWorkers.toInt(),
|
||||
cooldownActive = cooldownActive,
|
||||
underlyingNetworkAvailable = underlyingNetworkAvailable,
|
||||
@@ -2244,7 +2257,10 @@ private fun TunnelLaunchParametersDialog(
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
@@ -2287,7 +2303,7 @@ private fun TunnelLaunchParametersDialog(
|
||||
)
|
||||
IconButton(
|
||||
onClick = onPowerHelp,
|
||||
modifier = Modifier.size(28.dp),
|
||||
modifier = Modifier.size(28.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
@@ -2392,7 +2408,9 @@ private fun LaunchParameterSwitchRow(
|
||||
onTitleClick: (() -> Unit)? = null,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 8.dp, vertical = 8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
) {
|
||||
@@ -2403,17 +2421,27 @@ private fun LaunchParameterSwitchRow(
|
||||
) {
|
||||
Text(
|
||||
title,
|
||||
modifier = if (onTitleClick != null) {
|
||||
Modifier.clickable(onClick = onTitleClick).padding(vertical = 10.dp)
|
||||
} else {
|
||||
Modifier
|
||||
},
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.then(if (onTitleClick != null) {
|
||||
Modifier
|
||||
.remoteFocusOutline(RoundedCornerShape(8.dp))
|
||||
.clickable(onClick = onTitleClick)
|
||||
} else {
|
||||
Modifier.remoteToggleableRow(
|
||||
value = checked,
|
||||
enabled = enabled,
|
||||
shape = RoundedCornerShape(8.dp),
|
||||
onValueChange = onCheckedChange,
|
||||
)
|
||||
})
|
||||
.padding(horizontal = 8.dp, vertical = 10.dp),
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
)
|
||||
IconButton(
|
||||
onClick = onHelp,
|
||||
modifier = Modifier.size(28.dp),
|
||||
modifier = Modifier.size(28.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
@@ -2427,6 +2455,7 @@ private fun LaunchParameterSwitchRow(
|
||||
checked = checked,
|
||||
enabled = enabled,
|
||||
onCheckedChange = onCheckedChange,
|
||||
modifier = Modifier.remoteSwitchFocus(enabled = enabled),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -2437,6 +2466,7 @@ private fun AnimatedTunnelPowerButton(
|
||||
waiting: Boolean,
|
||||
transition: TunnelTransition,
|
||||
activeWorkers: Int,
|
||||
vpnInterfaceUp: Boolean,
|
||||
targetWorkers: Int,
|
||||
cooldownActive: Boolean,
|
||||
underlyingNetworkAvailable: Boolean,
|
||||
@@ -2458,6 +2488,7 @@ private fun AnimatedTunnelPowerButton(
|
||||
starting = isStarting,
|
||||
stopping = isStopping,
|
||||
activeWorkers = activeWorkers,
|
||||
vpnInterfaceUp = vpnInterfaceUp,
|
||||
underlyingNetworkAvailable = underlyingNetworkAvailable,
|
||||
hasConnectionError = connectionErrorTitle != null,
|
||||
cooldownActive = cooldownActive,
|
||||
@@ -2752,6 +2783,7 @@ private fun AnimatedTunnelPowerButton(
|
||||
modifier = Modifier
|
||||
.size(96.dp)
|
||||
.clip(CircleShape)
|
||||
.remoteFocusOutline(CircleShape, enabled = enabled)
|
||||
.clickable(
|
||||
enabled = enabled,
|
||||
onClick = {
|
||||
@@ -2825,6 +2857,7 @@ internal fun tunnelPowerVisualState(
|
||||
starting: Boolean,
|
||||
stopping: Boolean,
|
||||
activeWorkers: Int,
|
||||
vpnInterfaceUp: Boolean,
|
||||
underlyingNetworkAvailable: Boolean,
|
||||
hasConnectionError: Boolean,
|
||||
cooldownActive: Boolean,
|
||||
@@ -2833,7 +2866,7 @@ internal fun tunnelPowerVisualState(
|
||||
waitingForTrustedWifi -> TunnelPowerVisualState.WaitingForTrustedWifi
|
||||
(starting || running) && !underlyingNetworkAvailable -> TunnelPowerVisualState.NoNetwork
|
||||
hasConnectionError -> TunnelPowerVisualState.Error
|
||||
starting || running && activeWorkers <= 0 -> TunnelPowerVisualState.Connecting
|
||||
starting || running && (activeWorkers <= 0 || !vpnInterfaceUp) -> TunnelPowerVisualState.Connecting
|
||||
running -> TunnelPowerVisualState.Connected
|
||||
cooldownActive -> TunnelPowerVisualState.CoolingDown
|
||||
else -> TunnelPowerVisualState.Off
|
||||
@@ -2940,13 +2973,20 @@ private fun SettingsHelpDialog(
|
||||
secondaryActionEnabled: Boolean = true,
|
||||
onSecondaryActionDisabled: (() -> Unit)? = null,
|
||||
) {
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = !television),
|
||||
) {
|
||||
BoxWithConstraints(
|
||||
modifier = Modifier.fillMaxSize().padding(8.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.heightIn(max = maxHeight * 0.92f),
|
||||
modifier = Modifier
|
||||
.televisionDialogWidth(television)
|
||||
.heightIn(max = maxHeight * 0.92f),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
@@ -2956,7 +2996,8 @@ private fun SettingsHelpDialog(
|
||||
modifier = Modifier
|
||||
.padding(22.dp)
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState()),
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Row(
|
||||
@@ -2971,7 +3012,10 @@ private fun SettingsHelpDialog(
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
@@ -3017,6 +3061,7 @@ private fun SettingsHelpDialog(
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.matchParentSize()
|
||||
.remoteFocusOutline(RoundedCornerShape(16.dp))
|
||||
.clickable(onClick = onSecondaryActionDisabled),
|
||||
)
|
||||
}
|
||||
@@ -3045,13 +3090,20 @@ private fun PowerHelpDialog(
|
||||
profileMaxWorkers: Int,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = !television),
|
||||
) {
|
||||
BoxWithConstraints(
|
||||
modifier = Modifier.fillMaxSize().padding(8.dp),
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier.heightIn(max = maxHeight * 0.92f),
|
||||
modifier = Modifier
|
||||
.televisionDialogWidth(television)
|
||||
.heightIn(max = maxHeight * 0.92f),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
@@ -3061,7 +3113,8 @@ private fun PowerHelpDialog(
|
||||
modifier = Modifier
|
||||
.padding(22.dp)
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState()),
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Row(
|
||||
@@ -3075,7 +3128,10 @@ private fun PowerHelpDialog(
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
@@ -3197,6 +3253,7 @@ private fun CompactSteppedSlider(
|
||||
val currentValue by rememberUpdatedState(value)
|
||||
val currentOnValueChange by rememberUpdatedState(onValueChange)
|
||||
val currentOnValueChangeFinished by rememberUpdatedState(onValueChangeFinished)
|
||||
var remoteValue by remember(value) { mutableFloatStateOf(value) }
|
||||
|
||||
fun snap(raw: Float): Float {
|
||||
val min = valueRange.start
|
||||
@@ -3214,7 +3271,49 @@ private fun CompactSteppedSlider(
|
||||
|
||||
Canvas(
|
||||
modifier = modifier
|
||||
.height(30.dp)
|
||||
.height(40.dp)
|
||||
.remoteFocusOutline(
|
||||
shape = RoundedCornerShape(20.dp),
|
||||
enabled = enabled,
|
||||
)
|
||||
.onKeyEvent { event ->
|
||||
if (!enabled || event.type != KeyEventType.KeyDown) return@onKeyEvent false
|
||||
val direction = when (event.key) {
|
||||
Key.DirectionLeft -> -1
|
||||
Key.DirectionRight -> 1
|
||||
else -> return@onKeyEvent false
|
||||
}
|
||||
val selected = steppedSliderValue(
|
||||
value = remoteValue,
|
||||
range = valueRange,
|
||||
stepSize = stepSize,
|
||||
direction = direction,
|
||||
)
|
||||
if (selected != remoteValue) {
|
||||
remoteValue = selected
|
||||
currentOnValueChange(selected)
|
||||
currentOnValueChangeFinished(selected)
|
||||
}
|
||||
true
|
||||
}
|
||||
.semantics {
|
||||
progressBarRangeInfo = ProgressBarRangeInfo(
|
||||
current = value,
|
||||
range = valueRange,
|
||||
steps = (((valueRange.endInclusive - valueRange.start) / stepSize).roundToInt() - 1)
|
||||
.coerceAtLeast(0),
|
||||
)
|
||||
if (enabled) {
|
||||
setProgress { requested ->
|
||||
val selected = snap(requested)
|
||||
remoteValue = selected
|
||||
currentOnValueChange(selected)
|
||||
currentOnValueChangeFinished(selected)
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
.focusable(enabled = enabled)
|
||||
.pointerInput(enabled, valueRange, stepSize) {
|
||||
if (!enabled) return@pointerInput
|
||||
detectTapGestures { offset ->
|
||||
@@ -3283,9 +3382,22 @@ private fun CompactSteppedSlider(
|
||||
}
|
||||
}
|
||||
|
||||
internal fun steppedSliderValue(
|
||||
value: Float,
|
||||
range: ClosedFloatingPointRange<Float>,
|
||||
stepSize: Float,
|
||||
direction: Int,
|
||||
): Float {
|
||||
if (stepSize <= 0f || direction == 0) return value.coerceIn(range.start, range.endInclusive)
|
||||
val steps = ((value - range.start) / stepSize).roundToInt() + if (direction < 0) -1 else 1
|
||||
return (range.start + steps * stepSize).coerceIn(range.start, range.endInclusive)
|
||||
}
|
||||
|
||||
// ═══ Important Info Dialog ═══
|
||||
@Composable
|
||||
fun ImportantInfoDialog(onDismiss: () -> Unit) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
@@ -3295,8 +3407,11 @@ fun ImportantInfoDialog(onDismiss: () -> Unit) {
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.95f)
|
||||
modifier = (if (television) {
|
||||
Modifier.televisionDialogWidth(television)
|
||||
} else {
|
||||
Modifier.fillMaxWidth(0.95f)
|
||||
})
|
||||
.heightIn(max = maxHeight * 0.92f),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
@@ -3306,7 +3421,8 @@ fun ImportantInfoDialog(onDismiss: () -> Unit) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(24.dp)
|
||||
.verticalScroll(rememberScrollState())
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
@@ -3314,7 +3430,10 @@ fun ImportantInfoDialog(onDismiss: () -> Unit) {
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text("Важная информация", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, null)
|
||||
}
|
||||
}
|
||||
@@ -3758,7 +3877,12 @@ private fun UserManualConnectionDialog(
|
||||
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteToggleableRow(value = manualPortsEnabled) {
|
||||
manualPortsEnabled = it
|
||||
}
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
@@ -3772,7 +3896,7 @@ private fun UserManualConnectionDialog(
|
||||
}
|
||||
Switch(
|
||||
checked = manualPortsEnabled,
|
||||
onCheckedChange = { manualPortsEnabled = it }
|
||||
onCheckedChange = null,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3898,7 +4022,7 @@ private fun UserWdttLinkDialog(
|
||||
if (remoteUpdateOnly) {
|
||||
IconButton(
|
||||
onClick = { showRemoteUpdateHelp = true },
|
||||
modifier = Modifier.size(40.dp),
|
||||
modifier = Modifier.size(40.dp).remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
@@ -4046,6 +4170,8 @@ private fun RemoteUpdateHelpDialog(
|
||||
cachedAction: CachedRemoteAction,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
@@ -4055,9 +4181,11 @@ private fun RemoteUpdateHelpDialog(
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.92f)
|
||||
.widthIn(max = 540.dp)
|
||||
modifier = (if (television) {
|
||||
Modifier.televisionDialogWidth(television)
|
||||
} else {
|
||||
Modifier.fillMaxWidth(0.92f).widthIn(max = 540.dp)
|
||||
})
|
||||
.heightIn(max = maxHeight * 0.92f),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
@@ -4065,7 +4193,10 @@ private fun RemoteUpdateHelpDialog(
|
||||
tonalElevation = 10.dp,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(20.dp).verticalScroll(rememberScrollState()),
|
||||
modifier = Modifier
|
||||
.padding(20.dp)
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp),
|
||||
) {
|
||||
Row(
|
||||
@@ -4079,7 +4210,10 @@ private fun RemoteUpdateHelpDialog(
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.Default.Close,
|
||||
contentDescription = "Вернуться к обновлению маршрута",
|
||||
@@ -4769,7 +4903,7 @@ fun HashesDialog(
|
||||
Spacer(Modifier.width(4.dp))
|
||||
IconButton(
|
||||
onClick = { showHashesHelp = true },
|
||||
modifier = Modifier.size(36.dp)
|
||||
modifier = Modifier.size(36.dp).remoteHelpFocus()
|
||||
) {
|
||||
Surface(
|
||||
shape = CircleShape,
|
||||
@@ -5111,6 +5245,8 @@ private fun VkHashesInstructionDialog(
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val television = isTelevisionDevice()
|
||||
val scrollState = rememberScrollState()
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
@@ -5120,9 +5256,11 @@ private fun VkHashesInstructionDialog(
|
||||
contentAlignment = Alignment.Center
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.96f)
|
||||
.widthIn(max = 680.dp)
|
||||
modifier = (if (television) {
|
||||
Modifier.televisionDialogWidth(television)
|
||||
} else {
|
||||
Modifier.fillMaxWidth(0.96f).widthIn(max = 680.dp)
|
||||
})
|
||||
.heightIn(max = maxHeight * 0.92f),
|
||||
shape = RoundedCornerShape(24.dp),
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
@@ -5134,7 +5272,8 @@ private fun VkHashesInstructionDialog(
|
||||
modifier = Modifier
|
||||
.padding(22.dp)
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState()),
|
||||
.verticalScroll(scrollState)
|
||||
.tvDpadScrollable(scrollState, television),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
) {
|
||||
Row(
|
||||
@@ -5274,7 +5413,10 @@ private fun VkHashesInstructionDialog(
|
||||
}
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.align(Alignment.TopEnd).padding(top = 10.dp, end = 10.dp)
|
||||
modifier = Modifier
|
||||
.align(Alignment.TopEnd)
|
||||
.padding(top = 10.dp, end = 10.dp)
|
||||
.remoteIconButtonFocus()
|
||||
) {
|
||||
Surface(
|
||||
shape = CircleShape,
|
||||
@@ -5532,8 +5674,7 @@ private suspend fun checkVkHashes(
|
||||
val command = mutableListOf(
|
||||
binaryPath,
|
||||
"-check-hashes",
|
||||
"-vk",
|
||||
hashes.joinToString(",") { it.second },
|
||||
"-startup-config-stdin=true",
|
||||
"-captcha-mode",
|
||||
captchaMode,
|
||||
"-vkcalls-preflight=$vkCallsPreflight",
|
||||
@@ -5551,16 +5692,21 @@ private suspend fun checkVkHashes(
|
||||
.redirectErrorStream(true)
|
||||
.apply {
|
||||
environment()["LD_LIBRARY_PATH"] = context.applicationInfo.nativeLibraryDir
|
||||
if (customVkCredentialsEnabled) {
|
||||
environment()["WDTT_CUSTOM_VK_CLIENT_ID"] = customVkClientId
|
||||
environment()["WDTT_CUSTOM_VK_CLIENT_SECRET"] = customVkClientSecret
|
||||
} else {
|
||||
environment().remove("WDTT_CUSTOM_VK_CLIENT_ID")
|
||||
environment().remove("WDTT_CUSTOM_VK_CLIENT_SECRET")
|
||||
}
|
||||
environment().remove("WDTT_CUSTOM_VK_CLIENT_ID")
|
||||
environment().remove("WDTT_CUSTOM_VK_CLIENT_SECRET")
|
||||
}
|
||||
.start()
|
||||
|
||||
val startupLine = nativeClientStartupConfigLine(
|
||||
NativeClientStartupSecrets(
|
||||
vkHashes = hashes.joinToString(",") { it.second },
|
||||
customVkClientId = if (customVkCredentialsEnabled) customVkClientId else "",
|
||||
customVkClientSecret = if (customVkCredentialsEnabled) customVkClientSecret else "",
|
||||
)
|
||||
)
|
||||
process.outputStream.write("$startupLine\n".toByteArray(Charsets.UTF_8))
|
||||
process.outputStream.flush()
|
||||
|
||||
val byOrder = hashes.mapIndexed { order, pair -> order + 1 to pair }.toMap()
|
||||
val parsed = mutableMapOf<Int, HashCheckResult>()
|
||||
val startedAutoWebView = !TunnelManager.running.value
|
||||
@@ -5825,7 +5971,10 @@ fun SecretsDialog(
|
||||
if (allowPortsSelection) {
|
||||
Spacer(modifier = Modifier.height(12.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteToggleableRow(value = portsEnabled) { portsEnabled = it }
|
||||
.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.SpaceBetween
|
||||
) {
|
||||
@@ -5843,7 +5992,7 @@ fun SecretsDialog(
|
||||
}
|
||||
Switch(
|
||||
checked = portsEnabled,
|
||||
onCheckedChange = { portsEnabled = it }
|
||||
onCheckedChange = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.foundation.Canvas
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.gestures.detectDragGestures
|
||||
import androidx.compose.foundation.gestures.detectTapGestures
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
@@ -12,6 +13,7 @@ import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
@@ -45,6 +47,11 @@ import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.StrokeCap
|
||||
import androidx.compose.ui.graphics.drawscope.Stroke
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.semantics.contentDescription
|
||||
import androidx.compose.ui.semantics.ProgressBarRangeInfo
|
||||
@@ -71,6 +78,9 @@ import kotlin.math.sin
|
||||
internal fun adjustSleepTimerHours(totalMinutes: Int, hoursDelta: Int): Int =
|
||||
normalizeSleepPauseDelayMinutes(totalMinutes + hoursDelta * 60)
|
||||
|
||||
internal fun adjustSleepTimerMinutes(totalMinutes: Int, direction: Int): Int =
|
||||
normalizeSleepPauseDelayMinutes(totalMinutes + direction.coerceIn(-1, 1) * 5)
|
||||
|
||||
internal fun replaceSleepTimerMinuteComponent(totalMinutes: Int, minute: Int): Int {
|
||||
val normalized = normalizeSleepPauseDelayMinutes(totalMinutes)
|
||||
val hours = (normalized / 60).coerceAtMost(23)
|
||||
@@ -104,6 +114,7 @@ internal fun SleepTimerDialog(
|
||||
onApply: (SleepBatteryMode, Int, Int) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val television = isTelevisionDevice()
|
||||
var selectedModeName by rememberSaveable(initialMode) { mutableStateOf(initialMode.name) }
|
||||
var pauseDelayMinutes by rememberSaveable(initialPauseDelayMinutes) {
|
||||
mutableIntStateOf(normalizeSleepPauseDelayMinutes(initialPauseDelayMinutes))
|
||||
@@ -127,132 +138,141 @@ internal fun SleepTimerDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 20.dp),
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
tonalElevation = 8.dp,
|
||||
shadowElevation = 12.dp,
|
||||
Box(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 22.dp, vertical = 20.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
Surface(
|
||||
modifier = if (television) {
|
||||
Modifier.televisionDialogWidth(television, fraction = 0.72f, maxWidth = 820.dp)
|
||||
} else {
|
||||
Modifier.fillMaxWidth().padding(horizontal = 20.dp)
|
||||
},
|
||||
shape = RoundedCornerShape(28.dp),
|
||||
tonalElevation = 8.dp,
|
||||
shadowElevation = 12.dp,
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = "Таймер сна",
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.align(Alignment.CenterEnd),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Close,
|
||||
contentDescription = "Закрыть таймер сна",
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 80.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
.padding(horizontal = 22.dp, vertical = 20.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
text = when (selectedMode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> if (totalMinutes == 0) {
|
||||
"VPN отключится сразу после выключения экрана. Интернет будет работать напрямую до включения экрана"
|
||||
} else {
|
||||
"VPN отключится через выбранное время. После отключения интернет будет работать напрямую до включения экрана"
|
||||
}
|
||||
SleepBatteryMode.TIMED_PAUSE -> if (totalMinutes == 0) {
|
||||
"При значении 0 мин VPN останется активным после выключения экрана"
|
||||
} else {
|
||||
"VPN отключится сразу и включится примерно через выбранное время. Во время паузы интернет работает напрямую"
|
||||
}
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
SleepBatteryMode.entries.forEachIndexed { index, mode ->
|
||||
SegmentedButton(
|
||||
selected = selectedMode == mode,
|
||||
onClick = { selectedModeName = mode.name },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = SleepBatteryMode.entries.size,
|
||||
),
|
||||
icon = {
|
||||
StableSegmentedButtonIcon(selected = selectedMode == mode)
|
||||
},
|
||||
label = {
|
||||
Text(
|
||||
text = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> "Отключить позже"
|
||||
SleepBatteryMode.TIMED_PAUSE -> "Включить позже"
|
||||
},
|
||||
modifier = Modifier.width(IntrinsicSize.Min),
|
||||
maxLines = 2,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = "Таймер сна",
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier
|
||||
.align(Alignment.CenterEnd)
|
||||
.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Close,
|
||||
contentDescription = "Закрыть таймер сна",
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 80.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
Text(
|
||||
text = when (selectedMode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> if (totalMinutes == 0) {
|
||||
"VPN отключится сразу после выключения экрана. Интернет будет работать напрямую до включения экрана"
|
||||
} else {
|
||||
"VPN отключится через выбранное время. После отключения интернет будет работать напрямую до включения экрана"
|
||||
}
|
||||
SleepBatteryMode.TIMED_PAUSE -> if (totalMinutes == 0) {
|
||||
"При значении 0 мин VPN останется активным после выключения экрана"
|
||||
} else {
|
||||
"VPN отключится сразу и включится примерно через выбранное время. Во время паузы интернет работает напрямую"
|
||||
}
|
||||
},
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(16.dp))
|
||||
Spacer(Modifier.height(12.dp))
|
||||
|
||||
SleepTimerDial(
|
||||
totalMinutes = totalMinutes,
|
||||
mode = selectedMode,
|
||||
onTotalMinutesChange = onTotalMinutesChange,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = { onTotalMinutesChange(adjustSleepTimerHours(totalMinutes, -1)) },
|
||||
enabled = totalMinutes > 0,
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("−1 ч", fontWeight = FontWeight.SemiBold)
|
||||
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
|
||||
SleepBatteryMode.entries.forEachIndexed { index, mode ->
|
||||
SegmentedButton(
|
||||
selected = selectedMode == mode,
|
||||
onClick = { selectedModeName = mode.name },
|
||||
shape = SegmentedButtonDefaults.itemShape(
|
||||
index = index,
|
||||
count = SleepBatteryMode.entries.size,
|
||||
),
|
||||
icon = {
|
||||
StableSegmentedButtonIcon(selected = selectedMode == mode)
|
||||
},
|
||||
label = {
|
||||
Text(
|
||||
text = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> "Отключить позже"
|
||||
SleepBatteryMode.TIMED_PAUSE -> "Включить позже"
|
||||
},
|
||||
modifier = Modifier.width(IntrinsicSize.Min),
|
||||
maxLines = 2,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
OutlinedButton(
|
||||
onClick = { onTotalMinutesChange(adjustSleepTimerHours(totalMinutes, 1)) },
|
||||
enabled = totalMinutes < MAX_SLEEP_PAUSE_DELAY_MINUTES,
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
SleepTimerDial(
|
||||
totalMinutes = totalMinutes,
|
||||
mode = selectedMode,
|
||||
onTotalMinutesChange = onTotalMinutesChange,
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(14.dp))
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text("+1 ч", fontWeight = FontWeight.SemiBold)
|
||||
OutlinedButton(
|
||||
onClick = { onTotalMinutesChange(adjustSleepTimerHours(totalMinutes, -1)) },
|
||||
enabled = totalMinutes > 0,
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("−1 ч", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
Spacer(Modifier.width(12.dp))
|
||||
OutlinedButton(
|
||||
onClick = { onTotalMinutesChange(adjustSleepTimerHours(totalMinutes, 1)) },
|
||||
enabled = totalMinutes < MAX_SLEEP_PAUSE_DELAY_MINUTES,
|
||||
shape = RoundedCornerShape(14.dp),
|
||||
) {
|
||||
Text("+1 ч", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(18.dp))
|
||||
Spacer(Modifier.height(18.dp))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Button(onClick = { onApply(selectedMode, pauseDelayMinutes, resumeDelayMinutes) }) {
|
||||
Text("Применить")
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.End,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Button(onClick = { onApply(selectedMode, pauseDelayMinutes, resumeDelayMinutes) }) {
|
||||
Text("Применить")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -285,6 +305,22 @@ private fun SleepTimerDial(
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.size(238.dp)
|
||||
.remoteFocusOutline(CircleShape)
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (event.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false
|
||||
when (event.key) {
|
||||
Key.DirectionLeft -> {
|
||||
currentOnTotalMinutesChange(adjustSleepTimerMinutes(currentTotalMinutes, -1))
|
||||
true
|
||||
}
|
||||
Key.DirectionRight -> {
|
||||
currentOnTotalMinutesChange(adjustSleepTimerMinutes(currentTotalMinutes, 1))
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
.focusable()
|
||||
.semantics {
|
||||
contentDescription = when (mode) {
|
||||
SleepBatteryMode.DELAYED_PAUSE -> "Круговой таймер до отключения VPN"
|
||||
|
||||
@@ -86,6 +86,9 @@ fun TransferCenterDialog(
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
val context = androidx.compose.ui.platform.LocalContext.current
|
||||
val cameraAvailable = remember(context) {
|
||||
context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)
|
||||
}
|
||||
val scope = rememberCoroutineScope()
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var error by remember { mutableStateOf<String?>(null) }
|
||||
@@ -146,7 +149,11 @@ fun TransferCenterDialog(
|
||||
}
|
||||
Text("Получить профиль", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
"Добавьте профиль через камеру, изображение или файл. Через эти же кнопки можно получить защищённые настройки администратора: предварительно включать админ-режим не нужно. После ввода пароля приложение покажет подтверждение, импортирует настройки и активирует режим администратора.",
|
||||
if (cameraAvailable) {
|
||||
"Добавьте профиль через камеру, изображение или файл. Через эти же кнопки можно получить защищённые настройки администратора: предварительно включать админ-режим не нужно. После ввода пароля приложение покажет подтверждение, импортирует настройки и активирует режим администратора."
|
||||
} else {
|
||||
"На этом устройстве нет доступной камеры. Добавьте профиль из изображения или файла. Защищённые настройки администратора поддерживаются теми же способами."
|
||||
},
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
@@ -155,15 +162,17 @@ fun TransferCenterDialog(
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp)
|
||||
) {
|
||||
TransferButton("Камера", Icons.Default.CameraAlt, busy) {
|
||||
cameraLauncher.launch(
|
||||
ScanOptions()
|
||||
.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||
.setPrompt("Наведите камеру на QR-код WDTT Plus")
|
||||
.setBeepEnabled(false)
|
||||
.setCaptureActivity(QrCaptureActivity::class.java)
|
||||
.setOrientationLocked(false)
|
||||
)
|
||||
if (cameraAvailable) {
|
||||
TransferButton("Камера", Icons.Default.CameraAlt, busy) {
|
||||
cameraLauncher.launch(
|
||||
ScanOptions()
|
||||
.setDesiredBarcodeFormats(ScanOptions.QR_CODE)
|
||||
.setPrompt("Наведите камеру на QR-код WDTT Plus")
|
||||
.setBeepEnabled(false)
|
||||
.setCaptureActivity(QrCaptureActivity::class.java)
|
||||
.setOrientationLocked(false)
|
||||
)
|
||||
}
|
||||
}
|
||||
TransferButton("Галерея", Icons.Default.Image, busy) { galleryLauncher.launch("image/*") }
|
||||
TransferButton("Файл", Icons.Default.FileOpen, busy) {
|
||||
|
||||
@@ -244,7 +244,10 @@ fun TrustedWifiSettingsDialog(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
@@ -330,12 +333,15 @@ fun TrustedWifiSettingsDialog(
|
||||
) {
|
||||
Icon(Icons.Default.Wifi, contentDescription = null, modifier = Modifier.size(19.dp))
|
||||
Text(ssid, modifier = Modifier.weight(1f).padding(horizontal = 10.dp))
|
||||
IconButton(onClick = {
|
||||
scope.launch {
|
||||
settingsStore.removeTrustedWifiSsid(ssid)
|
||||
recheckService()
|
||||
}
|
||||
}) {
|
||||
IconButton(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
settingsStore.removeTrustedWifiSsid(ssid)
|
||||
recheckService()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.DeleteOutline, contentDescription = "Удалить сеть")
|
||||
}
|
||||
}
|
||||
@@ -395,7 +401,10 @@ fun TrustedWifiSettingsDialog(
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text("Добавить сеть")
|
||||
IconButton(onClick = { showManualInput = false }) {
|
||||
IconButton(
|
||||
onClick = { showManualInput = false },
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package com.wdtt.plus.ui
|
||||
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.focusable
|
||||
import androidx.compose.foundation.ScrollState
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.composed
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.focus.onFocusChanged
|
||||
import androidx.compose.ui.graphics.Shape
|
||||
import androidx.compose.ui.graphics.graphicsLayer
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.input.key.Key
|
||||
import androidx.compose.ui.input.key.KeyEventType
|
||||
import androidx.compose.ui.input.key.key
|
||||
import androidx.compose.ui.input.key.onPreviewKeyEvent
|
||||
import androidx.compose.ui.input.key.type
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import com.wdtt.plus.isTelevisionDevice
|
||||
|
||||
@Composable
|
||||
internal fun isTelevisionDevice(): Boolean {
|
||||
val configuration = LocalConfiguration.current
|
||||
val context = LocalContext.current
|
||||
return remember(configuration.uiMode, context) {
|
||||
isTelevisionDevice(context)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes keyboard/D-pad focus unmistakable on custom clickable surfaces.
|
||||
* Material controls already expose their own focus target; this modifier only
|
||||
* observes it, so one remote press never has to pass through a duplicate target.
|
||||
*/
|
||||
internal fun Modifier.remoteFocusOutline(
|
||||
shape: Shape = RoundedCornerShape(16.dp),
|
||||
enabled: Boolean = true,
|
||||
focusedScale: Float = 1f,
|
||||
): Modifier = composed {
|
||||
if (!enabled) return@composed this
|
||||
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val scale by animateFloatAsState(
|
||||
targetValue = if (focused) focusedScale.coerceAtLeast(1f) else 1f,
|
||||
label = "remote_focus_scale",
|
||||
)
|
||||
val borderColor = if (focused) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
androidx.compose.ui.graphics.Color.Transparent
|
||||
}
|
||||
|
||||
this
|
||||
.onFocusChanged { focused = it.isFocused }
|
||||
.then(
|
||||
if (focusedScale > 1f) {
|
||||
Modifier.graphicsLayer {
|
||||
scaleX = scale
|
||||
scaleY = scale
|
||||
}
|
||||
} else {
|
||||
Modifier
|
||||
}
|
||||
)
|
||||
.border(width = 2.dp, color = borderColor, shape = shape)
|
||||
.clip(shape)
|
||||
}
|
||||
|
||||
internal fun Modifier.remoteSwitchFocus(enabled: Boolean = true): Modifier =
|
||||
remoteFocusOutline(
|
||||
shape = RoundedCornerShape(percent = 50),
|
||||
enabled = enabled,
|
||||
focusedScale = 1.06f,
|
||||
)
|
||||
|
||||
internal fun Modifier.remoteToggleableRow(
|
||||
value: Boolean,
|
||||
enabled: Boolean = true,
|
||||
shape: Shape = RoundedCornerShape(14.dp),
|
||||
onValueChange: (Boolean) -> Unit,
|
||||
): Modifier = this
|
||||
.remoteFocusOutline(shape = shape, enabled = enabled)
|
||||
.toggleable(
|
||||
value = value,
|
||||
enabled = enabled,
|
||||
role = Role.Switch,
|
||||
onValueChange = onValueChange,
|
||||
)
|
||||
|
||||
internal fun Modifier.remoteCompactFocus(
|
||||
shape: Shape = CircleShape,
|
||||
enabled: Boolean = true,
|
||||
): Modifier = remoteFocusOutline(shape, enabled, focusedScale = 1.08f)
|
||||
|
||||
/** A stable circular focus ring for small icon buttons. */
|
||||
internal fun Modifier.remoteIconButtonFocus(enabled: Boolean = true): Modifier =
|
||||
remoteFocusOutline(shape = CircleShape, enabled = enabled)
|
||||
|
||||
internal fun Modifier.remoteHelpFocus(enabled: Boolean = true): Modifier =
|
||||
remoteIconButtonFocus(enabled)
|
||||
|
||||
/** Keeps informational dialogs comfortably wide on TV without changing phone sizing. */
|
||||
internal fun Modifier.televisionDialogWidth(
|
||||
television: Boolean,
|
||||
fraction: Float = 0.78f,
|
||||
maxWidth: Dp = 920.dp,
|
||||
): Modifier = if (television) {
|
||||
fillMaxWidth(fraction.coerceIn(0.5f, 0.96f)).widthIn(max = maxWidth)
|
||||
} else {
|
||||
this
|
||||
}
|
||||
|
||||
/** A readable, non-clickable list row that can carry D-pad focus and auto-scroll. */
|
||||
internal fun Modifier.remoteReadableItem(
|
||||
shape: Shape = RoundedCornerShape(8.dp),
|
||||
): Modifier = this
|
||||
.remoteFocusOutline(shape)
|
||||
.focusable()
|
||||
|
||||
internal fun tvDpadScrollDeltaPx(
|
||||
forward: Boolean,
|
||||
canScrollBackward: Boolean,
|
||||
canScrollForward: Boolean,
|
||||
viewportSizePx: Int,
|
||||
minimumStepPx: Float,
|
||||
): Float {
|
||||
val canScroll = if (forward) canScrollForward else canScrollBackward
|
||||
if (!canScroll) return 0f
|
||||
val step = maxOf(minimumStepPx, viewportSizePx.coerceAtLeast(0) * 0.16f)
|
||||
return if (forward) step else -step
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives a read-only scroll viewport its own visible TV focus target. While the
|
||||
* viewport itself is focused, every D-pad press moves the text by a small,
|
||||
* deterministic step. At either edge the event is released, allowing normal
|
||||
* focus navigation to the close/action buttons. Child controls keep their
|
||||
* ordinary D-pad behavior because only direct viewport focus is handled.
|
||||
*/
|
||||
internal fun Modifier.tvDpadScrollable(
|
||||
scrollState: ScrollState,
|
||||
television: Boolean,
|
||||
requestInitialFocus: Boolean = true,
|
||||
shape: Shape = RoundedCornerShape(12.dp),
|
||||
): Modifier = composed {
|
||||
if (!television) return@composed this
|
||||
|
||||
val focusRequester = remember { FocusRequester() }
|
||||
val minimumStepPx = with(LocalDensity.current) { 56.dp.toPx() }
|
||||
var directlyFocused by remember { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(requestInitialFocus) {
|
||||
if (requestInitialFocus) focusRequester.requestFocus()
|
||||
}
|
||||
|
||||
this
|
||||
.focusRequester(focusRequester)
|
||||
.onPreviewKeyEvent { event ->
|
||||
if (!directlyFocused || event.type != KeyEventType.KeyDown) {
|
||||
return@onPreviewKeyEvent false
|
||||
}
|
||||
val forward = when (event.key) {
|
||||
Key.DirectionDown -> true
|
||||
Key.DirectionUp -> false
|
||||
else -> return@onPreviewKeyEvent false
|
||||
}
|
||||
val delta = tvDpadScrollDeltaPx(
|
||||
forward = forward,
|
||||
canScrollBackward = scrollState.canScrollBackward,
|
||||
canScrollForward = scrollState.canScrollForward,
|
||||
viewportSizePx = scrollState.viewportSize,
|
||||
minimumStepPx = minimumStepPx,
|
||||
)
|
||||
if (delta == 0f) {
|
||||
false
|
||||
} else {
|
||||
scrollState.dispatchRawDelta(delta)
|
||||
true
|
||||
}
|
||||
}
|
||||
.remoteFocusOutline(shape = shape)
|
||||
.onFocusChanged { directlyFocused = it.isFocused }
|
||||
.focusable()
|
||||
}
|
||||
@@ -311,7 +311,10 @@ fun VkClientSettingsDialog(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
@@ -346,7 +349,17 @@ fun VkClientSettingsDialog(
|
||||
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteToggleableRow(
|
||||
value = enabled,
|
||||
enabled = !tunnelRunning,
|
||||
) { checked ->
|
||||
scope.launch {
|
||||
settingsStore.saveCustomVkCredentialsEnabled(checked)
|
||||
}
|
||||
}
|
||||
.padding(14.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
@@ -368,9 +381,7 @@ fun VkClientSettingsDialog(
|
||||
Switch(
|
||||
checked = enabled,
|
||||
enabled = !tunnelRunning,
|
||||
onCheckedChange = { checked ->
|
||||
scope.launch { settingsStore.saveCustomVkCredentialsEnabled(checked) }
|
||||
}
|
||||
onCheckedChange = null,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -389,7 +400,10 @@ fun VkClientSettingsDialog(
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
IconButton(onClick = { showHelp = true }) {
|
||||
IconButton(
|
||||
onClick = { showHelp = true },
|
||||
modifier = Modifier.remoteHelpFocus(),
|
||||
) {
|
||||
Icon(
|
||||
Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Как получить Client ID и secret"
|
||||
@@ -649,6 +663,7 @@ fun VkClientSettingsDialog(
|
||||
@Composable
|
||||
private fun VkClientCredentialsHelpDialog(onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
val television = isTelevisionDevice()
|
||||
val clipboard = LocalClipboardManager.current
|
||||
val configuration = LocalConfiguration.current
|
||||
val packageName = context.packageName
|
||||
@@ -665,8 +680,11 @@ private fun VkClientCredentialsHelpDialog(onDismiss: () -> Unit) {
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.92f)
|
||||
modifier = (if (television) {
|
||||
Modifier.televisionDialogWidth(television, fraction = 0.82f, maxWidth = 1_000.dp)
|
||||
} else {
|
||||
Modifier.fillMaxWidth(0.92f)
|
||||
})
|
||||
.fillMaxHeight(0.9f)
|
||||
.heightIn(max = (configuration.screenHeightDp.dp - 32.dp).coerceAtLeast(360.dp)),
|
||||
shape = RoundedCornerShape(30.dp),
|
||||
@@ -697,7 +715,10 @@ private fun VkClientCredentialsHelpDialog(onDismiss: () -> Unit) {
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
IconButton(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.remoteIconButtonFocus(),
|
||||
) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,6 +64,7 @@ internal fun VpnDnsSettingsCard(
|
||||
AppSectionCard(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteFocusOutline(RoundedCornerShape(16.dp))
|
||||
.clickable(onClick = onClick),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 14.dp),
|
||||
) {
|
||||
@@ -309,6 +310,7 @@ private fun VpnDnsOptionRow(
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.remoteFocusOutline(RoundedCornerShape(8.dp))
|
||||
.clickable(onClick = onClick),
|
||||
color = if (selected) {
|
||||
MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.55f)
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 35 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 56 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 109 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 180 KiB |
Reference in new issue
Block a user