From 98acfc9c9f13cdffa4620b7fcff0c9164f69c0cf Mon Sep 17 00:00:00 2001 From: Ivan4537 Date: Mon, 6 Jul 2026 00:18:02 +0300 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=8B=D0=BF=D1=83=D1=81=D0=BA=20WDTT=20P?= =?UTF-8?q?lus=20v8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 13 ++ README.md | 2 +- app/build.gradle.kts | 6 +- app/src/main/java/com/wdtt/plus/AppUpdate.kt | 209 +++++++++++++++--- .../main/java/com/wdtt/plus/MainActivity.kt | 66 +++--- .../main/java/com/wdtt/plus/SettingsStore.kt | 33 ++- .../java/com/wdtt/plus/ui/AppUpdateDialog.kt | 13 +- app/src/main/java/com/wdtt/plus/ui/InfoTab.kt | 93 +++++--- .../com/wdtt/plus/ui/ServerClientsSection.kt | 3 +- .../test/java/com/wdtt/plus/AppUpdateTest.kt | 93 ++++++++ 10 files changed, 432 insertions(+), 99 deletions(-) create mode 100644 app/src/test/java/com/wdtt/plus/AppUpdateTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 9606cd3..6ae8d18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ Здесь фиксируются заметные пользовательские изменения WDTT Plus. +## v8 — 06.07.2026 + +### Обновления + +- Проверка обновлений теперь различает новую версию и исправление текущей версии: если APK в уже опубликованном релизе заменён, приложение сверяет SHA-256 установленного APK со всеми APK релиза и предлагает установить исправление. +- Откладывание обновления учитывает не только номер версии, но и набор APK-хешей релиза, поэтому повторно заменённый APK той же версии снова будет предложен пользователю. +- Проверка запускается при старте приложения и повторяется каждые 30 минут, если приложение долго остаётся открытым. +- Проверка обновлений ограничена по времени и не зацикливается при недоступной сети, GitHub, сбое чтения SHA-256 установленного APK или других внутренних ошибках. + +### Интерфейс + +- Исправлен баг повторного появления блоков поиска и действий клиента при возврате на вкладку «Деплой», если «Клиенты и сервер» уже раскрыт. + ## v7 — 05.07.2026 ### Надёжность и данные diff --git a/README.md b/README.md index 6435fc1..c103c70 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ - **VK Auth fallback:** клиент использует 2 проверенных VK `client_id` и переключается между ними при ошибках авторизации. - **DNS fallback:** сначала используются Yandex DNS `77.88.8.8` / `77.88.8.1`, а при отказе или таймаутах выполняется fallback на системный провайдерский DNS устройства. - **Темы и оформление:** Material 3, Jetpack Compose, Inter, светлая/тёмная тема, Dynamic Colors на Android 12+ и встроенные палитры. -- **Автообновления:** приложение проверяет релизы WDTT Plus в этом репозитории, скачивает подходящий APK внутри приложения и передаёт его системному установщику Android. +- **Автообновления:** приложение проверяет релизы WDTT Plus при запуске и каждые 30 минут, если остаётся открытым, скачивает подходящий APK внутри приложения и передаёт его системному установщику Android. Если APK текущей версии был заменён в релизе, WDTT Plus сверяет SHA-256 установленного APK со всеми APK релиза и предлагает исправление текущей версии. ## Как это работает diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 39a83d3..fdf10d5 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -5,7 +5,7 @@ plugins { id("org.jetbrains.kotlin.plugin.compose") } -val appVersionName = "7" +val appVersionName = "8" val releaseApkBaseName = "WDTT-Plus" val localProperties = Properties() @@ -22,9 +22,9 @@ android { applicationId = "com.wdtt.plus" minSdk = 28 targetSdk = 35 - versionCode = 7 + versionCode = 8 versionName = appVersionName - buildConfigField("String", "MOD_RELEASE_DATE", "\"05.07.2026\"") + buildConfigField("String", "MOD_RELEASE_DATE", "\"06.07.2026\"") testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" vectorDrawables { diff --git a/app/src/main/java/com/wdtt/plus/AppUpdate.kt b/app/src/main/java/com/wdtt/plus/AppUpdate.kt index 828be8c..4925ca5 100644 --- a/app/src/main/java/com/wdtt/plus/AppUpdate.kt +++ b/app/src/main/java/com/wdtt/plus/AppUpdate.kt @@ -17,7 +17,7 @@ import java.security.MessageDigest import java.util.Locale const val UPDATE_CHECK_NEVER = -1 -const val DEFAULT_UPDATE_CHECK_INTERVAL_HOURS = 12 +const val DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES = 30 const val UPDATE_DIALOG_ACTION_POSTPONED = "postponed" const val UPDATE_DIALOG_ACTION_UPDATE = "update" @@ -28,15 +28,23 @@ private const val GITHUB_LATEST_RELEASE_WEB_URL = "https://github.com/Ivan4537/W private const val GITHUB_RELEASE_TAG_URL_PREFIX = "https://github.com/Ivan4537/WDTT-Plus/releases/tag/" private const val GITHUB_TAGS_URL = "https://api.github.com/repos/Ivan4537/WDTT-Plus/tags?per_page=100" private const val GITHUB_TAG_TREE_URL_PREFIX = "https://github.com/Ivan4537/WDTT-Plus/tree/" +private const val UPDATE_CHECK_TOTAL_TIMEOUT_MS = 25_000L +private const val UPDATE_CHECK_REQUEST_TIMEOUT_MS = 6_000L +private const val UPDATE_CHECK_MIN_REQUEST_TIMEOUT_MS = 1_000L +private const val UPDATE_APK_HASH_TIMEOUT_MS = 4_000L private const val GITHUB_API_RATE_LIMIT_FALLBACK_MS = 30L * 60L * 1000L private val SIMPLE_VERSION_TAG_REGEX = Regex("^v?(\\d+)$", RegexOption.IGNORE_CASE) @Volatile private var githubApiCooldownUntilMs = 0L -fun updateIntervalHoursToMillis(hours: Int): Long? = when { - hours <= 0 -> null - else -> hours * 60L * 60L * 1000L +@Volatile +private var installedApkSha256Cache: InstalledApkSha256Cache? = null + +fun updateIntervalMinutesToMillis(minutes: Int): Long? = when { + minutes == UPDATE_CHECK_NEVER -> null + minutes <= 0 -> null + else -> minutes.coerceAtLeast(DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES) * 60L * 1000L } data class AppReleaseInfo( @@ -77,16 +85,63 @@ enum class RemoteVersionSource { Tag } +enum class AppUpdateKind { + NewVersion, + SameVersionFix +} + +data class AppUpdateCandidate( + val release: AppReleaseInfo, + val kind: AppUpdateKind, + val sameVersionFixKey: String? = null +) { + val postponeKey: String + get() = when (kind) { + AppUpdateKind.NewVersion -> release.versionTag + AppUpdateKind.SameVersionFix -> sameVersionFixKey ?: "${release.versionTag}:fix" + } +} + +private data class InstalledApkSha256Cache( + val path: String, + val length: Long, + val lastModified: Long, + val sha256: String +) + +private class UpdateCheckBudget( + timeoutMs: Long = UPDATE_CHECK_TOTAL_TIMEOUT_MS +) { + private val deadlineAt = System.currentTimeMillis() + timeoutMs + + val expired: Boolean + get() = System.currentTimeMillis() >= deadlineAt + + fun timeoutForHttpPhase(): Int? { + val remaining = deadlineAt - System.currentTimeMillis() + if (remaining < UPDATE_CHECK_MIN_REQUEST_TIMEOUT_MS * 2L) return null + return minOf( + UPDATE_CHECK_REQUEST_TIMEOUT_MS, + (remaining / 2L).coerceAtLeast(UPDATE_CHECK_MIN_REQUEST_TIMEOUT_MS) + ).toInt() + } + + fun requireTimeLeft(operation: String) { + if (expired) throw IOException("$operation не уложилась в лимит времени") + } +} + suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo? = withContext(Dispatchers.IO) { - val webRelease = fetchReleaseFromLatestWebRedirect() - val apiRelease = fetchReleaseFromLatestEndpoint() ?: fetchLatestStableReleaseFromList() + val budget = UpdateCheckBudget() + val webRelease = fetchReleaseFromLatestWebRedirect(budget) + val apiRelease = fetchReleaseFromLatestEndpoint(budget) ?: fetchLatestStableReleaseFromList(budget) val latestRelease = when { webRelease == null -> apiRelease - apiRelease == null -> fetchReleaseByTag(webRelease.versionTag) ?: webRelease - isNewerVersion(apiRelease.versionTag, webRelease.versionTag) -> fetchReleaseByTag(webRelease.versionTag) ?: webRelease + apiRelease == null -> fetchReleaseByTag(webRelease.versionTag, budget) ?: webRelease + isNewerVersion(apiRelease.versionTag, webRelease.versionTag) -> fetchReleaseByTag(webRelease.versionTag, budget) ?: webRelease else -> apiRelease } - val latestTag = fetchLatestTagFromList() + val latestTag = fetchLatestTagFromList(budget) when { latestRelease == null -> latestTag @@ -96,6 +151,33 @@ suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo } } +suspend fun resolveAppUpdateCandidate( + context: Context, + localVersion: String, + release: AppReleaseInfo? +): AppUpdateCandidate? = withContext(Dispatchers.IO) { + if (release == null) return@withContext null + if (isNewerVersion(localVersion, release.versionTag)) { + return@withContext AppUpdateCandidate( + release = release, + kind = AppUpdateKind.NewVersion + ) + } + + if (!isSameVersion(localVersion, release.versionTag) || release.source != RemoteVersionSource.Release) { + return@withContext null + } + + val installedSha256 = installedApkSha256(context, UpdateCheckBudget(UPDATE_APK_HASH_TIMEOUT_MS)) + ?: return@withContext null + if (!hasSameVersionApkFix(installedSha256, release)) return@withContext null + AppUpdateCandidate( + release = release, + kind = AppUpdateKind.SameVersionFix, + sameVersionFixKey = sameVersionFixPostponeKey(release) + ) +} + fun selectUpdateApkAsset(release: AppReleaseInfo): AppReleaseAsset? { val apkAssets = release.assets .filter { it.name.endsWith(".apk", ignoreCase = true) && it.downloadUrl.isNotBlank() } @@ -222,8 +304,45 @@ fun isNewerVersion(local: String, remote: String): Boolean { return false } -private fun fetchLatestStableReleaseFromList(): AppReleaseInfo? { - val response = fetchGitHubApi(GITHUB_RELEASES_URL) ?: return null +fun isSameVersion(left: String, right: String): Boolean { + val leftNumber = versionNumber(left) ?: return false + val rightNumber = versionNumber(right) ?: return false + return leftNumber == rightNumber +} + +internal fun releaseApkSha256Set(release: AppReleaseInfo): Set { + return release.assets + .asSequence() + .filter { it.name.endsWith(".apk", ignoreCase = true) } + .mapNotNull { it.sha256 } + .map { it.lowercase(Locale.US) } + .toSet() +} + +internal fun hasSameVersionApkFix(installedSha256: String?, release: AppReleaseInfo): Boolean { + val installed = installedSha256 + ?.trim() + ?.lowercase(Locale.US) + ?.takeIf { it.matches(Regex("^[0-9a-f]{64}$")) } + ?: return false + val officialApkHashes = releaseApkSha256Set(release) + return officialApkHashes.isNotEmpty() && installed !in officialApkHashes +} + +internal fun sameVersionFixPostponeKey(release: AppReleaseInfo): String? { + val officialApkHashes = releaseApkSha256Set(release) + .takeIf { it.isNotEmpty() } + ?: return null + val fingerprint = officialApkHashes + .sorted() + .joinToString("\n") + .sha256Hex() + .take(16) + return "${release.versionTag}:fix:$fingerprint" +} + +private fun fetchLatestStableReleaseFromList(budget: UpdateCheckBudget): AppReleaseInfo? { + val response = fetchGitHubApi(GITHUB_RELEASES_URL, budget) ?: return null val releases = try { JSONArray(response) } catch (e: Exception) { @@ -243,8 +362,8 @@ private fun fetchLatestStableReleaseFromList(): AppReleaseInfo? { return bestRelease } -private fun fetchLatestTagFromList(): AppReleaseInfo? { - val response = fetchGitHubApi(GITHUB_TAGS_URL) ?: return null +private fun fetchLatestTagFromList(budget: UpdateCheckBudget): AppReleaseInfo? { + val response = fetchGitHubApi(GITHUB_TAGS_URL, budget) ?: return null val tags = try { JSONArray(response) } catch (e: Exception) { @@ -269,8 +388,8 @@ private fun fetchLatestTagFromList(): AppReleaseInfo? { return bestTag } -private fun fetchReleaseFromLatestEndpoint(): AppReleaseInfo? { - val response = fetchGitHubApi(GITHUB_LATEST_RELEASE_URL) ?: return null +private fun fetchReleaseFromLatestEndpoint(budget: UpdateCheckBudget): AppReleaseInfo? { + val response = fetchGitHubApi(GITHUB_LATEST_RELEASE_URL, budget) ?: return null val json = try { JSONObject(response) } catch (e: Exception) { @@ -280,10 +399,10 @@ private fun fetchReleaseFromLatestEndpoint(): AppReleaseInfo? { return json.toAppReleaseInfo() } -private fun fetchReleaseByTag(tag: String): AppReleaseInfo? { +private fun fetchReleaseByTag(tag: String, budget: UpdateCheckBudget): AppReleaseInfo? { val normalizedTag = normalizeVersionTag(tag) if (normalizedTag.isBlank()) return null - val response = fetchGitHubApi("https://api.github.com/repos/Ivan4537/WDTT-Plus/releases/tags/$normalizedTag") + val response = fetchGitHubApi("https://api.github.com/repos/Ivan4537/WDTT-Plus/releases/tags/$normalizedTag", budget) ?: return null val json = try { JSONObject(response) @@ -294,17 +413,18 @@ private fun fetchReleaseByTag(tag: String): AppReleaseInfo? { return json.toAppReleaseInfo() } -private fun fetchReleaseFromLatestWebRedirect(): AppReleaseInfo? { +private fun fetchReleaseFromLatestWebRedirect(budget: UpdateCheckBudget): AppReleaseInfo? { var conn: HttpURLConnection? = null return try { + val requestTimeout = budget.timeoutForHttpPhase() ?: return null conn = URL(GITHUB_LATEST_RELEASE_WEB_URL).openConnection() as HttpURLConnection applyNoCacheHeaders(conn) conn.instanceFollowRedirects = false conn.requestMethod = "GET" conn.setRequestProperty("Accept", "text/html,*/*") conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}") - conn.connectTimeout = 8_000 - conn.readTimeout = 8_000 + conn.connectTimeout = requestTimeout + conn.readTimeout = requestTimeout val responseCode = conn.responseCode val location = conn.getHeaderField("Location") @@ -334,13 +454,14 @@ private fun fetchReleaseFromLatestWebRedirect(): AppReleaseInfo? { } } -private fun fetchGitHubApi(url: String): String? { +private fun fetchGitHubApi(url: String, budget: UpdateCheckBudget): String? { val now = System.currentTimeMillis() - if (now < githubApiCooldownUntilMs) return null + if (now < githubApiCooldownUntilMs || budget.expired) return null return fetchHttpText( url = url, sourceLabel = "GitHub API", accept = "application/vnd.github+json", + budget = budget, isGitHubApi = true ) } @@ -349,10 +470,12 @@ private fun fetchHttpText( url: String, sourceLabel: String, accept: String, + budget: UpdateCheckBudget, isGitHubApi: Boolean = false ): String? { var conn: HttpURLConnection? = null return try { + val requestTimeout = budget.timeoutForHttpPhase() ?: return null conn = URL(url).openConnection() as HttpURLConnection applyNoCacheHeaders(conn) conn.requestMethod = "GET" @@ -361,8 +484,8 @@ private fun fetchHttpText( conn.setRequestProperty("X-GitHub-Api-Version", "2022-11-28") } conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}") - conn.connectTimeout = 8_000 - conn.readTimeout = 8_000 + conn.connectTimeout = requestTimeout + conn.readTimeout = requestTimeout val responseCode = conn.responseCode val stream = if (responseCode in 200..299) conn.inputStream else conn.errorStream @@ -476,11 +599,42 @@ private fun String.safeUpdateAssetName(): String { return if (cleaned.endsWith(".apk", ignoreCase = true)) cleaned else "$cleaned.apk" } -private fun File.sha256Hex(): String { +private fun installedApkSha256(context: Context, budget: UpdateCheckBudget): String? { + val appContext = context.applicationContext + val path = appContext.applicationInfo.sourceDir?.takeIf { it.isNotBlank() } ?: return null + val apkFile = File(path) + if (!apkFile.isFile) return null + + val cached = installedApkSha256Cache + if ( + cached != null && + cached.path == apkFile.absolutePath && + cached.length == apkFile.length() && + cached.lastModified == apkFile.lastModified() + ) { + return cached.sha256 + } + + return runCatching { + apkFile.sha256Hex(budget) + }.onSuccess { sha -> + installedApkSha256Cache = InstalledApkSha256Cache( + path = apkFile.absolutePath, + length = apkFile.length(), + lastModified = apkFile.lastModified(), + sha256 = sha + ) + }.onFailure { error -> + Log.w(UPDATE_LOG_TAG, "[WARN] Update check: failed to hash installed APK", error) + }.getOrNull() +} + +private fun File.sha256Hex(budget: UpdateCheckBudget? = null): String { val digest = MessageDigest.getInstance("SHA-256") inputStream().use { input -> val buffer = ByteArray(DEFAULT_BUFFER_SIZE) while (true) { + budget?.requireTimeLeft("SHA-256 установленного APK") val read = input.read(buffer) if (read < 0) break digest.update(buffer, 0, read) @@ -488,3 +642,8 @@ private fun File.sha256Hex(): String { } return digest.digest().joinToString("") { "%02x".format(it) } } + +private fun String.sha256Hex(): String { + val digest = MessageDigest.getInstance("SHA-256") + return digest.digest(toByteArray(Charsets.UTF_8)).joinToString("") { "%02x".format(it) } +} diff --git a/app/src/main/java/com/wdtt/plus/MainActivity.kt b/app/src/main/java/com/wdtt/plus/MainActivity.kt index 9157346..6fb7f6c 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -678,10 +678,10 @@ fun MainScreen( val infoScrollPosition = rememberSaveable { mutableIntStateOf(0) } var dragTargetIndex by remember { mutableIntStateOf(-1) } var dragProgress by remember { mutableFloatStateOf(0f) } - val updateCheckIntervalHours by settingsStore.updateCheckIntervalHours.collectAsStateWithLifecycle( - initialValue = DEFAULT_UPDATE_CHECK_INTERVAL_HOURS + val updateCheckIntervalMinutes by settingsStore.updateCheckIntervalMinutes.collectAsStateWithLifecycle( + initialValue = DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES ) - var pendingRelease by remember { mutableStateOf(null) } + var pendingUpdateCandidate by remember { mutableStateOf(null) } var updateDownloadProgress by remember { mutableStateOf(null) } var updateDownloadStatus by rememberSaveable { mutableStateOf("") } var updateDownloadBusy by remember { mutableStateOf(false) } @@ -699,7 +699,7 @@ fun MainScreen( if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) { runCatching { installUpdateApk(context, apkFile) - pendingRelease = null + pendingUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null }.onFailure { error -> @@ -726,7 +726,7 @@ fun MainScreen( runCatching { installUpdateApk(context, apkFile) - pendingRelease = null + pendingUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null }.onFailure { error -> @@ -837,20 +837,33 @@ fun MainScreen( if (selectedTab == 3) TunnelManager.clearUnreadErrors() } - LaunchedEffect(updateCheckIntervalHours) { - if (updateCheckIntervalHours == UPDATE_CHECK_NEVER) return@LaunchedEffect + LaunchedEffect(updateCheckIntervalMinutes) { + if (updateCheckIntervalMinutes == UPDATE_CHECK_NEVER) return@LaunchedEffect - val intervalMillis = updateIntervalHoursToMillis(updateCheckIntervalHours) - ?: updateIntervalHoursToMillis(DEFAULT_UPDATE_CHECK_INTERVAL_HOURS) - ?: 12L * 60L * 60L * 1000L + val intervalMillis = updateIntervalMinutesToMillis(updateCheckIntervalMinutes) + ?: updateIntervalMinutesToMillis(DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES) + ?: DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES * 60L * 1000L suspend fun runUpdateCheck(reason: String) { val checkedAt = System.currentTimeMillis() - val release = fetchLatestReleaseInfo(currentVersion) + var release: AppReleaseInfo? = null + var updateCandidate: AppUpdateCandidate? = null + var errorMessage = "" + runCatching { + release = fetchLatestReleaseInfo(currentVersion) + if (release == null) { + errorMessage = "Не удалось проверить" + return@runCatching + } + updateCandidate = resolveAppUpdateCandidate(context, currentVersion, release) + }.onFailure { error -> + errorMessage = error.message ?: "Не удалось проверить" + Log.w("WDTT", "[WARN] Update check failed unexpectedly, local=$currentVersion reason=$reason", error) + } settingsStore.saveUpdateState( lastCheckAt = checkedAt, latestVersion = release?.versionTag ?: "", - error = if (release == null) "Не удалось проверить" else "" + error = errorMessage ) if (release == null) { @@ -858,18 +871,19 @@ fun MainScreen( return } - val hasUpdate = isNewerVersion(currentVersion, release.versionTag) + val candidate = updateCandidate + val hasUpdate = candidate != null val postponeVer = settingsStore.updatePostponeVersion.first() val postponeUntil = settingsStore.updatePostponeUntil.first() - val isPostponed = postponeVer == release.versionTag && checkedAt < postponeUntil + val isPostponed = candidate != null && postponeVer == candidate.postponeKey && checkedAt < postponeUntil Log.i( "WDTT", - "Update check: local=$currentVersion remote=${release.versionTag} newer=$hasUpdate postponed=$isPostponed reason=$reason" + "Update check: local=$currentVersion remote=${release?.versionTag} candidate=${candidate?.kind} newer=$hasUpdate postponed=$isPostponed reason=$reason" ) - if (hasUpdate && !isPostponed) { - settingsStore.saveUpdateDialogShown(release.versionTag, checkedAt) - pendingRelease = release + if (candidate != null && !isPostponed) { + settingsStore.saveUpdateDialogShown(candidate.postponeKey, checkedAt) + pendingUpdateCandidate = candidate } } @@ -1158,27 +1172,29 @@ fun MainScreen( ) } - pendingRelease?.let { release -> + pendingUpdateCandidate?.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 = { - pendingRelease = null + pendingUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show() scope.launch { val now = System.currentTimeMillis() settingsStore.saveUpdatePostpone( - version = release.versionTag, + version = candidate.postponeKey, until = now + 24L * 60L * 60L * 1000L ) settingsStore.saveUpdateDialogAction( - version = release.versionTag, + version = candidate.postponeKey, action = UPDATE_DIALOG_ACTION_POSTPONED, actedAt = now ) @@ -1187,12 +1203,12 @@ fun MainScreen( onUpdate = { scope.launch { settingsStore.saveUpdateDialogAction( - version = release.versionTag, + version = candidate.postponeKey, action = UPDATE_DIALOG_ACTION_UPDATE, actedAt = System.currentTimeMillis() ) if (apkAsset == null) { - pendingRelease = null + pendingUpdateCandidate = null openReleaseUrl(context, release.releaseUrl) return@launch } @@ -1223,7 +1239,7 @@ fun MainScreen( } }, onOpenRelease = { - pendingRelease = null + pendingUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null openReleaseUrl(context, release.releaseUrl) diff --git a/app/src/main/java/com/wdtt/plus/SettingsStore.kt b/app/src/main/java/com/wdtt/plus/SettingsStore.kt index a1dc571..1ad4065 100644 --- a/app/src/main/java/com/wdtt/plus/SettingsStore.kt +++ b/app/src/main/java/com/wdtt/plus/SettingsStore.kt @@ -303,7 +303,7 @@ class SettingsStore(context: Context) { private val UPDATE_LAST_CHECK_AT = longPreferencesKey("update_last_check_at") private val UPDATE_LATEST_VERSION = stringPreferencesKey("update_latest_version") private val UPDATE_LAST_ERROR = stringPreferencesKey("update_last_error") - private val UPDATE_CHECK_INTERVAL_HOURS = intPreferencesKey("update_check_interval_hours") + private val UPDATE_CHECK_INTERVAL_MINUTES = intPreferencesKey("update_check_interval_hours") private val UPDATE_POSTPONE_UNTIL = longPreferencesKey("update_postpone_until") private val UPDATE_POSTPONE_VERSION = stringPreferencesKey("update_postpone_version") private val UPDATE_DIALOG_LAST_SHOWN_VERSION = stringPreferencesKey("update_dialog_last_shown_version") @@ -529,7 +529,9 @@ class SettingsStore(context: Context) { val updateLastCheckAt: Flow = dataStore.data.map { it[UPDATE_LAST_CHECK_AT] ?: 0L } val updateLatestVersion: Flow = dataStore.data.map { it[UPDATE_LATEST_VERSION] ?: "" } val updateLastError: Flow = dataStore.data.map { it[UPDATE_LAST_ERROR] ?: "" } - val updateCheckIntervalHours: Flow = dataStore.data.map { it[UPDATE_CHECK_INTERVAL_HOURS] ?: 24 } + val updateCheckIntervalMinutes: Flow = dataStore.data.map { + normalizeUpdateCheckIntervalMinutes(it[UPDATE_CHECK_INTERVAL_MINUTES] ?: DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES) + } val updatePostponeUntil: Flow = dataStore.data.map { it[UPDATE_POSTPONE_UNTIL] ?: 0L } val updatePostponeVersion: Flow = dataStore.data.map { it[UPDATE_POSTPONE_VERSION] ?: "" } val updateDialogLastShownVersion: Flow = dataStore.data.map { it[UPDATE_DIALOG_LAST_SHOWN_VERSION] ?: "" } @@ -615,9 +617,9 @@ class SettingsStore(context: Context) { } } - suspend fun saveUpdateCheckIntervalHours(hours: Int) { + suspend fun saveUpdateCheckIntervalMinutes(minutes: Int) { dataStore.edit { prefs -> - prefs[UPDATE_CHECK_INTERVAL_HOURS] = hours + prefs[UPDATE_CHECK_INTERVAL_MINUTES] = normalizeUpdateCheckIntervalMinutes(minutes) } } @@ -827,7 +829,12 @@ class SettingsStore(context: Context) { put("themePalette", prefs[THEME_PALETTE] ?: "indigo") put("showSystemApps", prefs[SHOW_SYSTEM_APPS] ?: false) put("loggingEnabled", prefs[LOGGING_ENABLED] ?: true) - put("updateCheckIntervalHours", prefs[UPDATE_CHECK_INTERVAL_HOURS] ?: 12) + put( + "updateCheckIntervalMinutes", + normalizeUpdateCheckIntervalMinutes( + prefs[UPDATE_CHECK_INTERVAL_MINUTES] ?: DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES + ) + ) put("profiles", profiles) put("outbound", exportSharedPreferences("wdtt_outbound_forms")) }.toString() @@ -900,7 +907,14 @@ class SettingsStore(context: Context) { prefs[THEME_PALETTE] = root.optString("themePalette", "indigo") prefs[SHOW_SYSTEM_APPS] = root.optBoolean("showSystemApps") prefs[LOGGING_ENABLED] = root.optBoolean("loggingEnabled", true) - prefs[UPDATE_CHECK_INTERVAL_HOURS] = root.optInt("updateCheckIntervalHours", 12) + val updateIntervalMinutes = when { + root.has("updateCheckIntervalMinutes") -> + root.optInt("updateCheckIntervalMinutes", DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES) + root.has("updateCheckIntervalHours") -> + root.optInt("updateCheckIntervalHours", 1) * 60 + else -> DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES + }.let(::normalizeUpdateCheckIntervalMinutes) + prefs[UPDATE_CHECK_INTERVAL_MINUTES] = updateIntervalMinutes prefs[INTERFACE_ROLE] = "admin" } importSharedPreferences("wdtt_outbound_forms", root.optJSONObject("outbound") ?: JSONObject()) @@ -1311,6 +1325,13 @@ fun sanitizeVpnProfileNameInput(name: String): String { fun normalizeVpnProfileName(name: String): String = sanitizeVpnProfileNameInput(name).trimEnd() +fun normalizeUpdateCheckIntervalMinutes(minutes: Int): Int = + if (minutes == UPDATE_CHECK_NEVER) { + UPDATE_CHECK_NEVER + } else { + minutes.coerceAtLeast(DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES) + } + fun vpnProfileDisplayName(profile: Int, names: List): String { val clean = normalizeVpnProfileName(names.getOrNull(profile).orEmpty()) return clean.ifBlank { vpnProfileDefaultName(profile) } diff --git a/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt b/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt index 9576460..1c7e6c8 100644 --- a/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt @@ -34,11 +34,13 @@ import androidx.compose.ui.window.DialogProperties import com.wdtt.plus.AppReleaseInfo import com.wdtt.plus.AppReleaseAsset import com.wdtt.plus.AppUpdateDownloadProgress +import com.wdtt.plus.AppUpdateKind import com.wdtt.plus.RemoteVersionSource @Composable fun AppUpdateDialog( release: AppReleaseInfo, + updateKind: AppUpdateKind = AppUpdateKind.NewVersion, apkAsset: AppReleaseAsset?, isDownloading: Boolean, downloadProgress: AppUpdateDownloadProgress?, @@ -48,9 +50,18 @@ fun AppUpdateDialog( onOpenRelease: () -> Unit ) { val isTagOnly = release.source == RemoteVersionSource.Tag - val title = if (isTagOnly) "Найден новый tag" else "Доступно обновление" + val isSameVersionFix = updateKind == AppUpdateKind.SameVersionFix + val title = when { + isSameVersionFix -> "Доступно исправление" + isTagOnly -> "Найден новый tag" + else -> "Доступно обновление" + } val canDownloadInApp = !isTagOnly && apkAsset != null val description = when { + isSameVersionFix && canDownloadInApp -> + "Версия ${release.versionTag} не изменилась, но APK в релизе обновлён. Это исправление текущей версии; WDTT Plus скачает подходящий файл и откроет установку Android." + isSameVersionFix -> + "Версия ${release.versionTag} не изменилась, но APK в релизе обновлён. Не удалось подобрать файл для этого устройства, можно открыть страницу релиза." isTagOnly -> "На GitHub обнаружен более новый tag ${release.versionTag}. Похоже, опубликованный release ещё не догнал его." canDownloadInApp -> diff --git a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt index 8aa4685..1101b9a 100644 --- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt @@ -111,6 +111,7 @@ 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.canRequestApkInstall import com.wdtt.plus.downloadUpdateApk @@ -118,6 +119,7 @@ import com.wdtt.plus.fetchLatestReleaseInfo import com.wdtt.plus.installUpdateApk import com.wdtt.plus.isNewerVersion import com.wdtt.plus.label +import com.wdtt.plus.resolveAppUpdateCandidate import com.wdtt.plus.selectUpdateApkAsset import com.wdtt.plus.deviceCheckActionIntent import kotlinx.coroutines.Dispatchers @@ -231,7 +233,7 @@ fun InfoTab( val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" } val releaseDate = remember { BuildConfig.MOD_RELEASE_DATE } var isCheckingUpdates by remember { mutableStateOf(false) } - var pendingManualRelease by remember { mutableStateOf(null) } + var pendingManualUpdateCandidate by remember { mutableStateOf(null) } var updateDownloadProgress by remember { mutableStateOf(null) } var updateDownloadStatus by rememberSaveable { mutableStateOf("") } var updateDownloadBusy by remember { mutableStateOf(false) } @@ -261,7 +263,7 @@ fun InfoTab( if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) { runCatching { installUpdateApk(context, apkFile) - pendingManualRelease = null + pendingManualUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null }.onFailure { error -> @@ -289,7 +291,7 @@ fun InfoTab( runCatching { installUpdateApk(context, apkFile) - pendingManualRelease = null + pendingManualUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null }.onFailure { error -> @@ -470,34 +472,51 @@ fun InfoTab( isCheckingUpdates = true scope.launch { val checkedAt = System.currentTimeMillis() - val release = fetchLatestReleaseInfo(currentVersion) - val latest = release?.versionTag - settingsStore.saveUpdateState( - lastCheckAt = checkedAt, - latestVersion = latest ?: "", - error = if (release == null) "Не удалось проверить" else "" - ) - isCheckingUpdates = false - - if (release == null) { - val message = if (updateLatestVersion.isNotBlank()) { - "Не удалось проверить. Последняя известная версия: $updateLatestVersion" - } else { - "Не удалось проверить обновления" + var release: AppReleaseInfo? = null + var updateCandidate: AppUpdateCandidate? = null + var errorMessage = "" + try { + runCatching { + release = fetchLatestReleaseInfo(currentVersion) + if (release == null) { + errorMessage = "Не удалось проверить" + return@runCatching + } + updateCandidate = resolveAppUpdateCandidate(context, currentVersion, release) + }.onFailure { error -> + errorMessage = error.message ?: "Не удалось проверить обновления" } - Toast.makeText(context, message, Toast.LENGTH_SHORT).show() - return@launch - } - if (isNewerVersion(currentVersion, release.versionTag)) { - settingsStore.saveUpdateDialogShown(release.versionTag, checkedAt) - pendingManualRelease = release - } else { - Toast.makeText( - context, - "У вас уже последняя версия: ${release.versionTag}", - Toast.LENGTH_SHORT - ).show() + 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 } } }, @@ -512,27 +531,29 @@ fun InfoTab( ) } - pendingManualRelease?.let { release -> + 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 = { - pendingManualRelease = null + pendingManualUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show() scope.launch { val now = System.currentTimeMillis() settingsStore.saveUpdatePostpone( - version = release.versionTag, + version = candidate.postponeKey, until = now + 24L * 60L * 60L * 1000L ) settingsStore.saveUpdateDialogAction( - version = release.versionTag, + version = candidate.postponeKey, action = UPDATE_DIALOG_ACTION_POSTPONED, actedAt = now ) @@ -541,12 +562,12 @@ fun InfoTab( onUpdate = { scope.launch { settingsStore.saveUpdateDialogAction( - version = release.versionTag, + version = candidate.postponeKey, action = UPDATE_DIALOG_ACTION_UPDATE, actedAt = System.currentTimeMillis() ) if (apkAsset == null) { - pendingManualRelease = null + pendingManualUpdateCandidate = null openUrlInBrowser(context, release.releaseUrl) return@launch } @@ -577,7 +598,7 @@ fun InfoTab( } }, onOpenRelease = { - pendingManualRelease = null + pendingManualUpdateCandidate = null updateDownloadStatus = "" updateDownloadProgress = null openUrlInBrowser(context, release.releaseUrl) diff --git a/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt index f322c3c..a6d5bcb 100644 --- a/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt +++ b/app/src/main/java/com/wdtt/plus/ui/ServerClientsSection.kt @@ -662,9 +662,8 @@ fun ServerClientsSection( ClientStatusBanner(status = status, busy = busy) } - AnimatedVisibility(state != null) { + state?.let { current -> Column(verticalArrangement = Arrangement.spacedBy(10.dp)) { - val current = state ?: return@AnimatedVisibility val activeFilterCount = activeClientFilterCount(statusFilter, bindingFilter, expiryFilter, vkHashFilter) ClientPanel { Text( diff --git a/app/src/test/java/com/wdtt/plus/AppUpdateTest.kt b/app/src/test/java/com/wdtt/plus/AppUpdateTest.kt new file mode 100644 index 0000000..43d3e28 --- /dev/null +++ b/app/src/test/java/com/wdtt/plus/AppUpdateTest.kt @@ -0,0 +1,93 @@ +package com.wdtt.plus + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class AppUpdateTest { + private val universalSha = "0".repeat(64) + private val arm64Sha = "1".repeat(64) + private val staleSha = "2".repeat(64) + + @Test + fun sameVersionFix_isNotReportedWhenInstalledShaMatchesAnyReleaseApk() { + val release = releaseWithHashes(universalSha, arm64Sha) + + assertFalse(hasSameVersionApkFix(universalSha, release)) + assertFalse(hasSameVersionApkFix(arm64Sha, release)) + } + + @Test + fun sameVersionFix_isReportedWhenInstalledShaIsAbsentFromReleaseApks() { + val release = releaseWithHashes(universalSha, arm64Sha) + + assertTrue(hasSameVersionApkFix(staleSha, release)) + } + + @Test + fun sameVersionFix_isNotReportedWithoutGithubApkDigests() { + val release = AppReleaseInfo( + versionTag = "v7", + releaseUrl = "https://example.org/v7", + source = RemoteVersionSource.Release, + assets = listOf( + AppReleaseAsset( + name = "WDTT-Plus-v7-arm64-v8a-release.apk", + downloadUrl = "https://example.org/app.apk", + sizeBytes = 1L, + digest = "" + ) + ) + ) + + assertFalse(hasSameVersionApkFix(staleSha, release)) + } + + @Test + fun sameVersionFixPostponeKey_changesWhenReleaseApkHashesChange() { + val first = sameVersionFixPostponeKey(releaseWithHashes(universalSha, arm64Sha)) + val second = sameVersionFixPostponeKey(releaseWithHashes(universalSha, staleSha)) + + assertNotEquals(first, second) + } + + @Test + fun versionComparison_supportsSameIntegerTags() { + assertTrue(isSameVersion("7", "v7")) + assertTrue(isSameVersion("v7", "7")) + assertFalse(isSameVersion("v7", "v8")) + assertEquals(false, isNewerVersion("v7", "v7")) + } + + @Test + fun updateInterval_usesAtLeastThirtyMinutesAndSupportsNever() { + assertEquals(null, updateIntervalMinutesToMillis(UPDATE_CHECK_NEVER)) + assertEquals(30L * 60L * 1000L, updateIntervalMinutesToMillis(1)) + assertEquals(30L * 60L * 1000L, updateIntervalMinutesToMillis(DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES)) + assertEquals(45L * 60L * 1000L, updateIntervalMinutesToMillis(45)) + assertEquals(UPDATE_CHECK_NEVER, normalizeUpdateCheckIntervalMinutes(UPDATE_CHECK_NEVER)) + assertEquals(DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES, normalizeUpdateCheckIntervalMinutes(1)) + } + + private fun releaseWithHashes(vararg hashes: String): AppReleaseInfo { + return AppReleaseInfo( + versionTag = "v7", + releaseUrl = "https://example.org/v7", + source = RemoteVersionSource.Release, + assets = hashes.mapIndexed { index, hash -> + AppReleaseAsset( + name = if (index == 0) { + "WDTT-Plus-v7-universal-release.apk" + } else { + "WDTT-Plus-v7-arm64-v8a-release.apk" + }, + downloadUrl = "https://example.org/app-$index.apk", + sizeBytes = 1L, + digest = "sha256:$hash" + ) + } + ) + } +}