Выпуск WDTT Plus v8
This commit is contained in:
1 parent
2ea94d9547
commit
98acfc9c9f
10 files changed
+432
-99
No files matched your search
@@ -2,6 +2,19 @@
|
|||||||
|
|
||||||
Здесь фиксируются заметные пользовательские изменения WDTT Plus.
|
Здесь фиксируются заметные пользовательские изменения WDTT Plus.
|
||||||
|
|
||||||
|
## v8 — 06.07.2026
|
||||||
|
|
||||||
|
### Обновления
|
||||||
|
|
||||||
|
- Проверка обновлений теперь различает новую версию и исправление текущей версии: если APK в уже опубликованном релизе заменён, приложение сверяет SHA-256 установленного APK со всеми APK релиза и предлагает установить исправление.
|
||||||
|
- Откладывание обновления учитывает не только номер версии, но и набор APK-хешей релиза, поэтому повторно заменённый APK той же версии снова будет предложен пользователю.
|
||||||
|
- Проверка запускается при старте приложения и повторяется каждые 30 минут, если приложение долго остаётся открытым.
|
||||||
|
- Проверка обновлений ограничена по времени и не зацикливается при недоступной сети, GitHub, сбое чтения SHA-256 установленного APK или других внутренних ошибках.
|
||||||
|
|
||||||
|
### Интерфейс
|
||||||
|
|
||||||
|
- Исправлен баг повторного появления блоков поиска и действий клиента при возврате на вкладку «Деплой», если «Клиенты и сервер» уже раскрыт.
|
||||||
|
|
||||||
## v7 — 05.07.2026
|
## v7 — 05.07.2026
|
||||||
|
|
||||||
### Надёжность и данные
|
### Надёжность и данные
|
||||||
|
|||||||
@@ -78,7 +78,7 @@
|
|||||||
- **VK Auth fallback:** клиент использует 2 проверенных VK `client_id` и переключается между ними при ошибках авторизации.
|
- **VK Auth fallback:** клиент использует 2 проверенных VK `client_id` и переключается между ними при ошибках авторизации.
|
||||||
- **DNS fallback:** сначала используются Yandex DNS `77.88.8.8` / `77.88.8.1`, а при отказе или таймаутах выполняется fallback на системный провайдерский DNS устройства.
|
- **DNS fallback:** сначала используются Yandex DNS `77.88.8.8` / `77.88.8.1`, а при отказе или таймаутах выполняется fallback на системный провайдерский DNS устройства.
|
||||||
- **Темы и оформление:** Material 3, Jetpack Compose, Inter, светлая/тёмная тема, Dynamic Colors на Android 12+ и встроенные палитры.
|
- **Темы и оформление:** 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 релиза и предлагает исправление текущей версии.
|
||||||
|
|
||||||
## Как это работает
|
## Как это работает
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ plugins {
|
|||||||
id("org.jetbrains.kotlin.plugin.compose")
|
id("org.jetbrains.kotlin.plugin.compose")
|
||||||
}
|
}
|
||||||
|
|
||||||
val appVersionName = "7"
|
val appVersionName = "8"
|
||||||
val releaseApkBaseName = "WDTT-Plus"
|
val releaseApkBaseName = "WDTT-Plus"
|
||||||
|
|
||||||
val localProperties = Properties()
|
val localProperties = Properties()
|
||||||
@@ -22,9 +22,9 @@ android {
|
|||||||
applicationId = "com.wdtt.plus"
|
applicationId = "com.wdtt.plus"
|
||||||
minSdk = 28
|
minSdk = 28
|
||||||
targetSdk = 35
|
targetSdk = 35
|
||||||
versionCode = 7
|
versionCode = 8
|
||||||
versionName = appVersionName
|
versionName = appVersionName
|
||||||
buildConfigField("String", "MOD_RELEASE_DATE", "\"05.07.2026\"")
|
buildConfigField("String", "MOD_RELEASE_DATE", "\"06.07.2026\"")
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
vectorDrawables {
|
vectorDrawables {
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import java.security.MessageDigest
|
|||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
|
|
||||||
const val UPDATE_CHECK_NEVER = -1
|
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_POSTPONED = "postponed"
|
||||||
const val UPDATE_DIALOG_ACTION_UPDATE = "update"
|
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_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_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 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 const val GITHUB_API_RATE_LIMIT_FALLBACK_MS = 30L * 60L * 1000L
|
||||||
private val SIMPLE_VERSION_TAG_REGEX = Regex("^v?(\\d+)$", RegexOption.IGNORE_CASE)
|
private val SIMPLE_VERSION_TAG_REGEX = Regex("^v?(\\d+)$", RegexOption.IGNORE_CASE)
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
private var githubApiCooldownUntilMs = 0L
|
private var githubApiCooldownUntilMs = 0L
|
||||||
|
|
||||||
fun updateIntervalHoursToMillis(hours: Int): Long? = when {
|
@Volatile
|
||||||
hours <= 0 -> null
|
private var installedApkSha256Cache: InstalledApkSha256Cache? = null
|
||||||
else -> hours * 60L * 60L * 1000L
|
|
||||||
|
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(
|
data class AppReleaseInfo(
|
||||||
@@ -77,16 +85,63 @@ enum class RemoteVersionSource {
|
|||||||
Tag
|
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) {
|
suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo? = withContext(Dispatchers.IO) {
|
||||||
val webRelease = fetchReleaseFromLatestWebRedirect()
|
val budget = UpdateCheckBudget()
|
||||||
val apiRelease = fetchReleaseFromLatestEndpoint() ?: fetchLatestStableReleaseFromList()
|
val webRelease = fetchReleaseFromLatestWebRedirect(budget)
|
||||||
|
val apiRelease = fetchReleaseFromLatestEndpoint(budget) ?: fetchLatestStableReleaseFromList(budget)
|
||||||
val latestRelease = when {
|
val latestRelease = when {
|
||||||
webRelease == null -> apiRelease
|
webRelease == null -> apiRelease
|
||||||
apiRelease == null -> fetchReleaseByTag(webRelease.versionTag) ?: webRelease
|
apiRelease == null -> fetchReleaseByTag(webRelease.versionTag, budget) ?: webRelease
|
||||||
isNewerVersion(apiRelease.versionTag, webRelease.versionTag) -> fetchReleaseByTag(webRelease.versionTag) ?: webRelease
|
isNewerVersion(apiRelease.versionTag, webRelease.versionTag) -> fetchReleaseByTag(webRelease.versionTag, budget) ?: webRelease
|
||||||
else -> apiRelease
|
else -> apiRelease
|
||||||
}
|
}
|
||||||
val latestTag = fetchLatestTagFromList()
|
val latestTag = fetchLatestTagFromList(budget)
|
||||||
|
|
||||||
when {
|
when {
|
||||||
latestRelease == null -> latestTag
|
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? {
|
fun selectUpdateApkAsset(release: AppReleaseInfo): AppReleaseAsset? {
|
||||||
val apkAssets = release.assets
|
val apkAssets = release.assets
|
||||||
.filter { it.name.endsWith(".apk", ignoreCase = true) && it.downloadUrl.isNotBlank() }
|
.filter { it.name.endsWith(".apk", ignoreCase = true) && it.downloadUrl.isNotBlank() }
|
||||||
@@ -222,8 +304,45 @@ fun isNewerVersion(local: String, remote: String): Boolean {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fetchLatestStableReleaseFromList(): AppReleaseInfo? {
|
fun isSameVersion(left: String, right: String): Boolean {
|
||||||
val response = fetchGitHubApi(GITHUB_RELEASES_URL) ?: return null
|
val leftNumber = versionNumber(left) ?: return false
|
||||||
|
val rightNumber = versionNumber(right) ?: return false
|
||||||
|
return leftNumber == rightNumber
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun releaseApkSha256Set(release: AppReleaseInfo): Set<String> {
|
||||||
|
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 {
|
val releases = try {
|
||||||
JSONArray(response)
|
JSONArray(response)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -243,8 +362,8 @@ private fun fetchLatestStableReleaseFromList(): AppReleaseInfo? {
|
|||||||
return bestRelease
|
return bestRelease
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fetchLatestTagFromList(): AppReleaseInfo? {
|
private fun fetchLatestTagFromList(budget: UpdateCheckBudget): AppReleaseInfo? {
|
||||||
val response = fetchGitHubApi(GITHUB_TAGS_URL) ?: return null
|
val response = fetchGitHubApi(GITHUB_TAGS_URL, budget) ?: return null
|
||||||
val tags = try {
|
val tags = try {
|
||||||
JSONArray(response)
|
JSONArray(response)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -269,8 +388,8 @@ private fun fetchLatestTagFromList(): AppReleaseInfo? {
|
|||||||
return bestTag
|
return bestTag
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fetchReleaseFromLatestEndpoint(): AppReleaseInfo? {
|
private fun fetchReleaseFromLatestEndpoint(budget: UpdateCheckBudget): AppReleaseInfo? {
|
||||||
val response = fetchGitHubApi(GITHUB_LATEST_RELEASE_URL) ?: return null
|
val response = fetchGitHubApi(GITHUB_LATEST_RELEASE_URL, budget) ?: return null
|
||||||
val json = try {
|
val json = try {
|
||||||
JSONObject(response)
|
JSONObject(response)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -280,10 +399,10 @@ private fun fetchReleaseFromLatestEndpoint(): AppReleaseInfo? {
|
|||||||
return json.toAppReleaseInfo()
|
return json.toAppReleaseInfo()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fetchReleaseByTag(tag: String): AppReleaseInfo? {
|
private fun fetchReleaseByTag(tag: String, budget: UpdateCheckBudget): AppReleaseInfo? {
|
||||||
val normalizedTag = normalizeVersionTag(tag)
|
val normalizedTag = normalizeVersionTag(tag)
|
||||||
if (normalizedTag.isBlank()) return null
|
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
|
?: return null
|
||||||
val json = try {
|
val json = try {
|
||||||
JSONObject(response)
|
JSONObject(response)
|
||||||
@@ -294,17 +413,18 @@ private fun fetchReleaseByTag(tag: String): AppReleaseInfo? {
|
|||||||
return json.toAppReleaseInfo()
|
return json.toAppReleaseInfo()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fetchReleaseFromLatestWebRedirect(): AppReleaseInfo? {
|
private fun fetchReleaseFromLatestWebRedirect(budget: UpdateCheckBudget): AppReleaseInfo? {
|
||||||
var conn: HttpURLConnection? = null
|
var conn: HttpURLConnection? = null
|
||||||
return try {
|
return try {
|
||||||
|
val requestTimeout = budget.timeoutForHttpPhase() ?: return null
|
||||||
conn = URL(GITHUB_LATEST_RELEASE_WEB_URL).openConnection() as HttpURLConnection
|
conn = URL(GITHUB_LATEST_RELEASE_WEB_URL).openConnection() as HttpURLConnection
|
||||||
applyNoCacheHeaders(conn)
|
applyNoCacheHeaders(conn)
|
||||||
conn.instanceFollowRedirects = false
|
conn.instanceFollowRedirects = false
|
||||||
conn.requestMethod = "GET"
|
conn.requestMethod = "GET"
|
||||||
conn.setRequestProperty("Accept", "text/html,*/*")
|
conn.setRequestProperty("Accept", "text/html,*/*")
|
||||||
conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}")
|
conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}")
|
||||||
conn.connectTimeout = 8_000
|
conn.connectTimeout = requestTimeout
|
||||||
conn.readTimeout = 8_000
|
conn.readTimeout = requestTimeout
|
||||||
|
|
||||||
val responseCode = conn.responseCode
|
val responseCode = conn.responseCode
|
||||||
val location = conn.getHeaderField("Location")
|
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()
|
val now = System.currentTimeMillis()
|
||||||
if (now < githubApiCooldownUntilMs) return null
|
if (now < githubApiCooldownUntilMs || budget.expired) return null
|
||||||
return fetchHttpText(
|
return fetchHttpText(
|
||||||
url = url,
|
url = url,
|
||||||
sourceLabel = "GitHub API",
|
sourceLabel = "GitHub API",
|
||||||
accept = "application/vnd.github+json",
|
accept = "application/vnd.github+json",
|
||||||
|
budget = budget,
|
||||||
isGitHubApi = true
|
isGitHubApi = true
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -349,10 +470,12 @@ private fun fetchHttpText(
|
|||||||
url: String,
|
url: String,
|
||||||
sourceLabel: String,
|
sourceLabel: String,
|
||||||
accept: String,
|
accept: String,
|
||||||
|
budget: UpdateCheckBudget,
|
||||||
isGitHubApi: Boolean = false
|
isGitHubApi: Boolean = false
|
||||||
): String? {
|
): String? {
|
||||||
var conn: HttpURLConnection? = null
|
var conn: HttpURLConnection? = null
|
||||||
return try {
|
return try {
|
||||||
|
val requestTimeout = budget.timeoutForHttpPhase() ?: return null
|
||||||
conn = URL(url).openConnection() as HttpURLConnection
|
conn = URL(url).openConnection() as HttpURLConnection
|
||||||
applyNoCacheHeaders(conn)
|
applyNoCacheHeaders(conn)
|
||||||
conn.requestMethod = "GET"
|
conn.requestMethod = "GET"
|
||||||
@@ -361,8 +484,8 @@ private fun fetchHttpText(
|
|||||||
conn.setRequestProperty("X-GitHub-Api-Version", "2022-11-28")
|
conn.setRequestProperty("X-GitHub-Api-Version", "2022-11-28")
|
||||||
}
|
}
|
||||||
conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}")
|
conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}")
|
||||||
conn.connectTimeout = 8_000
|
conn.connectTimeout = requestTimeout
|
||||||
conn.readTimeout = 8_000
|
conn.readTimeout = requestTimeout
|
||||||
|
|
||||||
val responseCode = conn.responseCode
|
val responseCode = conn.responseCode
|
||||||
val stream = if (responseCode in 200..299) conn.inputStream else conn.errorStream
|
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"
|
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")
|
val digest = MessageDigest.getInstance("SHA-256")
|
||||||
inputStream().use { input ->
|
inputStream().use { input ->
|
||||||
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
|
||||||
while (true) {
|
while (true) {
|
||||||
|
budget?.requireTimeLeft("SHA-256 установленного APK")
|
||||||
val read = input.read(buffer)
|
val read = input.read(buffer)
|
||||||
if (read < 0) break
|
if (read < 0) break
|
||||||
digest.update(buffer, 0, read)
|
digest.update(buffer, 0, read)
|
||||||
@@ -488,3 +642,8 @@ private fun File.sha256Hex(): String {
|
|||||||
}
|
}
|
||||||
return digest.digest().joinToString("") { "%02x".format(it) }
|
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) }
|
||||||
|
}
|
||||||
@@ -678,10 +678,10 @@ fun MainScreen(
|
|||||||
val infoScrollPosition = rememberSaveable { mutableIntStateOf(0) }
|
val infoScrollPosition = rememberSaveable { mutableIntStateOf(0) }
|
||||||
var dragTargetIndex by remember { mutableIntStateOf(-1) }
|
var dragTargetIndex by remember { mutableIntStateOf(-1) }
|
||||||
var dragProgress by remember { mutableFloatStateOf(0f) }
|
var dragProgress by remember { mutableFloatStateOf(0f) }
|
||||||
val updateCheckIntervalHours by settingsStore.updateCheckIntervalHours.collectAsStateWithLifecycle(
|
val updateCheckIntervalMinutes by settingsStore.updateCheckIntervalMinutes.collectAsStateWithLifecycle(
|
||||||
initialValue = DEFAULT_UPDATE_CHECK_INTERVAL_HOURS
|
initialValue = DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES
|
||||||
)
|
)
|
||||||
var pendingRelease by remember { mutableStateOf<AppReleaseInfo?>(null) }
|
var pendingUpdateCandidate by remember { mutableStateOf<AppUpdateCandidate?>(null) }
|
||||||
var updateDownloadProgress by remember { mutableStateOf<AppUpdateDownloadProgress?>(null) }
|
var updateDownloadProgress by remember { mutableStateOf<AppUpdateDownloadProgress?>(null) }
|
||||||
var updateDownloadStatus by rememberSaveable { mutableStateOf("") }
|
var updateDownloadStatus by rememberSaveable { mutableStateOf("") }
|
||||||
var updateDownloadBusy by remember { mutableStateOf(false) }
|
var updateDownloadBusy by remember { mutableStateOf(false) }
|
||||||
@@ -699,7 +699,7 @@ fun MainScreen(
|
|||||||
if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) {
|
if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) {
|
||||||
runCatching {
|
runCatching {
|
||||||
installUpdateApk(context, apkFile)
|
installUpdateApk(context, apkFile)
|
||||||
pendingRelease = null
|
pendingUpdateCandidate = null
|
||||||
updateDownloadStatus = ""
|
updateDownloadStatus = ""
|
||||||
updateDownloadProgress = null
|
updateDownloadProgress = null
|
||||||
}.onFailure { error ->
|
}.onFailure { error ->
|
||||||
@@ -726,7 +726,7 @@ fun MainScreen(
|
|||||||
|
|
||||||
runCatching {
|
runCatching {
|
||||||
installUpdateApk(context, apkFile)
|
installUpdateApk(context, apkFile)
|
||||||
pendingRelease = null
|
pendingUpdateCandidate = null
|
||||||
updateDownloadStatus = ""
|
updateDownloadStatus = ""
|
||||||
updateDownloadProgress = null
|
updateDownloadProgress = null
|
||||||
}.onFailure { error ->
|
}.onFailure { error ->
|
||||||
@@ -837,20 +837,33 @@ fun MainScreen(
|
|||||||
if (selectedTab == 3) TunnelManager.clearUnreadErrors()
|
if (selectedTab == 3) TunnelManager.clearUnreadErrors()
|
||||||
}
|
}
|
||||||
|
|
||||||
LaunchedEffect(updateCheckIntervalHours) {
|
LaunchedEffect(updateCheckIntervalMinutes) {
|
||||||
if (updateCheckIntervalHours == UPDATE_CHECK_NEVER) return@LaunchedEffect
|
if (updateCheckIntervalMinutes == UPDATE_CHECK_NEVER) return@LaunchedEffect
|
||||||
|
|
||||||
val intervalMillis = updateIntervalHoursToMillis(updateCheckIntervalHours)
|
val intervalMillis = updateIntervalMinutesToMillis(updateCheckIntervalMinutes)
|
||||||
?: updateIntervalHoursToMillis(DEFAULT_UPDATE_CHECK_INTERVAL_HOURS)
|
?: updateIntervalMinutesToMillis(DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES)
|
||||||
?: 12L * 60L * 60L * 1000L
|
?: DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES * 60L * 1000L
|
||||||
|
|
||||||
suspend fun runUpdateCheck(reason: String) {
|
suspend fun runUpdateCheck(reason: String) {
|
||||||
val checkedAt = System.currentTimeMillis()
|
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(
|
settingsStore.saveUpdateState(
|
||||||
lastCheckAt = checkedAt,
|
lastCheckAt = checkedAt,
|
||||||
latestVersion = release?.versionTag ?: "",
|
latestVersion = release?.versionTag ?: "",
|
||||||
error = if (release == null) "Не удалось проверить" else ""
|
error = errorMessage
|
||||||
)
|
)
|
||||||
|
|
||||||
if (release == null) {
|
if (release == null) {
|
||||||
@@ -858,18 +871,19 @@ fun MainScreen(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
val hasUpdate = isNewerVersion(currentVersion, release.versionTag)
|
val candidate = updateCandidate
|
||||||
|
val hasUpdate = candidate != null
|
||||||
val postponeVer = settingsStore.updatePostponeVersion.first()
|
val postponeVer = settingsStore.updatePostponeVersion.first()
|
||||||
val postponeUntil = settingsStore.updatePostponeUntil.first()
|
val postponeUntil = settingsStore.updatePostponeUntil.first()
|
||||||
val isPostponed = postponeVer == release.versionTag && checkedAt < postponeUntil
|
val isPostponed = candidate != null && postponeVer == candidate.postponeKey && checkedAt < postponeUntil
|
||||||
Log.i(
|
Log.i(
|
||||||
"WDTT",
|
"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) {
|
if (candidate != null && !isPostponed) {
|
||||||
settingsStore.saveUpdateDialogShown(release.versionTag, checkedAt)
|
settingsStore.saveUpdateDialogShown(candidate.postponeKey, checkedAt)
|
||||||
pendingRelease = release
|
pendingUpdateCandidate = candidate
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1158,27 +1172,29 @@ fun MainScreen(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pendingRelease?.let { release ->
|
pendingUpdateCandidate?.let { candidate ->
|
||||||
|
val release = candidate.release
|
||||||
val apkAsset = remember(release) { selectUpdateApkAsset(release) }
|
val apkAsset = remember(release) { selectUpdateApkAsset(release) }
|
||||||
AppUpdateDialog(
|
AppUpdateDialog(
|
||||||
release = release,
|
release = release,
|
||||||
|
updateKind = candidate.kind,
|
||||||
apkAsset = apkAsset,
|
apkAsset = apkAsset,
|
||||||
isDownloading = updateDownloadBusy,
|
isDownloading = updateDownloadBusy,
|
||||||
downloadProgress = updateDownloadProgress,
|
downloadProgress = updateDownloadProgress,
|
||||||
downloadStatus = updateDownloadStatus,
|
downloadStatus = updateDownloadStatus,
|
||||||
onPostpone = {
|
onPostpone = {
|
||||||
pendingRelease = null
|
pendingUpdateCandidate = null
|
||||||
updateDownloadStatus = ""
|
updateDownloadStatus = ""
|
||||||
updateDownloadProgress = null
|
updateDownloadProgress = null
|
||||||
Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show()
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
settingsStore.saveUpdatePostpone(
|
settingsStore.saveUpdatePostpone(
|
||||||
version = release.versionTag,
|
version = candidate.postponeKey,
|
||||||
until = now + 24L * 60L * 60L * 1000L
|
until = now + 24L * 60L * 60L * 1000L
|
||||||
)
|
)
|
||||||
settingsStore.saveUpdateDialogAction(
|
settingsStore.saveUpdateDialogAction(
|
||||||
version = release.versionTag,
|
version = candidate.postponeKey,
|
||||||
action = UPDATE_DIALOG_ACTION_POSTPONED,
|
action = UPDATE_DIALOG_ACTION_POSTPONED,
|
||||||
actedAt = now
|
actedAt = now
|
||||||
)
|
)
|
||||||
@@ -1187,12 +1203,12 @@ fun MainScreen(
|
|||||||
onUpdate = {
|
onUpdate = {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
settingsStore.saveUpdateDialogAction(
|
settingsStore.saveUpdateDialogAction(
|
||||||
version = release.versionTag,
|
version = candidate.postponeKey,
|
||||||
action = UPDATE_DIALOG_ACTION_UPDATE,
|
action = UPDATE_DIALOG_ACTION_UPDATE,
|
||||||
actedAt = System.currentTimeMillis()
|
actedAt = System.currentTimeMillis()
|
||||||
)
|
)
|
||||||
if (apkAsset == null) {
|
if (apkAsset == null) {
|
||||||
pendingRelease = null
|
pendingUpdateCandidate = null
|
||||||
openReleaseUrl(context, release.releaseUrl)
|
openReleaseUrl(context, release.releaseUrl)
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
@@ -1223,7 +1239,7 @@ fun MainScreen(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
onOpenRelease = {
|
onOpenRelease = {
|
||||||
pendingRelease = null
|
pendingUpdateCandidate = null
|
||||||
updateDownloadStatus = ""
|
updateDownloadStatus = ""
|
||||||
updateDownloadProgress = null
|
updateDownloadProgress = null
|
||||||
openReleaseUrl(context, release.releaseUrl)
|
openReleaseUrl(context, release.releaseUrl)
|
||||||
|
|||||||
@@ -303,7 +303,7 @@ class SettingsStore(context: Context) {
|
|||||||
private val UPDATE_LAST_CHECK_AT = longPreferencesKey("update_last_check_at")
|
private val UPDATE_LAST_CHECK_AT = longPreferencesKey("update_last_check_at")
|
||||||
private val UPDATE_LATEST_VERSION = stringPreferencesKey("update_latest_version")
|
private val UPDATE_LATEST_VERSION = stringPreferencesKey("update_latest_version")
|
||||||
private val UPDATE_LAST_ERROR = stringPreferencesKey("update_last_error")
|
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_UNTIL = longPreferencesKey("update_postpone_until")
|
||||||
private val UPDATE_POSTPONE_VERSION = stringPreferencesKey("update_postpone_version")
|
private val UPDATE_POSTPONE_VERSION = stringPreferencesKey("update_postpone_version")
|
||||||
private val UPDATE_DIALOG_LAST_SHOWN_VERSION = stringPreferencesKey("update_dialog_last_shown_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<Long> = dataStore.data.map { it[UPDATE_LAST_CHECK_AT] ?: 0L }
|
val updateLastCheckAt: Flow<Long> = dataStore.data.map { it[UPDATE_LAST_CHECK_AT] ?: 0L }
|
||||||
val updateLatestVersion: Flow<String> = dataStore.data.map { it[UPDATE_LATEST_VERSION] ?: "" }
|
val updateLatestVersion: Flow<String> = dataStore.data.map { it[UPDATE_LATEST_VERSION] ?: "" }
|
||||||
val updateLastError: Flow<String> = dataStore.data.map { it[UPDATE_LAST_ERROR] ?: "" }
|
val updateLastError: Flow<String> = dataStore.data.map { it[UPDATE_LAST_ERROR] ?: "" }
|
||||||
val updateCheckIntervalHours: Flow<Int> = dataStore.data.map { it[UPDATE_CHECK_INTERVAL_HOURS] ?: 24 }
|
val updateCheckIntervalMinutes: Flow<Int> = dataStore.data.map {
|
||||||
|
normalizeUpdateCheckIntervalMinutes(it[UPDATE_CHECK_INTERVAL_MINUTES] ?: DEFAULT_UPDATE_CHECK_INTERVAL_MINUTES)
|
||||||
|
}
|
||||||
val updatePostponeUntil: Flow<Long> = dataStore.data.map { it[UPDATE_POSTPONE_UNTIL] ?: 0L }
|
val updatePostponeUntil: Flow<Long> = dataStore.data.map { it[UPDATE_POSTPONE_UNTIL] ?: 0L }
|
||||||
val updatePostponeVersion: Flow<String> = dataStore.data.map { it[UPDATE_POSTPONE_VERSION] ?: "" }
|
val updatePostponeVersion: Flow<String> = dataStore.data.map { it[UPDATE_POSTPONE_VERSION] ?: "" }
|
||||||
val updateDialogLastShownVersion: Flow<String> = dataStore.data.map { it[UPDATE_DIALOG_LAST_SHOWN_VERSION] ?: "" }
|
val updateDialogLastShownVersion: Flow<String> = 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 ->
|
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("themePalette", prefs[THEME_PALETTE] ?: "indigo")
|
||||||
put("showSystemApps", prefs[SHOW_SYSTEM_APPS] ?: false)
|
put("showSystemApps", prefs[SHOW_SYSTEM_APPS] ?: false)
|
||||||
put("loggingEnabled", prefs[LOGGING_ENABLED] ?: true)
|
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("profiles", profiles)
|
||||||
put("outbound", exportSharedPreferences("wdtt_outbound_forms"))
|
put("outbound", exportSharedPreferences("wdtt_outbound_forms"))
|
||||||
}.toString()
|
}.toString()
|
||||||
@@ -900,7 +907,14 @@ class SettingsStore(context: Context) {
|
|||||||
prefs[THEME_PALETTE] = root.optString("themePalette", "indigo")
|
prefs[THEME_PALETTE] = root.optString("themePalette", "indigo")
|
||||||
prefs[SHOW_SYSTEM_APPS] = root.optBoolean("showSystemApps")
|
prefs[SHOW_SYSTEM_APPS] = root.optBoolean("showSystemApps")
|
||||||
prefs[LOGGING_ENABLED] = root.optBoolean("loggingEnabled", true)
|
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"
|
prefs[INTERFACE_ROLE] = "admin"
|
||||||
}
|
}
|
||||||
importSharedPreferences("wdtt_outbound_forms", root.optJSONObject("outbound") ?: JSONObject())
|
importSharedPreferences("wdtt_outbound_forms", root.optJSONObject("outbound") ?: JSONObject())
|
||||||
@@ -1311,6 +1325,13 @@ fun sanitizeVpnProfileNameInput(name: String): String {
|
|||||||
fun normalizeVpnProfileName(name: String): String =
|
fun normalizeVpnProfileName(name: String): String =
|
||||||
sanitizeVpnProfileNameInput(name).trimEnd()
|
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>): String {
|
fun vpnProfileDisplayName(profile: Int, names: List<String>): String {
|
||||||
val clean = normalizeVpnProfileName(names.getOrNull(profile).orEmpty())
|
val clean = normalizeVpnProfileName(names.getOrNull(profile).orEmpty())
|
||||||
return clean.ifBlank { vpnProfileDefaultName(profile) }
|
return clean.ifBlank { vpnProfileDefaultName(profile) }
|
||||||
|
|||||||
@@ -34,11 +34,13 @@ import androidx.compose.ui.window.DialogProperties
|
|||||||
import com.wdtt.plus.AppReleaseInfo
|
import com.wdtt.plus.AppReleaseInfo
|
||||||
import com.wdtt.plus.AppReleaseAsset
|
import com.wdtt.plus.AppReleaseAsset
|
||||||
import com.wdtt.plus.AppUpdateDownloadProgress
|
import com.wdtt.plus.AppUpdateDownloadProgress
|
||||||
|
import com.wdtt.plus.AppUpdateKind
|
||||||
import com.wdtt.plus.RemoteVersionSource
|
import com.wdtt.plus.RemoteVersionSource
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun AppUpdateDialog(
|
fun AppUpdateDialog(
|
||||||
release: AppReleaseInfo,
|
release: AppReleaseInfo,
|
||||||
|
updateKind: AppUpdateKind = AppUpdateKind.NewVersion,
|
||||||
apkAsset: AppReleaseAsset?,
|
apkAsset: AppReleaseAsset?,
|
||||||
isDownloading: Boolean,
|
isDownloading: Boolean,
|
||||||
downloadProgress: AppUpdateDownloadProgress?,
|
downloadProgress: AppUpdateDownloadProgress?,
|
||||||
@@ -48,9 +50,18 @@ fun AppUpdateDialog(
|
|||||||
onOpenRelease: () -> Unit
|
onOpenRelease: () -> Unit
|
||||||
) {
|
) {
|
||||||
val isTagOnly = release.source == RemoteVersionSource.Tag
|
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 canDownloadInApp = !isTagOnly && apkAsset != null
|
||||||
val description = when {
|
val description = when {
|
||||||
|
isSameVersionFix && canDownloadInApp ->
|
||||||
|
"Версия ${release.versionTag} не изменилась, но APK в релизе обновлён. Это исправление текущей версии; WDTT Plus скачает подходящий файл и откроет установку Android."
|
||||||
|
isSameVersionFix ->
|
||||||
|
"Версия ${release.versionTag} не изменилась, но APK в релизе обновлён. Не удалось подобрать файл для этого устройства, можно открыть страницу релиза."
|
||||||
isTagOnly ->
|
isTagOnly ->
|
||||||
"На GitHub обнаружен более новый tag ${release.versionTag}. Похоже, опубликованный release ещё не догнал его."
|
"На GitHub обнаружен более новый tag ${release.versionTag}. Похоже, опубликованный release ещё не догнал его."
|
||||||
canDownloadInApp ->
|
canDownloadInApp ->
|
||||||
|
|||||||
@@ -111,6 +111,7 @@ import com.wdtt.plus.UPDATE_DIALOG_ACTION_POSTPONED
|
|||||||
import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE
|
import com.wdtt.plus.UPDATE_DIALOG_ACTION_UPDATE
|
||||||
import com.wdtt.plus.WDTTColors
|
import com.wdtt.plus.WDTTColors
|
||||||
import com.wdtt.plus.AppReleaseInfo
|
import com.wdtt.plus.AppReleaseInfo
|
||||||
|
import com.wdtt.plus.AppUpdateCandidate
|
||||||
import com.wdtt.plus.AppUpdateDownloadProgress
|
import com.wdtt.plus.AppUpdateDownloadProgress
|
||||||
import com.wdtt.plus.canRequestApkInstall
|
import com.wdtt.plus.canRequestApkInstall
|
||||||
import com.wdtt.plus.downloadUpdateApk
|
import com.wdtt.plus.downloadUpdateApk
|
||||||
@@ -118,6 +119,7 @@ import com.wdtt.plus.fetchLatestReleaseInfo
|
|||||||
import com.wdtt.plus.installUpdateApk
|
import com.wdtt.plus.installUpdateApk
|
||||||
import com.wdtt.plus.isNewerVersion
|
import com.wdtt.plus.isNewerVersion
|
||||||
import com.wdtt.plus.label
|
import com.wdtt.plus.label
|
||||||
|
import com.wdtt.plus.resolveAppUpdateCandidate
|
||||||
import com.wdtt.plus.selectUpdateApkAsset
|
import com.wdtt.plus.selectUpdateApkAsset
|
||||||
import com.wdtt.plus.deviceCheckActionIntent
|
import com.wdtt.plus.deviceCheckActionIntent
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
@@ -231,7 +233,7 @@ fun InfoTab(
|
|||||||
val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" }
|
val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" }
|
||||||
val releaseDate = remember { BuildConfig.MOD_RELEASE_DATE }
|
val releaseDate = remember { BuildConfig.MOD_RELEASE_DATE }
|
||||||
var isCheckingUpdates by remember { mutableStateOf(false) }
|
var isCheckingUpdates by remember { mutableStateOf(false) }
|
||||||
var pendingManualRelease by remember { mutableStateOf<AppReleaseInfo?>(null) }
|
var pendingManualUpdateCandidate by remember { mutableStateOf<AppUpdateCandidate?>(null) }
|
||||||
var updateDownloadProgress by remember { mutableStateOf<AppUpdateDownloadProgress?>(null) }
|
var updateDownloadProgress by remember { mutableStateOf<AppUpdateDownloadProgress?>(null) }
|
||||||
var updateDownloadStatus by rememberSaveable { mutableStateOf("") }
|
var updateDownloadStatus by rememberSaveable { mutableStateOf("") }
|
||||||
var updateDownloadBusy by remember { mutableStateOf(false) }
|
var updateDownloadBusy by remember { mutableStateOf(false) }
|
||||||
@@ -261,7 +263,7 @@ fun InfoTab(
|
|||||||
if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) {
|
if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) {
|
||||||
runCatching {
|
runCatching {
|
||||||
installUpdateApk(context, apkFile)
|
installUpdateApk(context, apkFile)
|
||||||
pendingManualRelease = null
|
pendingManualUpdateCandidate = null
|
||||||
updateDownloadStatus = ""
|
updateDownloadStatus = ""
|
||||||
updateDownloadProgress = null
|
updateDownloadProgress = null
|
||||||
}.onFailure { error ->
|
}.onFailure { error ->
|
||||||
@@ -289,7 +291,7 @@ fun InfoTab(
|
|||||||
|
|
||||||
runCatching {
|
runCatching {
|
||||||
installUpdateApk(context, apkFile)
|
installUpdateApk(context, apkFile)
|
||||||
pendingManualRelease = null
|
pendingManualUpdateCandidate = null
|
||||||
updateDownloadStatus = ""
|
updateDownloadStatus = ""
|
||||||
updateDownloadProgress = null
|
updateDownloadProgress = null
|
||||||
}.onFailure { error ->
|
}.onFailure { error ->
|
||||||
@@ -470,34 +472,51 @@ fun InfoTab(
|
|||||||
isCheckingUpdates = true
|
isCheckingUpdates = true
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val checkedAt = System.currentTimeMillis()
|
val checkedAt = System.currentTimeMillis()
|
||||||
val release = fetchLatestReleaseInfo(currentVersion)
|
var release: AppReleaseInfo? = null
|
||||||
val latest = release?.versionTag
|
var updateCandidate: AppUpdateCandidate? = null
|
||||||
settingsStore.saveUpdateState(
|
var errorMessage = ""
|
||||||
lastCheckAt = checkedAt,
|
try {
|
||||||
latestVersion = latest ?: "",
|
runCatching {
|
||||||
error = if (release == null) "Не удалось проверить" else ""
|
release = fetchLatestReleaseInfo(currentVersion)
|
||||||
)
|
if (release == null) {
|
||||||
isCheckingUpdates = false
|
errorMessage = "Не удалось проверить"
|
||||||
|
return@runCatching
|
||||||
if (release == null) {
|
}
|
||||||
val message = if (updateLatestVersion.isNotBlank()) {
|
updateCandidate = resolveAppUpdateCandidate(context, currentVersion, release)
|
||||||
"Не удалось проверить. Последняя известная версия: $updateLatestVersion"
|
}.onFailure { error ->
|
||||||
} else {
|
errorMessage = error.message ?: "Не удалось проверить обновления"
|
||||||
"Не удалось проверить обновления"
|
|
||||||
}
|
}
|
||||||
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
|
|
||||||
return@launch
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isNewerVersion(currentVersion, release.versionTag)) {
|
settingsStore.saveUpdateState(
|
||||||
settingsStore.saveUpdateDialogShown(release.versionTag, checkedAt)
|
lastCheckAt = checkedAt,
|
||||||
pendingManualRelease = release
|
latestVersion = release?.versionTag ?: "",
|
||||||
} else {
|
error = errorMessage
|
||||||
Toast.makeText(
|
)
|
||||||
context,
|
|
||||||
"У вас уже последняя версия: ${release.versionTag}",
|
val currentRelease = release
|
||||||
Toast.LENGTH_SHORT
|
if (currentRelease == null) {
|
||||||
).show()
|
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) }
|
val apkAsset = remember(release) { selectUpdateApkAsset(release) }
|
||||||
AppUpdateDialog(
|
AppUpdateDialog(
|
||||||
release = release,
|
release = release,
|
||||||
|
updateKind = candidate.kind,
|
||||||
apkAsset = apkAsset,
|
apkAsset = apkAsset,
|
||||||
isDownloading = updateDownloadBusy,
|
isDownloading = updateDownloadBusy,
|
||||||
downloadProgress = updateDownloadProgress,
|
downloadProgress = updateDownloadProgress,
|
||||||
downloadStatus = updateDownloadStatus,
|
downloadStatus = updateDownloadStatus,
|
||||||
onPostpone = {
|
onPostpone = {
|
||||||
pendingManualRelease = null
|
pendingManualUpdateCandidate = null
|
||||||
updateDownloadStatus = ""
|
updateDownloadStatus = ""
|
||||||
updateDownloadProgress = null
|
updateDownloadProgress = null
|
||||||
Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show()
|
Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show()
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val now = System.currentTimeMillis()
|
val now = System.currentTimeMillis()
|
||||||
settingsStore.saveUpdatePostpone(
|
settingsStore.saveUpdatePostpone(
|
||||||
version = release.versionTag,
|
version = candidate.postponeKey,
|
||||||
until = now + 24L * 60L * 60L * 1000L
|
until = now + 24L * 60L * 60L * 1000L
|
||||||
)
|
)
|
||||||
settingsStore.saveUpdateDialogAction(
|
settingsStore.saveUpdateDialogAction(
|
||||||
version = release.versionTag,
|
version = candidate.postponeKey,
|
||||||
action = UPDATE_DIALOG_ACTION_POSTPONED,
|
action = UPDATE_DIALOG_ACTION_POSTPONED,
|
||||||
actedAt = now
|
actedAt = now
|
||||||
)
|
)
|
||||||
@@ -541,12 +562,12 @@ fun InfoTab(
|
|||||||
onUpdate = {
|
onUpdate = {
|
||||||
scope.launch {
|
scope.launch {
|
||||||
settingsStore.saveUpdateDialogAction(
|
settingsStore.saveUpdateDialogAction(
|
||||||
version = release.versionTag,
|
version = candidate.postponeKey,
|
||||||
action = UPDATE_DIALOG_ACTION_UPDATE,
|
action = UPDATE_DIALOG_ACTION_UPDATE,
|
||||||
actedAt = System.currentTimeMillis()
|
actedAt = System.currentTimeMillis()
|
||||||
)
|
)
|
||||||
if (apkAsset == null) {
|
if (apkAsset == null) {
|
||||||
pendingManualRelease = null
|
pendingManualUpdateCandidate = null
|
||||||
openUrlInBrowser(context, release.releaseUrl)
|
openUrlInBrowser(context, release.releaseUrl)
|
||||||
return@launch
|
return@launch
|
||||||
}
|
}
|
||||||
@@ -577,7 +598,7 @@ fun InfoTab(
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
onOpenRelease = {
|
onOpenRelease = {
|
||||||
pendingManualRelease = null
|
pendingManualUpdateCandidate = null
|
||||||
updateDownloadStatus = ""
|
updateDownloadStatus = ""
|
||||||
updateDownloadProgress = null
|
updateDownloadProgress = null
|
||||||
openUrlInBrowser(context, release.releaseUrl)
|
openUrlInBrowser(context, release.releaseUrl)
|
||||||
|
|||||||
@@ -662,9 +662,8 @@ fun ServerClientsSection(
|
|||||||
ClientStatusBanner(status = status, busy = busy)
|
ClientStatusBanner(status = status, busy = busy)
|
||||||
}
|
}
|
||||||
|
|
||||||
AnimatedVisibility(state != null) {
|
state?.let { current ->
|
||||||
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
|
||||||
val current = state ?: return@AnimatedVisibility
|
|
||||||
val activeFilterCount = activeClientFilterCount(statusFilter, bindingFilter, expiryFilter, vkHashFilter)
|
val activeFilterCount = activeClientFilterCount(statusFilter, bindingFilter, expiryFilter, vkHashFilter)
|
||||||
ClientPanel {
|
ClientPanel {
|
||||||
Text(
|
Text(
|
||||||
|
|||||||
@@ -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"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user