package com.wdtt.plus.ui import androidx.compose.runtime.MutableState import android.app.ActivityManager import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.PowerManager import android.os.StatFs import android.provider.Settings import android.system.Os import android.system.OsConstants import android.webkit.WebView import android.widget.Toast import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut 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 import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.GenericShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material.icons.automirrored.filled.HelpOutline import androidx.compose.material.icons.automirrored.filled.OpenInNew import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Cloud import androidx.compose.material.icons.filled.Code import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Update import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FilledTonalIconButton import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableIntState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.luminance import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.wdtt.plus.BuildConfig import com.wdtt.plus.DeviceCheckAction import com.wdtt.plus.DeviceCompatibility import com.wdtt.plus.R import com.wdtt.plus.RemoteActionCatalogGateway import com.wdtt.plus.RemoteActionForm import com.wdtt.plus.RemoteContinuationLauncher import com.wdtt.plus.RemoteUiAction import com.wdtt.plus.RemoteUiActionLauncher import com.wdtt.plus.RT_MASQUE_CONFIG_FILE_NAME import com.wdtt.plus.RtMasqueEnrollmentState import com.wdtt.plus.SettingsStore import com.wdtt.plus.ScreenOffMode import com.wdtt.plus.SleepBatteryMode import com.wdtt.plus.SleepBatteryRuntimePhase import com.wdtt.plus.SleepBatteryRuntimeState import com.wdtt.plus.TunnelManager import com.wdtt.plus.TrustedWifiManager import com.wdtt.plus.decodeStoredVpnPackages import com.wdtt.plus.displayedTunnelProfile import com.wdtt.plus.trustedWifiAccessProblem import com.wdtt.plus.sleepBatteryModeItem import com.wdtt.plus.trustedWifiModeItem import com.wdtt.plus.vpnRoutingModeItem import com.wdtt.plus.vpnProfileDisplayName import com.wdtt.plus.inspectRtMasqueEnrollment import com.wdtt.plus.normalizeTunnelMode import com.wdtt.plus.tunnelModeNeedsVpnPermission import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE import com.wdtt.plus.WDTTColors import com.wdtt.plus.AppReleaseInfo import com.wdtt.plus.AppUpdateCandidate import com.wdtt.plus.AppUpdateDownloadProgress import com.wdtt.plus.ClientNetworkDiagnosticsReport import com.wdtt.plus.canRequestApkInstall import com.wdtt.plus.collectClientNetworkDiagnostics import com.wdtt.plus.downloadUpdateApk import com.wdtt.plus.fetchLatestReleaseInfo import com.wdtt.plus.installUpdateApk import com.wdtt.plus.isNewerVersion import com.wdtt.plus.resolveAppUpdateCandidate import com.wdtt.plus.selectUpdateApkAsset import com.wdtt.plus.deviceCheckActionIntent import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.CancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import java.security.MessageDigest import java.text.SimpleDateFormat import java.util.Date import java.util.Locale import java.util.TimeZone import java.util.UUID import kotlin.math.PI import kotlin.math.cos import kotlin.math.min import kotlin.math.sin private const val ReleasesUrl = "https://github.com/Ivan4537/WDTT-Plus/releases" private const val IssuesUrl = "https://github.com/Ivan4537/WDTT-Plus/issues/new/choose" private const val DeveloperProfileUrl = "https://github.com/Ivan4537" private const val RepositoryUrl = "https://github.com/Ivan4537/WDTT-Plus" private const val ChangelogUrl = "$RepositoryUrl/blob/main/CHANGELOG.md" private const val ProjectDonateFallbackUrl = "https://yoomoney.ru/to/410012216336438" private const val OriginalDonateUrl = "https://yoomoney.ru/to/4100119505530465/" private val DonateActionButtonColor = Color(0xFF00AEA5) private val browserPackages = listOf( "com.android.chrome", "com.google.android.googlequicksearchbox", "org.mozilla.firefox", "com.yandex.browser", "ru.yandex.searchplugin", "com.yandex.browser.lite", "com.opera.browser", "com.opera.mini.native", "com.microsoft.emmx", "com.brave.browser", "com.duckduckgo.mobile.android", "com.sec.android.app.sbrowser", "com.vivaldi.browser", "com.kiwibrowser.browser", ) private val Android16BlobShape: Shape = GenericShape { size, _ -> val centerX = size.width / 2f val centerY = size.height / 2f val outerRadius = min(size.width, size.height) / 2f val innerRadius = outerRadius * 0.92f val points = 14 for (i in 0 until points * 2) { val angle = (-PI / 2.0) + (i * PI / points) val radius = if (i % 2 == 0) outerRadius else innerRadius val x = centerX + (radius * cos(angle)).toFloat() val y = centerY + (radius * sin(angle)).toFloat() if (i == 0) moveTo(x, y) else lineTo(x, y) } close() } private fun openUrlInBrowser(context: Context, url: String) { try { val pm = context.packageManager val uri = Uri.parse(url) for (pkg in browserPackages) { val intent = Intent(Intent.ACTION_VIEW, uri).apply { addCategory(Intent.CATEGORY_BROWSABLE) setPackage(pkg) } if (intent.resolveActivity(pm) != null) { context.startActivity(intent) return } } val intent = Intent(Intent.ACTION_VIEW, uri).apply { addCategory(Intent.CATEGORY_BROWSABLE) } if (intent.resolveActivity(pm) != null) context.startActivity(intent) } catch (_: Exception) { } } private fun openDeviceCheckAction(context: Context, action: DeviceCheckAction) { runCatching { val intent = deviceCheckActionIntent(context, action) if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) } else { context.startActivity( Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { data = Uri.parse("package:${context.packageName}") } ) } }.onFailure { Toast.makeText(context, "Не удалось открыть настройки Android", Toast.LENGTH_SHORT).show() } } @Composable fun InfoTab( actionsExpandedState: MutableState = rememberSaveable { mutableStateOf(true) }, projectExpandedState: MutableState = rememberSaveable { mutableStateOf(true) }, scrollPosition: MutableIntState = rememberSaveable { mutableIntStateOf(0) }, projectSupportDialogRequest: Int = 0, onProjectSupportDialogRequestConsumed: () -> Unit = {}, ) { val context = LocalContext.current val scope = rememberCoroutineScope() val settingsStore = remember { SettingsStore(context) } val infoScrollState = rememberRememberedScrollState(scrollPosition) val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() } var actionsSectionY by remember { mutableStateOf(0f) } var projectSectionY by remember { mutableStateOf(0f) } val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" } val releaseDate = remember { BuildConfig.MOD_RELEASE_DATE } var isCheckingUpdates by remember { mutableStateOf(false) } var pendingManualUpdateCandidate by remember { mutableStateOf(null) } var updateDownloadProgress by remember { mutableStateOf(null) } var updateDownloadStatus by rememberSaveable { mutableStateOf("") } var updateDownloadBusy by remember { mutableStateOf(false) } var pendingUpdateApkPath by rememberSaveable { mutableStateOf(null) } var showHelpDialog by remember { mutableStateOf(false) } var showQuestionDialog by remember { mutableStateOf(false) } var showSupportDialog by remember { mutableStateOf(false) } var highlightNoServerBlock by remember { mutableStateOf(false) } var pendingActionForm by remember { mutableStateOf(null) } var actionCatalog by remember { mutableStateOf(RemoteActionCatalogGateway.cached()) } var questionAction by remember { mutableStateOf(null) } var questionActionLoading by remember { mutableStateOf(false) } var isCheckingDevice by remember { mutableStateOf(false) } var deviceCheckReport by remember { mutableStateOf(null) } var actionsExpanded by actionsExpandedState var projectExpanded by projectExpandedState LaunchedEffect(projectSupportDialogRequest) { if (projectSupportDialogRequest > 0) { highlightNoServerBlock = true showSupportDialog = true onProjectSupportDialogRequestConsumed() } } val updateLatestVersion by settingsStore.updateLatestVersion.collectAsStateWithLifecycle(initialValue = "") val updateLastError by settingsStore.updateLastError.collectAsStateWithLifecycle(initialValue = "") val updateStatus = remember(isCheckingUpdates, updateLatestVersion, updateLastError, currentVersion) { when { isCheckingUpdates -> "Проверяем GitHub releases..." updateLatestVersion.isNotBlank() && isNewerVersion(currentVersion, updateLatestVersion) -> "На GitHub доступна версия $updateLatestVersion" updateLatestVersion.isNotBlank() -> "Последняя версия: $updateLatestVersion" updateLastError.isNotBlank() -> "Последняя проверка завершилась ошибкой" else -> "Проверить GitHub вручную" } } val updateInstallPermissionLauncher = rememberLauncherForActivityResult( ActivityResultContracts.StartActivityForResult() ) { val apkFile = pendingUpdateApkPath?.let(::File) if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) { runCatching { installUpdateApk(context, apkFile) pendingManualUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null }.onFailure { error -> updateDownloadStatus = error.message ?: "Не удалось открыть установку APK." Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() } } else if (apkFile != null) { updateDownloadStatus = "Разрешение на установку из WDTT Plus не выдано." Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() } } LaunchedEffect(Unit) { actionCatalog = RemoteActionCatalogGateway.fetch() } LaunchedEffect(showSupportDialog) { if (showSupportDialog) { // Каталог общий для всех режимов соединения. Обновляем его при каждом // открытии окна, сохраняя последний корректный кэш при сетевом сбое. actionCatalog = RemoteActionCatalogGateway.fetch(force = true) } } LaunchedEffect(Unit) { questionActionLoading = true questionAction = RemoteActionCatalogGateway.fetchQuestionAction() questionActionLoading = false } fun requestDownloadedUpdateInstall(apkFile: File) { pendingUpdateApkPath = apkFile.absolutePath if (!canRequestApkInstall(context)) { updateDownloadStatus = "Разрешите установку из WDTT Plus в настройках Android." updateInstallPermissionLauncher.launch( Intent( Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:${context.packageName}") ) ) return } runCatching { installUpdateApk(context, apkFile) pendingManualUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null }.onFailure { error -> updateDownloadStatus = error.message ?: "Не удалось открыть установку APK." Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() } } suspend fun buildDeviceCheckReportWithVersion(): com.wdtt.plus.DeviceCompatibilityReport { val latestCheckedAt = System.currentTimeMillis() val latestRelease = fetchLatestReleaseInfo(context, currentVersion) settingsStore.saveUpdateState( lastCheckAt = latestCheckedAt, latestVersion = latestRelease?.versionTag ?: "", error = if (latestRelease == null) "Не удалось проверить" else "" ) val versionItem = DeviceCompatibility.appVersionItem( currentVersion = currentVersion, releaseDate = releaseDate, latestRelease = latestRelease ) val selectedProfile = runCatching { settingsStore.activeProfile.first() }.getOrDefault(0) val savedTunnelProfile = runCatching { settingsStore.activeTunnelProfile.first() }.getOrNull() val trustedWifiRuntime = TrustedWifiManager.state.value val trustedWifiWaiting = trustedWifiRuntime.waiting || runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false) val diagnosticProfile = displayedTunnelProfile( selectedProfile = selectedProfile, activeTunnelProfile = TunnelManager.activeTunnelProfile.value ?: savedTunnelProfile, running = TunnelManager.running.value, trustedWifiWaiting = trustedWifiWaiting, ) val profileNames = runCatching { settingsStore.profileNames.first() }.getOrDefault(emptyList()) val diagnosticProfileName = vpnProfileDisplayName(diagnosticProfile, profileNames) val tunnelProfile = runCatching { settingsStore.tunnelProfileSnapshot(diagnosticProfile) }.getOrNull() val diagnosticTunnelMode = normalizeTunnelMode(tunnelProfile?.proxyMode) val systemVpnMode = tunnelModeNeedsVpnPermission(diagnosticTunnelMode) val workers = tunnelProfile?.workersPerHash ?: runCatching { settingsStore.workersPerHash.first() }.getOrNull() val routingSnapshot = runCatching { settingsStore.vpnRoutingSettingsForProfile(diagnosticProfile) }.getOrNull() val vpnDnsSnapshot = runCatching { settingsStore.vpnDnsSettingsForProfile(diagnosticProfile) }.getOrNull() val installedPackages = withContext(Dispatchers.Default) { runCatching { @Suppress("DEPRECATION") context.packageManager.getInstalledApplications(0) .mapTo(linkedSetOf()) { it.packageName } }.getOrDefault(emptySet()) } val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrDefault(false) val trustedWifiSsids = runCatching { settingsStore.trustedWifiSsids.first() }.getOrDefault(emptyList()) val trustedWifiWaitingSsid = trustedWifiRuntime.ssid.ifBlank { runCatching { settingsStore.trustedWifiWaitingSsid.first() }.getOrDefault("") } val trustedWifiProblem = if (trustedWifiEnabled) { trustedWifiAccessProblem(context.applicationContext) } else { null } val sleepEnabled = runCatching { settingsStore.pauseVpnDuringSleep.first() }.getOrDefault(false) val screenOffMode = runCatching { settingsStore.screenOffMode.first() } .getOrDefault(ScreenOffMode.BALANCED) val sleepMode = runCatching { settingsStore.sleepBatteryMode.first() } .getOrDefault(SleepBatteryMode.DELAYED_PAUSE) val sleepPauseDelay = runCatching { settingsStore.pauseVpnDuringSleepDelayMinutes.first() }.getOrDefault(0) val sleepResumeDelay = runCatching { settingsStore.resumeVpnDuringSleepDelayMinutes.first() }.getOrDefault(0) val sleepRuntime = runCatching { settingsStore.sleepBatteryRuntimeState.first() } .getOrDefault(SleepBatteryRuntimeState()) val notificationsGranted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED val batteryOptimizationsIgnored = runCatching { context.getSystemService(PowerManager::class.java) ?.isIgnoringBatteryOptimizations(context.packageName) }.getOrNull() val backgroundRestricted = runCatching { context.getSystemService(ActivityManager::class.java)?.isBackgroundRestricted }.getOrNull() val diagnosticsSummary = withContext(Dispatchers.Default) { buildSupportReportSummary( context.applicationContext, settingsStore, diagnosticTunnelMode, ) } val clientNetworkDiagnostics = try { collectClientNetworkDiagnostics(context.applicationContext) } catch (error: CancellationException) { throw error } catch (error: Throwable) { ClientNetworkDiagnosticsReport( summaryLines = listOf("Активная диагностика сети телефона: не выполнена"), items = listOf( com.wdtt.plus.DeviceCheckItem( title = "Активная диагностика сети телефона", status = "не выполнена", details = error.message?.take(180) ?: error.javaClass.simpleName, recommendation = "Повторите проверку устройства при активной сети.", severity = com.wdtt.plus.DeviceCheckSeverity.Warning, action = DeviceCheckAction.NetworkSettings ) ) ) } val vpnDnsRuntimeItem = vpnDnsSnapshot?.takeIf { systemVpnMode }?.let { settings -> try { com.wdtt.plus.collectVpnDnsRuntimeDiagnostic( context = context.applicationContext, settings = settings, tunnelRunning = TunnelManager.running.value, runningProfile = TunnelManager.activeTunnelProfile.value, ) } catch (error: CancellationException) { throw error } catch (error: Throwable) { com.wdtt.plus.DeviceCheckItem( title = "Доступность выбранного DNS внутри VPN", status = "проверка не выполнена", details = error.message?.take(180) ?: error.javaClass.simpleName, recommendation = "Повторите проверку при активном VPN этого профиля.", severity = com.wdtt.plus.DeviceCheckSeverity.Warning, ) } } val report = withContext(Dispatchers.Default) { DeviceCompatibility.check( context = context.applicationContext, includeRuntimeChecks = true, workersPerHash = workers, tunnelMode = diagnosticTunnelMode, screenOffMode = screenOffMode, ) } val relevantNetworkSummary = clientNetworkDiagnostics.summaryLines.filterNot { line -> !systemVpnMode && line.contains("DNS внутри VPN", ignoreCase = true) } val relevantNetworkItems = clientNetworkDiagnostics.items.filterNot { item -> !systemVpnMode && item.title.contains("DNS внутри VPN", ignoreCase = true) } return report.copy( summaryLines = diagnosticsSummary + relevantNetworkSummary + listOfNotNull(vpnDnsRuntimeItem?.let { "DNS внутри VPN: ${it.status}" }), items = listOf(versionItem) + report.items.filterNot { it.title == DeviceCompatibility.APP_VERSION_ITEM_TITLE || it.title == "Сеть Android" } + listOfNotNull( tunnelProfile?.let { DeviceCompatibility.rtNetworkModeItem(context, it) }, sleepBatteryModeItem( enabled = sleepEnabled, screenOffMode = screenOffMode, mode = sleepMode, pauseDelayMinutes = sleepPauseDelay, resumeDelayMinutes = sleepResumeDelay, runtime = sleepRuntime, notificationsGranted = notificationsGranted, batteryOptimizationsIgnored = batteryOptimizationsIgnored, backgroundRestricted = backgroundRestricted, ).takeIf { systemVpnMode || screenOffMode == ScreenOffMode.HOLD_CONNECTION }, trustedWifiModeItem( enabled = trustedWifiEnabled, savedNetworkCount = trustedWifiSsids.size, waiting = trustedWifiWaiting, waitingSsid = trustedWifiWaitingSsid, accessProblem = trustedWifiProblem, ).takeIf { systemVpnMode }, routingSnapshot?.takeIf { systemVpnMode }?.let { vpnRoutingModeItem( snapshot = it, installedPackages = installedPackages, ownPackageName = context.packageName, ) }, vpnDnsSnapshot?.takeIf { systemVpnMode }?.let { com.wdtt.plus.vpnDnsModeItem( settings = it, tunnelRunning = TunnelManager.running.value, runningProfile = TunnelManager.activeTunnelProfile.value, profileName = diagnosticProfileName, ) }, vpnDnsRuntimeItem, ) + relevantNetworkItems ) } Column( 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) ) { Row( modifier = Modifier .fillMaxWidth() .height(48.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = "Информация", style = MaterialTheme.typography.titleMedium.copy(fontWeight = FontWeight.Bold), color = MaterialTheme.colorScheme.onSurface ) } InfoHeroCard( currentVersion = currentVersion, releaseDate = releaseDate, onSupportClick = { highlightNoServerBlock = false showSupportDialog = true } ) ExpandableSectionCard( title = "Действия", itemCount = "4 пункта", expanded = actionsExpanded, modifier = Modifier.onGloballyPositioned { actionsSectionY = it.positionInParent().y }, onToggle = { val willExpand = !actionsExpanded actionsExpanded = willExpand if (willExpand) { scope.launch { kotlinx.coroutines.delay(80) infoScrollState.animateScrollTo((actionsSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0)) } } }, icon = { Icon( imageVector = Icons.Default.Info, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp) ) } ) { WideActionTile( title = "Поднять вопрос", subtitle = "Выбрать подходящий способ обращения", onClick = { showQuestionDialog = true if (questionAction == null && !questionActionLoading) { scope.launch { questionActionLoading = true questionAction = RemoteActionCatalogGateway.fetchQuestionAction() questionActionLoading = false } } }, icon = { Icon( painter = painterResource(id = R.drawable.ic_github), contentDescription = null, modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer ) } ) WideActionTile( title = "Проверить устройство", subtitle = if (isCheckingDevice) { "Проверяем Android, ABI, 16 КиБ, WireGuard, режим РТ и сеть..." } else { "Проверка совместимости и полный отчёт для диагностики" }, onClick = { if (isCheckingDevice) return@WideActionTile isCheckingDevice = true scope.launch { runCatching { buildDeviceCheckReportWithVersion() }.onSuccess { report -> deviceCheckReport = report }.onFailure { error -> Toast.makeText( context, error.message ?: "Не удалось проверить устройство", Toast.LENGTH_LONG ).show() } isCheckingDevice = false } }, icon = { Icon( imageVector = Icons.Default.Info, contentDescription = null, modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer ) } ) WideActionTile( title = "Справка", subtitle = "Коротко про режимы, цепочки, исключения и запуск", onClick = { showHelpDialog = true }, icon = { Icon( imageVector = Icons.AutoMirrored.Filled.HelpOutline, contentDescription = null, modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer ) } ) WideActionTile( title = "Проверить обновления", subtitle = updateStatus, onClick = { if (isCheckingUpdates) return@WideActionTile isCheckingUpdates = true scope.launch { val checkedAt = System.currentTimeMillis() var release: AppReleaseInfo? = null var updateCandidate: AppUpdateCandidate? = null var errorMessage = "" try { runCatching { release = fetchLatestReleaseInfo(context, currentVersion) if (release == null) { errorMessage = "Не удалось проверить" return@runCatching } updateCandidate = resolveAppUpdateCandidate(context, currentVersion, release) }.onFailure { error -> errorMessage = error.message ?: "Не удалось проверить обновления" } settingsStore.saveUpdateState( lastCheckAt = checkedAt, latestVersion = release?.versionTag ?: "", error = errorMessage ) val currentRelease = release if (currentRelease == null) { val message = if (updateLatestVersion.isNotBlank()) { "Не удалось проверить. Последняя известная версия: $updateLatestVersion" } else { "Не удалось проверить обновления" } Toast.makeText(context, message, Toast.LENGTH_SHORT).show() return@launch } val candidate = updateCandidate if (candidate != null) { settingsStore.saveUpdateDialogShown(candidate.postponeKey, checkedAt) pendingManualUpdateCandidate = candidate } else { Toast.makeText( context, "У вас уже последняя версия: ${currentRelease.versionTag}", Toast.LENGTH_SHORT ).show() } } finally { isCheckingUpdates = false } } }, icon = { Icon( imageVector = Icons.Default.Update, contentDescription = null, modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer ) } ) } pendingManualUpdateCandidate?.let { candidate -> val release = candidate.release val apkAsset = remember(release) { selectUpdateApkAsset(release) } AppUpdateDialog( release = release, updateKind = candidate.kind, apkAsset = apkAsset, isDownloading = updateDownloadBusy, downloadProgress = updateDownloadProgress, downloadStatus = updateDownloadStatus, onPostpone = { pendingManualUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show() scope.launch { val now = System.currentTimeMillis() settingsStore.saveUpdatePostpone( version = candidate.postponeKey, until = now + 24L * 60L * 60L * 1000L ) settingsStore.saveUpdateDialogAction( version = candidate.postponeKey, action = UPDATE_DIALOG_ACTION_POSTPONED, actedAt = now ) } }, onUpdate = { scope.launch { settingsStore.saveUpdateDialogAction( version = candidate.postponeKey, action = UPDATE_DIALOG_ACTION_UPDATE, actedAt = System.currentTimeMillis() ) if (apkAsset == null) { pendingManualUpdateCandidate = null openUrlInBrowser(context, release.releaseUrl) return@launch } updateDownloadBusy = true updateDownloadStatus = "Подготовка скачивания..." updateDownloadProgress = null runCatching { val apkFile = downloadUpdateApk(context, apkAsset) { progress -> updateDownloadProgress = progress updateDownloadStatus = if (progress.percent != null) { "Скачивание APK" } else { "Скачивание APK..." } } updateDownloadStatus = if (apkAsset.sha256 != null) { "APK скачан и проверен. Открываю установку..." } else { "APK скачан. Открываю установку..." } requestDownloadedUpdateInstall(apkFile) }.onFailure { error -> updateDownloadStatus = error.message ?: "Не удалось скачать обновление." Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() } updateDownloadBusy = false } }, onOpenRelease = { pendingManualUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null openUrlInBrowser(context, release.releaseUrl) } ) } ExpandableSectionCard( title = "О проекте", itemCount = "4 ссылки", expanded = projectExpanded, modifier = Modifier.onGloballyPositioned { projectSectionY = it.positionInParent().y }, onToggle = { val willExpand = !projectExpanded projectExpanded = willExpand if (willExpand) { scope.launch { kotlinx.coroutines.delay(80) infoScrollState.animateScrollTo((projectSectionY - topRevealOffsetPx).toInt().coerceAtLeast(0)) } } }, icon = { Icon( imageVector = Icons.Default.Code, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp) ) } ) { ProjectLinkRow( title = "Разработка модификации", subtitle = "GitHub профиль Ivan4537", onClick = { openUrlInBrowser(context, DeveloperProfileUrl) }, icon = { Icon( imageVector = Icons.Default.Person, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp) ) } ) ProjectLinkRow( title = "Репозиторий WDTT Plus", subtitle = "Исходники и релизы приложения", onClick = { openUrlInBrowser(context, RepositoryUrl) }, icon = { Icon( painter = painterResource(id = R.drawable.ic_github), contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp) ) } ) ProjectLinkRow( title = "Актуальные релизы", subtitle = "Страница загрузки APK", onClick = { openUrlInBrowser(context, ReleasesUrl) }, icon = { Icon( imageVector = Icons.Default.Update, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp) ) } ) ProjectLinkRow( title = "История изменений", subtitle = "Что менялось в версиях WDTT Plus", onClick = { openUrlInBrowser(context, ChangelogUrl) }, icon = { Icon( imageVector = Icons.Default.Update, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp) ) } ) } Spacer(modifier = Modifier.height(20.dp)) } if (showHelpDialog) ImportantInfoDialog(onDismiss = { showHelpDialog = false }) if (showQuestionDialog) { QuestionDestinationDialog( remoteAction = questionAction, remoteActionLoading = questionActionLoading, onDismiss = { showQuestionDialog = false }, onGitHubClick = { showQuestionDialog = false openUrlInBrowser(context, IssuesUrl) }, onRemoteActionClick = { action -> showQuestionDialog = false scope.launch { if (!RemoteUiActionLauncher.open(context, action)) { Toast.makeText( context, "Не удалось открыть страницу. Проверьте браузер.", Toast.LENGTH_LONG, ).show() } } }, ) } deviceCheckReport?.let { report -> DeviceCompatibilityDialog( report = report, title = "Проверка устройства", subtitle = "Расширенная проверка не запускает соединение, но безопасно проверяет системный DNS, сетевой путь клиента и доступность узлов VK/OK.", note = "Кнопка «Скопировать отчёт» повторит сетевые пробы и добавит их результат без VK-хешей, паролей, токенов и локальных IP-адресов телефона.", onDismiss = { deviceCheckReport = null }, onCopy = { scope.launch { val freshReport = runCatching { buildDeviceCheckReportWithVersion() }.getOrElse { report } deviceCheckReport = freshReport val clipboard = context.getSystemService(ClipboardManager::class.java) clipboard?.setPrimaryClip(ClipData.newPlainText("WDTT Device Check", freshReport.toPlainText())) Toast.makeText(context, "Отчёт проверки скопирован", Toast.LENGTH_SHORT).show() } }, onAction = { action -> openDeviceCheckAction(context, action) } ) } if (showSupportDialog) { AdditionalActionsDialog( onDismiss = { highlightNoServerBlock = false showSupportDialog = false }, primaryAction = actionCatalog.at("about"), secondaryAction = actionCatalog.at("tunnel"), highlightSecondaryAction = highlightNoServerBlock, onSecondaryHighlightConsumed = { highlightNoServerBlock = false }, onActionClick = { action -> highlightNoServerBlock = false if (action.form != null) { showSupportDialog = false pendingActionForm = action } else { showSupportDialog = false scope.launch { if (!RemoteUiActionLauncher.open(context, action)) { Toast.makeText( context, "Не удалось открыть страницу. Проверьте браузер.", Toast.LENGTH_LONG, ).show() } } } }, onProjectFallbackClick = { highlightNoServerBlock = false showSupportDialog = false openUrlInBrowser(context, ProjectDonateFallbackUrl) }, onDonateOriginalClick = { highlightNoServerBlock = false showSupportDialog = false openUrlInBrowser(context, OriginalDonateUrl) } ) } pendingActionForm?.form?.let { form -> RemoteActionFormDialog( form = form, onDismiss = { pendingActionForm = null showSupportDialog = true }, onComplete = { pendingActionForm = null showSupportDialog = true }, onFallbackClick = { openUrlInBrowser(context, ProjectDonateFallbackUrl) pendingActionForm = null showSupportDialog = true }, ) } } @Composable private fun QuestionDestinationDialog( remoteAction: RemoteUiAction?, remoteActionLoading: Boolean, onDismiss: () -> Unit, onGitHubClick: () -> Unit, onRemoteActionClick: (RemoteUiAction) -> Unit, ) { val television = isTelevisionDevice() Dialog( onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false), ) { Box( modifier = Modifier.fillMaxSize().padding(20.dp), contentAlignment = Alignment.Center, ) { Surface( shape = RoundedCornerShape(28.dp), color = MaterialTheme.colorScheme.surface, tonalElevation = 8.dp, shadowElevation = 18.dp, modifier = (if (television) { Modifier.televisionDialogWidth(television) } else { Modifier.fillMaxWidth() }).heightIn(max = 560.dp), ) { Column( modifier = Modifier.fillMaxWidth().padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically, ) { Surface( shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.primaryContainer, ) { Box( modifier = Modifier.size(42.dp), contentAlignment = Alignment.Center, ) { Icon( imageVector = Icons.AutoMirrored.Filled.HelpOutline, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(21.dp), ) } } Column( modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp), ) { Text( "Поднять вопрос", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, ) Text( "Выберите подходящий вариант обращения.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) } FilledTonalIconButton(onClick = onDismiss) { Icon(Icons.Default.Close, contentDescription = null) } } WideActionTile( title = "Проблема в приложении", subtitle = "Открыть шаблоны обращений GitHub", onClick = onGitHubClick, icon = { Icon( painter = painterResource(id = R.drawable.ic_github), contentDescription = null, modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer, ) }, ) remoteAction?.let { action -> WideActionTile( title = action.label, subtitle = action.message, onClick = { onRemoteActionClick(action) }, icon = { Icon( Icons.AutoMirrored.Filled.HelpOutline, contentDescription = null, modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onPrimaryContainer, ) }, ) } if (remoteAction == null && remoteActionLoading) { Surface( shape = RoundedCornerShape(20.dp), color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.62f), modifier = Modifier.fillMaxWidth(), ) { Row( modifier = Modifier.padding(horizontal = 18.dp, vertical = 16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically, ) { CircularProgressIndicator( modifier = Modifier.size(20.dp), strokeWidth = 2.dp, ) Text( "Проверяем доступные способы помощи…", style = MaterialTheme.typography.bodyMedium, ) } } } } } } } } @Composable private fun AdditionalActionsDialog( onDismiss: () -> Unit, primaryAction: RemoteUiAction?, secondaryAction: RemoteUiAction?, highlightSecondaryAction: Boolean, onSecondaryHighlightConsumed: () -> Unit, onActionClick: (RemoteUiAction) -> Unit, onProjectFallbackClick: () -> Unit, onDonateOriginalClick: () -> Unit ) { var originalAuthorExpanded by rememberSaveable { mutableStateOf(false) } val supportScrollState = rememberScrollState() val supportScope = rememberCoroutineScope() val topRevealOffsetPx = with(LocalDensity.current) { 10.dp.toPx() } var originalAuthorSectionY by remember { mutableStateOf(0f) } Dialog( onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false) ) { BoxWithConstraints( modifier = Modifier.fillMaxSize().padding(8.dp), contentAlignment = Alignment.Center ) { Surface( shape = RoundedCornerShape(28.dp), color = MaterialTheme.colorScheme.surface, tonalElevation = 8.dp, shadowElevation = 18.dp, modifier = Modifier .fillMaxWidth() .padding(horizontal = 12.dp) .heightIn(max = maxHeight * 0.92f) ) { Column( modifier = Modifier .fillMaxWidth() .padding(20.dp) .verticalScroll(supportScrollState), verticalArrangement = Arrangement.spacedBy(16.dp) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically ) { Surface( shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.primaryContainer ) { Box(modifier = Modifier.size(42.dp), contentAlignment = Alignment.Center) { Icon( imageVector = Icons.Default.Favorite, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp) ) } } Column(modifier = Modifier.weight(1f)) { Text( "Поддержать проект", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface ) } FilledTonalIconButton(onClick = onDismiss) { Icon(Icons.Default.Close, contentDescription = null) } } if (primaryAction?.form != null) { ExternalSupportBlock( title = primaryAction.title, body = primaryAction.message, buttonText = "Поддержать проект", onClick = { onActionClick(primaryAction) }, emphasized = true, ) } else { ExternalSupportBlock( title = "WDTT Plus", body = ( "Поддержка помогает развивать приложение, серверную " + "часть и Telegram-бота." ), buttonText = "ЮMoney", onClick = onProjectFallbackClick, emphasized = true, ) } secondaryAction?.let { action -> RemoteInfoActionBlock( action = action, highlightRequested = highlightSecondaryAction, onHighlightConsumed = onSecondaryHighlightConsumed, onClick = { onActionClick(action) }, ) } OriginalAuthorSupportBlock( expanded = originalAuthorExpanded, onToggle = { val willExpand = !originalAuthorExpanded originalAuthorExpanded = willExpand if (willExpand) { supportScope.launch { delay(80) supportScrollState.animateScrollTo( (originalAuthorSectionY - topRevealOffsetPx) .toInt() .coerceAtLeast(0), ) } } }, onClick = onDonateOriginalClick, modifier = Modifier.onGloballyPositioned { originalAuthorSectionY = it.positionInParent().y }, ) Spacer(Modifier.height(4.dp)) } } } } } @Composable private fun OriginalAuthorSupportBlock( expanded: Boolean, onToggle: () -> Unit, onClick: () -> Unit, modifier: Modifier = Modifier, ) { val arrowRotation by animateFloatAsState( targetValue = if (expanded) 180f else 0f, label = "original_author_arrow_rotation", ) Surface( modifier = modifier, shape = RoundedCornerShape(22.dp), color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f), border = BorderStroke( 1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f), ), ) { Column(modifier = Modifier.fillMaxWidth()) { Row( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(22.dp)) .remoteFocusOutline(RoundedCornerShape(22.dp)) .clickable(onClick = onToggle) .padding(horizontal = 16.dp, vertical = 14.dp), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically, ) { Icon( Icons.Default.Person, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp), ) Text( "Автор оригинального приложения", modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, ) Icon( Icons.Default.KeyboardArrowDown, contentDescription = if (expanded) "Свернуть" else "Развернуть", modifier = Modifier.size(24.dp).rotate(arrowRotation), tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } AnimatedVisibility( visible = expanded, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut(), ) { Column( modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { HorizontalDivider( color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f), ) Text( "Оригинальная основа проекта создана amurcanov. Можно отдельно поддержать автора исходного приложения.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, lineHeight = 18.sp, ) Button( onClick = onClick, shape = RoundedCornerShape(18.dp), colors = ButtonDefaults.buttonColors( containerColor = MaterialTheme.colorScheme.primary, contentColor = Color.White, ), modifier = Modifier.fillMaxWidth().heightIn(min = 46.dp), ) { Text("ЮMoney", fontWeight = FontWeight.Bold) } } } } } } @Composable private fun RemoteActionFormDialog( form: RemoteActionForm, onDismiss: () -> Unit, onComplete: () -> Unit, onFallbackClick: () -> Unit, ) { val context = LocalContext.current val scope = rememberCoroutineScope() var valueText by rememberSaveable(form.token) { mutableStateOf(form.initialValue) } var requestId by rememberSaveable(form.token) { mutableStateOf(UUID.randomUUID().toString()) } var busy by remember(form.token) { mutableStateOf(false) } var errorMessage by remember(form.token) { mutableStateOf("") } var fallbackAvailable by remember(form.token) { mutableStateOf(false) } val numericValue = valueText.toLongOrNull() val valueValid = numericValue != null && numericValue in form.minimum..form.maximum val supportAmount = valueText.trim() val supportButtonLabel = if (supportAmount.isNotEmpty()) { buildString { append("Поддержать на ") append(supportAmount) if (form.inputSuffix.isNotBlank()) { append(' ') append(form.inputSuffix.trim()) } } } else { "Поддержать" } fun selectValue(value: String) { valueText = value requestId = UUID.randomUUID().toString() errorMessage = "" fallbackAvailable = false } Dialog( onDismissRequest = { if (!busy) onDismiss() }, properties = DialogProperties(usePlatformDefaultWidth = false), ) { Surface( shape = RoundedCornerShape(28.dp), color = MaterialTheme.colorScheme.surface, tonalElevation = 8.dp, shadowElevation = 18.dp, modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp), ) { Column( modifier = Modifier .fillMaxWidth() .padding(20.dp) .verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(16.dp), ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { Surface( shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.primaryContainer, ) { Box(Modifier.size(42.dp), contentAlignment = Alignment.Center) { Icon( Icons.Default.Favorite, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp), ) } } Text( form.title, modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, ) FilledTonalIconButton( onClick = onDismiss, enabled = !busy, ) { Icon(Icons.Default.Close, contentDescription = "Закрыть") } } Text( form.message, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, lineHeight = 20.sp, ) Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { form.choices.chunked(2).forEach { rowChoices -> Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { rowChoices.forEach { choice -> OutlinedButton( onClick = { selectValue(choice.value) }, enabled = !busy, modifier = Modifier.weight(1f), colors = if (valueText == choice.value) { ButtonDefaults.outlinedButtonColors( containerColor = MaterialTheme.colorScheme.primaryContainer, contentColor = MaterialTheme.colorScheme.onPrimaryContainer, ) } else { ButtonDefaults.outlinedButtonColors() }, ) { Text(choice.label, fontWeight = FontWeight.SemiBold) } } if (rowChoices.size == 1) { Spacer(Modifier.weight(1f)) } } } } OutlinedTextField( value = valueText, onValueChange = { raw -> selectValue(raw.filter(Char::isDigit).take(form.maxCharacters)) }, enabled = !busy, modifier = Modifier.fillMaxWidth(), label = { Text(form.inputLabel) }, suffix = { if (form.inputSuffix.isNotBlank()) { Text(form.inputSuffix) } }, singleLine = true, isError = valueText.isNotEmpty() && !valueValid, supportingText = { Text( if (valueValid || valueText.isEmpty()) { form.supportingText } else { form.invalidText } ) }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), shape = RoundedCornerShape(16.dp), ) if (errorMessage.isNotBlank()) { Surface( color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.64f), shape = RoundedCornerShape(14.dp), ) { Text( errorMessage, modifier = Modifier.fillMaxWidth().padding(12.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onErrorContainer, ) } } Button( onClick = { if (!valueValid) return@Button busy = true errorMessage = "" fallbackAvailable = false scope.launch { runCatching { RemoteActionCatalogGateway.execute( form = form, requestId = requestId, value = valueText, ) }.onSuccess { target -> RemoteContinuationLauncher.launch(context, target) onComplete() }.onFailure { error -> errorMessage = error.message ?: form.failureMessage fallbackAvailable = true } busy = false } }, enabled = valueValid && !busy, modifier = Modifier.fillMaxWidth().heightIn(min = 50.dp), shape = RoundedCornerShape(17.dp), colors = ButtonDefaults.buttonColors( containerColor = DonateActionButtonColor, contentColor = Color.White, ), ) { if (busy) { CircularProgressIndicator( modifier = Modifier.size(20.dp), strokeWidth = 2.dp, color = Color.White, ) Spacer(Modifier.width(9.dp)) Text(form.busyLabel, fontWeight = FontWeight.Bold) } else { Text( supportButtonLabel, fontWeight = FontWeight.Bold, ) } } if (fallbackAvailable) { OutlinedButton( onClick = onFallbackClick, enabled = !busy, modifier = Modifier.fillMaxWidth().heightIn(min = 46.dp), shape = RoundedCornerShape(16.dp), ) { Text(form.fallbackLabel, fontWeight = FontWeight.SemiBold) Spacer(Modifier.width(6.dp)) Icon( Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, modifier = Modifier.size(17.dp), ) } } } } } } @Composable private fun RemoteInfoActionBlock( action: RemoteUiAction, highlightRequested: Boolean = false, onHighlightConsumed: () -> Unit = {}, onClick: () -> Unit, ) { var borderPulseActive by remember(highlightRequested) { mutableStateOf(false) } LaunchedEffect(highlightRequested) { if (highlightRequested) { repeat(2) { borderPulseActive = true delay(380) borderPulseActive = false delay(280) } onHighlightConsumed() } } val borderColor by animateColorAsState( targetValue = if (borderPulseActive) { MaterialTheme.colorScheme.primary } else { MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) }, animationSpec = tween(durationMillis = 240), label = "no_server_highlight_border", ) val borderWidth by animateDpAsState( targetValue = if (borderPulseActive) 2.5.dp else 1.dp, animationSpec = tween(durationMillis = 240), label = "no_server_highlight_border_width", ) Surface( shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.48f), contentColor = MaterialTheme.colorScheme.onSecondaryContainer, border = BorderStroke(borderWidth, borderColor), ) { Column( modifier = Modifier.fillMaxWidth().padding(14.dp), verticalArrangement = Arrangement.spacedBy(9.dp) ) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(9.dp) ) { Icon(Icons.Default.Cloud, contentDescription = null, modifier = Modifier.size(21.dp)) Text( action.title, modifier = Modifier.weight(1f), style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.SemiBold ) } Text( action.message, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSecondaryContainer.copy(alpha = 0.86f), lineHeight = 18.sp ) OutlinedButton( onClick = onClick, modifier = Modifier.fillMaxWidth().heightIn(min = 44.dp), shape = RoundedCornerShape(14.dp), contentPadding = PaddingValues(horizontal = 10.dp, vertical = 7.dp) ) { Text(action.label, fontWeight = FontWeight.SemiBold) Spacer(Modifier.width(6.dp)) Icon( Icons.AutoMirrored.Filled.OpenInNew, contentDescription = null, modifier = Modifier.size(17.dp) ) } } } } @Composable private fun ExternalSupportBlock( title: String, body: String, buttonText: String, onClick: () -> Unit, emphasized: Boolean ) { val containerColor = if (emphasized) { DonateActionButtonColor.copy(alpha = 0.12f) } else { MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f) } val borderColor = if (emphasized) { DonateActionButtonColor.copy(alpha = 0.38f) } else { MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.45f) } Surface( shape = RoundedCornerShape(22.dp), color = containerColor, border = BorderStroke(1.dp, borderColor) ) { Column( modifier = Modifier .fillMaxWidth() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { Text( title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface ) Text( body, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, lineHeight = 18.sp ) Button( onClick = onClick, shape = RoundedCornerShape(18.dp), colors = ButtonDefaults.buttonColors( containerColor = if (emphasized) { DonateActionButtonColor } else { MaterialTheme.colorScheme.primary }, contentColor = Color.White ), modifier = Modifier .fillMaxWidth() .heightIn(min = 46.dp) ) { Text(buttonText, fontWeight = FontWeight.Bold) } } } } @Composable private fun InfoHeroCard( currentVersion: String, releaseDate: String, onSupportClick: () -> Unit ) { val colors = MaterialTheme.colorScheme val isDark = colors.background.luminance() < 0.22f val heroBrush = remember(colors.primaryContainer, colors.secondaryContainer, colors.surfaceVariant) { Brush.linearGradient( listOf( colors.primaryContainer, colors.secondaryContainer, colors.surfaceVariant ) ) } val glassColor = if (isDark) colors.surface.copy(alpha = 0.46f) else Color.White.copy(alpha = 0.54f) val glassBorder = colors.outlineVariant.copy(alpha = if (isDark) 0.50f else 0.32f) Surface( shape = RoundedCornerShape(32.dp), color = Color.Transparent, contentColor = MaterialTheme.colorScheme.onSurface, shadowElevation = 10.dp, tonalElevation = 0.dp ) { Box( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(32.dp)) .background(heroBrush) .padding(22.dp) ) { Box( modifier = Modifier .align(Alignment.TopEnd) .offset(x = 30.dp, y = (-34).dp) .size(138.dp) .clip(Android16BlobShape) .background(colors.primary.copy(alpha = 0.10f)) ) Box( modifier = Modifier .align(Alignment.BottomEnd) .offset(x = 26.dp, y = 30.dp) .size(112.dp) .clip(Android16BlobShape) .background(colors.secondary.copy(alpha = 0.12f)) ) Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(18.dp) ) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically ) { HeroMetaPill( text = "WDTT Plus", containerColor = glassColor, borderColor = glassBorder, modifier = Modifier.weight(1f) ) HeroVersionPill( version = currentVersion, releaseDate = releaseDate, containerColor = colors.primary.copy(alpha = if (isDark) 0.18f else 0.10f), borderColor = colors.primary.copy(alpha = if (isDark) 0.22f else 0.14f), modifier = Modifier.weight(1f) ) } Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( text = "WDTT Plus", style = MaterialTheme.typography.headlineSmall.copy( fontWeight = FontWeight.Black, fontSize = 30.sp, lineHeight = 34.sp ), color = colors.onSurface ) Text( text = "Android-клиент для TURN/VK туннеля с WireGuard, капчей, управлением сервером и удобными сценариями подключения.", style = MaterialTheme.typography.bodyMedium, color = colors.onSurfaceVariant, lineHeight = 21.sp ) } Button( onClick = onSupportClick, shape = RoundedCornerShape(22.dp), colors = ButtonDefaults.buttonColors( containerColor = DonateActionButtonColor, contentColor = Color.White ), modifier = Modifier .fillMaxWidth() .heightIn(min = 54.dp) ) { Icon(Icons.Default.Favorite, contentDescription = null, modifier = Modifier.size(18.dp)) Spacer(modifier = Modifier.width(8.dp)) Text("Поддержать проект", fontWeight = FontWeight.Bold, fontSize = 15.sp) } } } } } @Composable private fun HeroMetaPill( text: String, containerColor: Color, borderColor: Color, modifier: Modifier = Modifier ) { Surface( shape = RoundedCornerShape(18.dp), color = containerColor, border = BorderStroke(1.dp, borderColor), modifier = modifier.height(52.dp) ) { Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { Text( text = text, modifier = Modifier.padding(horizontal = 12.dp), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface, textAlign = TextAlign.Center ) } } } @Composable private fun HeroVersionPill( version: String, releaseDate: String, containerColor: Color, borderColor: Color, modifier: Modifier = Modifier ) { Surface( shape = RoundedCornerShape(18.dp), color = containerColor, border = BorderStroke(1.dp, borderColor), modifier = modifier.height(52.dp) ) { Column( modifier = Modifier .fillMaxSize() .padding(horizontal = 12.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = "Версия ${version.removePrefix("v")}", style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface, textAlign = TextAlign.Center ) Text( text = "от $releaseDate", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, textAlign = TextAlign.Center ) } } } @Composable private fun ExpandableSectionCard( title: String, itemCount: String, expanded: Boolean, modifier: Modifier = Modifier, onToggle: () -> Unit, icon: @Composable () -> Unit, content: @Composable ColumnScope.() -> Unit ) { val arrowRotation by animateFloatAsState( targetValue = if (expanded) 180f else 0f, label = "section_arrow_rotation" ) AppSectionCard( modifier = modifier, contentPadding = PaddingValues(horizontal = 18.dp, vertical = 18.dp), verticalArrangement = Arrangement.spacedBy(0.dp) ) { Row( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(24.dp)) .remoteFocusOutline(RoundedCornerShape(24.dp)) .clickable(onClick = onToggle) .padding(vertical = 2.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically ) { Surface(shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.primaryContainer) { Box(modifier = Modifier.size(40.dp), contentAlignment = Alignment.Center) { icon() } } Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.Center) { Text( text = title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface ) } MetaChip(text = itemCount) Icon( imageVector = Icons.Default.KeyboardArrowDown, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier .size(24.dp) .rotate(arrowRotation) ) } AnimatedVisibility( visible = expanded, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut() ) { Column( modifier = Modifier.padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f)) content() } } } } @Composable private fun MetaChip(text: String) { Surface( shape = RoundedCornerShape(14.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = 0.88f), contentColor = MaterialTheme.colorScheme.onSurface ) { Text( text = text, modifier = Modifier.padding(horizontal = 10.dp, vertical = 7.dp), style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } @Composable private fun InfoActionTile( title: String, subtitle: String, modifier: Modifier = Modifier, onClick: () -> Unit, icon: @Composable () -> Unit ) { Surface( shape = RoundedCornerShape(24.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = 0.70f), contentColor = MaterialTheme.colorScheme.onSurface, modifier = modifier .clip(RoundedCornerShape(24.dp)) .remoteFocusOutline(RoundedCornerShape(24.dp)) .clickable(onClick = onClick) ) { Column( modifier = Modifier .fillMaxWidth() .heightIn(min = 116.dp) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { Surface(shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.primaryContainer) { Box(modifier = Modifier.size(40.dp), contentAlignment = Alignment.Center) { icon() } } Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface ) Text( text = subtitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, lineHeight = 18.sp ) } } } } @Composable private fun WideActionTile( title: String, subtitle: String, onClick: () -> Unit, icon: @Composable () -> Unit ) { Surface( shape = RoundedCornerShape(24.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = 0.70f), contentColor = MaterialTheme.colorScheme.onSurface, modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(24.dp)) .remoteFocusOutline(RoundedCornerShape(24.dp)) .clickable(onClick = onClick) ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 15.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically ) { Surface(shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.primaryContainer) { Box(modifier = Modifier.size(40.dp), contentAlignment = Alignment.Center) { icon() } } Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { Text( title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface ) Text( text = subtitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, lineHeight = 18.sp ) } Icon( imageVector = Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp) ) } } } @Composable private fun ProjectLinkRow( title: String, subtitle: String, onClick: () -> Unit, icon: @Composable () -> Unit ) { Surface( shape = RoundedCornerShape(24.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = 0.64f), contentColor = MaterialTheme.colorScheme.onSurface, modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(24.dp)) .remoteFocusOutline(RoundedCornerShape(24.dp)) .clickable(onClick = onClick) ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 14.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically ) { Surface(shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.primaryContainer) { Box( modifier = Modifier.defaultMinSize(minWidth = 40.dp, minHeight = 40.dp), contentAlignment = Alignment.Center ) { icon() } } Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { Text( title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, color = MaterialTheme.colorScheme.onSurface ) Text( text = subtitle, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, lineHeight = 18.sp ) } Icon( imageVector = Icons.AutoMirrored.Filled.ArrowForward, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp) ) } } } private fun diagnosticText(block: () -> Any?): String = runCatching { block()?.toString()?.takeIf(String::isNotBlank) ?: "недоступно" } .getOrDefault("недоступно") private fun formatMiB(bytes: Long): String = "${bytes.coerceAtLeast(0L) / (1024L * 1024L)} МБ" internal fun sleepBatteryModeDiagnosticText(mode: SleepBatteryMode): String = when (mode) { SleepBatteryMode.DELAYED_PAUSE -> "отключить VPN после задержки до включения экрана" SleepBatteryMode.TIMED_PAUSE -> "отключить VPN сразу и включить по таймеру" } internal fun sleepBatteryRuntimeDiagnosticText( runtime: SleepBatteryRuntimeState, nowMs: Long = System.currentTimeMillis(), ): String { val phase = when (runtime.phase) { SleepBatteryRuntimePhase.IDLE -> "ожидание выключения экрана" SleepBatteryRuntimePhase.WAITING_TO_PAUSE -> "ожидание отключения VPN" SleepBatteryRuntimePhase.PAUSED_UNTIL_SCREEN_ON -> "VPN отключён до включения экрана" SleepBatteryRuntimePhase.WAITING_TO_RESUME -> "VPN отключён, ожидается включение по таймеру" SleepBatteryRuntimePhase.RESUMED_UNTIL_SCREEN_ON -> "VPN включён таймером до включения экрана" } if (runtime.deadlineMs <= 0L) return phase val remainingMs = (runtime.deadlineMs - nowMs).coerceAtLeast(0L) val remainingMinutes = remainingMs / 60_000L + if (remainingMs % 60_000L == 0L) 0L else 1L val boundedMinutes = remainingMinutes.coerceAtMost(Int.MAX_VALUE.toLong()).toInt() return "$phase, осталось ${formatSleepTimerDuration(boundedMinutes)}" } private suspend fun buildSupportReportSummary( context: Context, settingsStore: SettingsStore, tunnelMode: String, ): List { val systemVpnMode = tunnelModeNeedsVpnPermission(tunnelMode) val androidVersion = Build.VERSION.RELEASE ?: "?" val sdkInt = Build.VERSION.SDK_INT val primaryAbi = Build.SUPPORTED_ABIS.firstOrNull().orEmpty().ifBlank { "unknown" } val supportedAbis = Build.SUPPORTED_ABIS.joinToString().ifBlank { "unknown" } val manufacturer = Build.MANUFACTURER.orEmpty().ifBlank { "unknown" } val brand = Build.BRAND.orEmpty().ifBlank { "unknown" } val model = Build.MODEL.orEmpty().ifBlank { "unknown" } val device = Build.DEVICE.orEmpty().ifBlank { "unknown" } val product = Build.PRODUCT.orEmpty().ifBlank { "unknown" } val hardware = Build.HARDWARE.orEmpty().ifBlank { "unknown" } val board = Build.BOARD.orEmpty().ifBlank { "unknown" } val romDisplay = Build.DISPLAY.orEmpty().ifBlank { "unknown" } val buildId = Build.ID.orEmpty().ifBlank { "unknown" } val buildFingerprint = Build.FINGERPRINT.orEmpty().ifBlank { "unknown" } val buildType = Build.TYPE.orEmpty().ifBlank { "unknown" } val socManufacturer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { Build.SOC_MANUFACTURER.orEmpty().ifBlank { "unknown" } } else { "n/a" } val socModel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { Build.SOC_MODEL.orEmpty().ifBlank { "unknown" } } else { "n/a" } val appInfo = runCatching { context.applicationInfo }.getOrNull() val packageInfo = runCatching { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { context.packageManager.getPackageInfo( context.packageName, PackageManager.PackageInfoFlags.of(PackageManager.GET_SIGNING_CERTIFICATES.toLong()) ) } else { @Suppress("DEPRECATION") context.packageManager.getPackageInfo( context.packageName, PackageManager.GET_SIGNING_CERTIFICATES ) } }.getOrNull() val signingCertificate = diagnosticText { val certificate = packageInfo?.signingInfo?.apkContentsSigners?.firstOrNull()?.toByteArray() ?: return@diagnosticText null MessageDigest.getInstance("SHA-256") .digest(certificate) .joinToString("") { "%02x".format(it) } } val installSource = diagnosticText { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { context.packageManager.getInstallSourceInfo(context.packageName).installingPackageName } else { @Suppress("DEPRECATION") context.packageManager.getInstallerPackageName(context.packageName) } ?: "ручная установка" } val dateFormat = SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.ROOT) val firstInstallTime = diagnosticText { packageInfo?.firstInstallTime?.let { dateFormat.format(Date(it)) } } val lastUpdateTime = diagnosticText { packageInfo?.lastUpdateTime?.let { dateFormat.format(Date(it)) } } val processBits = diagnosticText { if (android.os.Process.is64Bit()) "64-bit" else "32-bit" } val pageSize = diagnosticText { "${Os.sysconf(OsConstants._SC_PAGESIZE)} байт" } val securityPatch = Build.VERSION.SECURITY_PATCH.orEmpty().ifBlank { "unknown" } val kernel = diagnosticText { System.getProperty("os.version") } val activityManager = runCatching { context.getSystemService(ActivityManager::class.java) }.getOrNull() val memoryInfo = runCatching { ActivityManager.MemoryInfo().also { activityManager?.getMemoryInfo(it) } }.getOrNull() val memorySummary = if (memoryInfo != null && memoryInfo.totalMem > 0L) { "всего ${formatMiB(memoryInfo.totalMem)}, доступно ${formatMiB(memoryInfo.availMem)}, " + "lowMemory=${memoryInfo.lowMemory}" } else { "недоступно" } val memoryClass = diagnosticText { "обычный ${activityManager?.memoryClass} МБ, большой ${activityManager?.largeMemoryClass} МБ" } val lowRamDevice = diagnosticText { activityManager?.isLowRamDevice } val storageSummary = runCatching { val stat = StatFs(context.filesDir.absolutePath) "свободно ${formatMiB(stat.availableBytes)}, всего ${formatMiB(stat.totalBytes)}" }.getOrDefault("недоступно") val powerManager = runCatching { context.getSystemService(PowerManager::class.java) }.getOrNull() val powerSummary = diagnosticText { "экономия=${powerManager?.isPowerSaveMode}, " + "без ограничений батареи=${powerManager?.isIgnoringBatteryOptimizations(context.packageName)}, " + "ограничено в фоне=${activityManager?.isBackgroundRestricted}" } val webViewInfo = diagnosticText { WebView.getCurrentWebViewPackage()?.let { "${it.packageName} ${it.versionName}" } } val nativeComponentsInfo = runCatching { val nativeClient = File(appInfo?.nativeLibraryDir.orEmpty(), "libclient.so") val wireGuardBackend = File(appInfo?.nativeLibraryDir.orEmpty(), "libwg-go.so") buildString { append("libclient.so=${if (nativeClient.isFile) formatMiB(nativeClient.length()) else "не найден"}") if (systemVpnMode) { append(", libwg-go.so=${if (wireGuardBackend.isFile) formatMiB(wireGuardBackend.length()) else "не найден"}") } else { append(", libwg-go.so не требуется для SOCKS5") } } }.getOrDefault("недоступно") val notificationPermission = diagnosticText { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { "не требуется до Android 13" } else { context.checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED } } val updateInstallPermission = diagnosticText { context.packageManager.canRequestPackageInstalls() } val vpnPermission = "проверяется только при явном подключении" val displayMetrics = context.resources.displayMetrics val screenSummary = diagnosticText { "${displayMetrics.widthPixels}×${displayMetrics.heightPixels}, " + "density=${displayMetrics.densityDpi} dpi, fontScale=${context.resources.configuration.fontScale}" } val selectedProfileIndex = runCatching { settingsStore.activeProfile.first() }.getOrNull() val savedTunnelProfileIndex = runCatching { settingsStore.activeTunnelProfile.first() }.getOrNull() val trustedWifiWaiting = TrustedWifiManager.state.value.waiting || runCatching { settingsStore.trustedWifiWaiting.first() }.getOrDefault(false) val diagnosticProfileIndex = selectedProfileIndex?.let { selected -> displayedTunnelProfile( selectedProfile = selected, activeTunnelProfile = TunnelManager.activeTunnelProfile.value ?: savedTunnelProfileIndex, running = TunnelManager.running.value, trustedWifiWaiting = trustedWifiWaiting, ) } val activeProfile = diagnosticProfileIndex?.plus(1) val routingSettings = diagnosticProfileIndex?.let { profile -> runCatching { settingsStore.vpnRoutingSettingsForProfile(profile) }.getOrNull() } val vpnDnsSettings = diagnosticProfileIndex?.let { profile -> runCatching { settingsStore.vpnDnsSettingsForProfile(profile) }.getOrNull() } val routingPackages = routingSettings?.let { decodeStoredVpnPackages(it.appPackages) }.orEmpty() val routingDomains = routingSettings?.addressRules?.count { it.type == com.wdtt.plus.VpnAddressType.DOMAIN } val workers = runCatching { settingsStore.workersPerHash.first() }.getOrNull() val vkHashes = runCatching { settingsStore.vkHashes.first() }.getOrDefault("") val hashCount = vkHashes .split(Regex("[,\\s\\n]+")) .count { it.isNotBlank() } .coerceAtMost(4) val vkCallsEnabled = runCatching { settingsStore.vkCallsPreflight.first() }.getOrNull() val rtNetworkEnabled = runCatching { settingsStore.rtNetwork.first() }.getOrNull() val rtMasqueEnabled = runCatching { settingsStore.rtMasque.first() }.getOrNull() val rtMasqueServerBootstrap = runCatching { settingsStore.rtMasqueServerBootstrap.first() }.getOrNull() val rtMasqueEnrollment = runCatching { val config = File(context.filesDir, RT_MASQUE_CONFIG_FILE_NAME) when (inspectRtMasqueEnrollment(config)) { RtMasqueEnrollmentState.Missing -> "не создана" RtMasqueEnrollmentState.Ready -> "сохранена и структурно корректна" RtMasqueEnrollmentState.Invalid -> "повреждена" } }.getOrDefault("недоступно") val customVkCredentialsEnabled = runCatching { settingsStore.customVkCredentialsEnabled.first() }.getOrNull() val customVkCredentialsComplete = runCatching { settingsStore.customVkCredentialsComplete.first() }.getOrNull() val builtInVkClientCount = runCatching { settingsStore.activeClientIds.first().split(',').count { it.trim().isNotEmpty() } }.getOrNull() val captchaMode = runCatching { settingsStore.captchaMode.first() }.getOrNull() val fingerprint = runCatching { settingsStore.selectedFingerprint.first() }.getOrNull() val linkMode = runCatching { settingsStore.wdttLinkMode.first() }.getOrNull() val interfaceRole = runCatching { settingsStore.interfaceRole.first() }.getOrNull() val themeMode = runCatching { settingsStore.themeMode.first() }.getOrNull() val dynamicColor = runCatching { settingsStore.isDynamicColor.first() }.getOrNull() val loggingEnabled = runCatching { settingsStore.loggingEnabled.first() }.getOrNull() val trustedWifiEnabled = runCatching { settingsStore.trustedWifiEnabled.first() }.getOrNull() val trustedWifiCount = runCatching { settingsStore.trustedWifiSsids.first().size }.getOrNull() val sleepBatteryEnabled = runCatching { settingsStore.pauseVpnDuringSleep.first() }.getOrNull() val screenOffMode = runCatching { settingsStore.screenOffMode.first() }.getOrNull() val sleepBatteryPauseDelay = runCatching { settingsStore.pauseVpnDuringSleepDelayMinutes.first() }.getOrNull() val sleepBatteryMode = runCatching { settingsStore.sleepBatteryMode.first() }.getOrNull() val sleepBatteryResumeDelay = runCatching { settingsStore.resumeVpnDuringSleepDelayMinutes.first() }.getOrNull() val sleepBatteryRuntime = runCatching { settingsStore.sleepBatteryRuntimeState.first() }.getOrNull() val trustedWifiAccess = if (trustedWifiEnabled == true) { when (trustedWifiAccessProblem(context)) { com.wdtt.plus.TrustedWifiAccessProblem.ForegroundPermission -> "нет доступа к имени Wi-Fi" com.wdtt.plus.TrustedWifiAccessProblem.BackgroundPermission -> "нет фонового доступа" com.wdtt.plus.TrustedWifiAccessProblem.LocationDisabled -> "определение местоположения выключено" null -> "доступ выдан" } } else { "не требуется" } val confirmedNetworkFailure = TunnelManager.hasConfirmedNetworkFailureSince(0L) val tunnelIssue = TunnelManager.connectionIssue.value?.let { issue -> "${issue.title}: ${issue.action}" }.orEmpty().ifBlank { if (confirmedNetworkFailure) { "пользовательский трафик передан, но ответы не получены" } else { "нет" } } return buildString { appendLine("Версия приложения: ${BuildConfig.VERSION_NAME}") appendLine("Дата релиза: ${BuildConfig.MOD_RELEASE_DATE}") appendLine("Версия пакета: code ${packageInfo?.longVersionCode ?: "?"}") appendLine("Источник установки: $installSource") appendLine("Первая установка: $firstInstallTime") appendLine("Последнее обновление: $lastUpdateTime") appendLine("SHA-256 сертификата: $signingCertificate") appendLine("Android: $androidVersion (SDK $sdkInt, patch $securityPatch)") appendLine("SDK приложения: min ${appInfo?.minSdkVersion ?: "?"}, target ${appInfo?.targetSdkVersion ?: "?"}") appendLine("Устройство: $manufacturer / $brand / $model") appendLine("Код устройства: $device") appendLine("Продукт: $product") appendLine("ABI: $primaryAbi") appendLine("Все ABI: $supportedAbis") appendLine("Процесс: $processBits") appendLine("Страница памяти: $pageSize") appendLine("SoC: $socManufacturer / $socModel") appendLine("Hardware: $hardware") appendLine("Board: $board") appendLine("ROM: $romDisplay") appendLine("Build ID: $buildId") appendLine("Build type: $buildType") appendLine("Fingerprint: $buildFingerprint") appendLine("Kernel: $kernel") appendLine("RAM: $memorySummary") appendLine("Memory class: $memoryClass") appendLine("Low-RAM устройство: $lowRamDevice") appendLine("Хранилище приложения: $storageSummary") appendLine("Питание: $powerSummary") appendLine("WebView: $webViewInfo") appendLine("Нативные компоненты: $nativeComponentsInfo") appendLine("Экран: $screenSummary") appendLine("Разрешение уведомлений: $notificationPermission") appendLine("Установка обновлений APK: $updateInstallPermission") appendLine("Режим соединения: ${if (systemVpnMode) "системный VPN" else "локальный SOCKS5"}") if (systemVpnMode) { appendLine("VPN-разрешение: $vpnPermission") appendLine( "Доверенные Wi-Fi: включено=${trustedWifiEnabled ?: "недоступно"}, " + "сетей=${trustedWifiCount ?: "недоступно"}, ожидание=$trustedWifiWaiting, доступ=$trustedWifiAccess" ) } appendLine( "Работа при выключенном экране: режим=${screenOffMode?.let { mode -> when (mode) { ScreenOffMode.BALANCED -> "сбалансированно" ScreenOffMode.HOLD_CONNECTION -> "удерживать соединение" ScreenOffMode.SAVE_BATTERY -> "экономить батарею" } } ?: "недоступно"}, " + "экономия включена=${sleepBatteryEnabled ?: "недоступно"}, " + "режим=${sleepBatteryMode?.let(::sleepBatteryModeDiagnosticText) ?: "недоступно"}, " + "отключение через=${sleepBatteryPauseDelay?.let(::formatSleepTimerDuration) ?: "недоступно"}, " + "включение через=${sleepBatteryResumeDelay?.let(::formatSleepTimerDuration) ?: "недоступно"}, " + "состояние=${sleepBatteryRuntime?.let(::sleepBatteryRuntimeDiagnosticText) ?: "недоступно"}" ) TunnelManager.connectionHoldDiagnostics.value.let { hold -> appendLine( "Диагностика удержания: выбрано=${hold.modeSelected}, активно=${hold.active}, " + "CPU wake lock=${hold.cpuWakeLockHeld}, Wi-Fi lock=${hold.wifiLockHeld}, " + "Wi-Fi доступен=${hold.wifiTransportAvailable}, экран активен=${hold.deviceInteractive}" ) } appendLine("Локаль: ${diagnosticText { Locale.getDefault().toLanguageTag() }}") appendLine("Часовой пояс: ${diagnosticText { TimeZone.getDefault().id }}") appendLine("Туннель: запущен=${TunnelManager.running.value}, активных=${TunnelManager.activeWorkers.value}") appendLine("Последняя проблема: $tunnelIssue") appendLine( "Последняя остановка соединения: " + (TunnelManager.lastStopReason.value?.displayText ?: "не зафиксирована в текущем процессе") ) appendLine("Профиль: ${activeProfile ?: "недоступно"}") if (systemVpnMode) { appendLine( "Маршрутизация профиля: режим=${routingSettings?.let { if (it.isWhitelist) "БС" else "ЧС" } ?: "недоступно"}, " + "приложений=${routingSettings?.let { routingPackages.size } ?: "недоступно"}, " + "адресов=${routingSettings?.addressRules?.size ?: "недоступно"}, " + "доменов=${routingDomains ?: "недоступно"}" ) appendLine( "DNS внутри VPN: ${vpnDnsSettings?.title ?: "недоступно"}, " + "адреса=${vpnDnsSettings?.configuredServers?.joinToString(", ")?.ifBlank { "из WireGuard-профиля" } ?: "недоступно"}, " + "smart=${vpnDnsSettings?.isSmartDns ?: "недоступно"}" ) } appendLine("Потоки: ${workers ?: "недоступно"}") appendLine( "VK-хеши: заполнено $hashCount, " + "автоматический резерв между хешами=${if (hashCount > 1) "включён" else "недоступен"}" ) appendLine("Быстрый VKCalls: ${vkCallsEnabled ?: "недоступно"}") appendLine("Сеть РТ (TURN stream-first): ${rtNetworkEnabled ?: "недоступно"}") appendLine( "MASQUE в Сети РТ (HTTP/2 → HTTP/3): ${rtMasqueEnabled ?: "недоступно"}, " + "регистрация WARP=$rtMasqueEnrollment, " + "первая регистрация через сервер=${rtMasqueServerBootstrap ?: "недоступно"}" ) appendLine( "Резерв VK: собственные=${customVkCredentialsEnabled ?: "недоступно"}, " + "заполнены=${customVkCredentialsComplete ?: "недоступно"}, встроенных=${builtInVkClientCount ?: "недоступно"}" ) appendLine("Captcha mode (legacy): ${captchaMode ?: "недоступно"}") appendLine("TLS fingerprint: ${fingerprint ?: "недоступно"}") appendLine("Режим ссылки: ${linkMode ?: "недоступно"}") appendLine("Роль интерфейса: ${interfaceRole?.ifBlank { "не выбрана" } ?: "недоступно"}") appendLine("Тема: ${themeMode ?: "недоступно"}, Dynamic Colors=${dynamicColor ?: "недоступно"}") appendLine("Логирование: ${loggingEnabled ?: "недоступно"}") }.trim().lines() }