From efabc7e61ac4798c8379cf8020ca4ad49b388b8a Mon Sep 17 00:00:00 2001 From: Ivan4537 Date: Fri, 3 Jul 2026 17:16:32 +0300 Subject: [PATCH] =?UTF-8?q?=D0=92=D1=81=D1=82=D1=80=D0=BE=D0=B5=D0=BD?= =?UTF-8?q?=D0=BD=D0=BE=D0=B5=20=D0=BE=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20APK?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 1 + README.md | 2 +- app/src/main/AndroidManifest.xml | 1 + app/src/main/java/com/wdtt/plus/AppUpdate.kt | 221 +++++++++++++++++- .../main/java/com/wdtt/plus/MainActivity.kt | 91 +++++++- .../java/com/wdtt/plus/ui/AppUpdateDialog.kt | 85 ++++++- app/src/main/java/com/wdtt/plus/ui/InfoTab.kt | 103 +++++++- app/src/main/res/xml/file_paths.xml | 3 + 8 files changed, 490 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e0e042..f4cb7ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,7 @@ ### Интерфейс - В «Инфо → О проекте» добавлена ссылка на историю изменений. +- Обновление приложения можно скачать внутри WDTT Plus: приложение выбирает подходящий APK, проверяет скачанный файл и открывает системную установку Android. - Доработана навигация в диалогах и блоке «Клиенты»: закрытие возвращает пользователя к предыдущему меню, а список клиентов, поиск и позиция во вкладке «Деплой» сохраняются при переключении между вкладками. ## v1 — 01.07.2026 diff --git a/README.md b/README.md index 837c331..6c769ce 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,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 в этом репозитории, показывает диалог обновления и периодически повторяет проверку в фоне. +- **Автообновления:** приложение проверяет релизы WDTT Plus в этом репозитории, скачивает подходящий APK внутри приложения и передаёт его системному установщику Android. ## Как это работает diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 9b0c2d2..6fc072e 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -11,6 +11,7 @@ + = emptyList() ) +data class AppReleaseAsset( + val name: String, + val downloadUrl: String, + val sizeBytes: Long, + val digest: String = "" +) { + val sha256: String? + get() = digest + .removePrefix("sha256:") + .trim() + .lowercase(Locale.US) + .takeIf { it.matches(Regex("^[0-9a-f]{64}$")) } +} + +data class AppUpdateDownloadProgress( + val fileName: String, + val downloadedBytes: Long, + val totalBytes: Long +) { + val fraction: Float? + get() = totalBytes.takeIf { it > 0L }?.let { (downloadedBytes.toFloat() / it).coerceIn(0f, 1f) } + + val percent: Int? + get() = fraction?.let { (it * 100).toInt().coerceIn(0, 100) } +} + enum class RemoteVersionSource { Release, Tag } suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo? = withContext(Dispatchers.IO) { - val latestRelease = fetchReleaseFromLatestWebRedirect() - ?: fetchReleaseFromLatestEndpoint() - ?: fetchLatestStableReleaseFromList() + val webRelease = fetchReleaseFromLatestWebRedirect() + val apiRelease = fetchReleaseFromLatestEndpoint() ?: fetchLatestStableReleaseFromList() + val latestRelease = when { + webRelease == null -> apiRelease + apiRelease == null -> fetchReleaseByTag(webRelease.versionTag) ?: webRelease + isNewerVersion(apiRelease.versionTag, webRelease.versionTag) -> fetchReleaseByTag(webRelease.versionTag) ?: webRelease + else -> apiRelease + } val latestTag = fetchLatestTagFromList() when { @@ -56,6 +96,117 @@ suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo } } +fun selectUpdateApkAsset(release: AppReleaseInfo): AppReleaseAsset? { + val apkAssets = release.assets + .filter { it.name.endsWith(".apk", ignoreCase = true) && it.downloadUrl.isNotBlank() } + if (apkAssets.isEmpty()) return null + + Build.SUPPORTED_ABIS.orEmpty().forEach { abi -> + apkAssets.firstOrNull { it.name.contains(abi, ignoreCase = true) }?.let { return it } + } + + return apkAssets.firstOrNull { it.name.contains("universal", ignoreCase = true) } + ?: apkAssets.firstOrNull() +} + +suspend fun downloadUpdateApk( + context: Context, + asset: AppReleaseAsset, + onProgress: suspend (AppUpdateDownloadProgress) -> Unit = {} +): File = withContext(Dispatchers.IO) { + val appContext = context.applicationContext + val updatesDir = File(appContext.cacheDir, "updates").apply { mkdirs() } + updatesDir.listFiles()?.forEach { file -> + if (file.isFile && file.extension.equals("apk", ignoreCase = true)) file.delete() + } + + val outputFile = File(updatesDir, asset.name.safeUpdateAssetName()) + var conn: HttpURLConnection? = null + + suspend fun emit(downloaded: Long, total: Long) { + withContext(Dispatchers.Main) { + onProgress(AppUpdateDownloadProgress(asset.name, downloaded, total)) + } + } + + try { + conn = URL(asset.downloadUrl).openConnection() as HttpURLConnection + applyNoCacheHeaders(conn) + conn.instanceFollowRedirects = true + conn.requestMethod = "GET" + conn.setRequestProperty("Accept", "application/vnd.android.package-archive,application/octet-stream,*/*") + conn.setRequestProperty("User-Agent", "WDTTAndroid/${BuildConfig.VERSION_NAME}") + conn.connectTimeout = 15_000 + conn.readTimeout = 30_000 + + val responseCode = conn.responseCode + if (responseCode !in 200..299) { + throw IOException("GitHub вернул HTTP $responseCode при скачивании APK") + } + + val total = asset.sizeBytes.takeIf { it > 0L } + ?: conn.contentLengthLong.takeIf { it > 0L } + ?: 0L + var downloaded = 0L + var lastEmitAt = 0L + emit(0L, total) + + conn.inputStream.use { input -> + outputFile.outputStream().use { output -> + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + while (true) { + val read = input.read(buffer) + if (read < 0) break + output.write(buffer, 0, read) + downloaded += read + val now = System.currentTimeMillis() + if (now - lastEmitAt >= 250L || downloaded == total) { + lastEmitAt = now + emit(downloaded, total) + } + } + } + } + + if (asset.sizeBytes > 0L && outputFile.length() != asset.sizeBytes) { + outputFile.delete() + throw IOException("Размер APK не совпал с GitHub asset") + } + + asset.sha256?.let { expected -> + val actual = outputFile.sha256Hex() + if (!actual.equals(expected, ignoreCase = true)) { + outputFile.delete() + throw SecurityException("SHA-256 скачанного APK не совпал с GitHub digest") + } + } + + emit(outputFile.length(), total.takeIf { it > 0L } ?: outputFile.length()) + outputFile + } catch (e: Exception) { + outputFile.delete() + throw e + } finally { + conn?.disconnect() + } +} + +fun canRequestApkInstall(context: Context): Boolean { + return Build.VERSION.SDK_INT < Build.VERSION_CODES.O || + context.packageManager.canRequestPackageInstalls() +} + +fun installUpdateApk(context: Context, apkFile: File) { + val appContext = context.applicationContext + val uri = FileProvider.getUriForFile(appContext, "${appContext.packageName}.files", apkFile) + val intent = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + } + appContext.startActivity(intent) +} + fun isNewerVersion(local: String, remote: String): Boolean { val localParts = versionParts(local) val remoteParts = versionParts(remote) @@ -129,6 +280,20 @@ private fun fetchReleaseFromLatestEndpoint(): AppReleaseInfo? { return json.toAppReleaseInfo() } +private fun fetchReleaseByTag(tag: String): AppReleaseInfo? { + val normalizedTag = normalizeVersionTag(tag) + if (normalizedTag.isBlank()) return null + val response = fetchGitHubApi("https://api.github.com/repos/Ivan4537/WDTT-Plus/releases/tags/$normalizedTag") + ?: return null + val json = try { + JSONObject(response) + } catch (e: Exception) { + Log.w(UPDATE_LOG_TAG, "[WARN] Update check: failed to parse release by tag", e) + return null + } + return json.toAppReleaseInfo() +} + private fun fetchReleaseFromLatestWebRedirect(): AppReleaseInfo? { var conn: HttpURLConnection? = null return try { @@ -249,7 +414,32 @@ private fun JSONObject.toAppReleaseInfo(): AppReleaseInfo? { val versionTag = normalizeVersionTag(optString("tag_name")) val releaseUrl = optString("html_url").trim() if (versionTag.isBlank() || releaseUrl.isBlank()) return null - return AppReleaseInfo(versionTag, releaseUrl, RemoteVersionSource.Release) + return AppReleaseInfo( + versionTag = versionTag, + releaseUrl = releaseUrl, + source = RemoteVersionSource.Release, + assets = optJSONArray("assets").toReleaseAssets() + ) +} + +private fun JSONArray?.toReleaseAssets(): List { + if (this == null) return emptyList() + return buildList { + for (i in 0 until length()) { + val json = optJSONObject(i) ?: continue + val name = json.optString("name").trim() + val downloadUrl = json.optString("browser_download_url").trim() + if (name.isBlank() || downloadUrl.isBlank()) continue + add( + AppReleaseAsset( + name = name, + downloadUrl = downloadUrl, + sizeBytes = json.optLong("size", 0L), + digest = json.optString("digest").trim() + ) + ) + } + } } private fun versionParts(version: String): List { @@ -277,3 +467,24 @@ private fun extractTagFromReleaseUrl(releaseUrl: String): String? { .takeIf { it.isNotBlank() } ?.let(::normalizeVersionTag) } + +private fun String.safeUpdateAssetName(): String { + val cleaned = replace(Regex("[^A-Za-z0-9._-]+"), "-") + .trim('-', '.', '_') + .takeIf { it.isNotBlank() } + ?: "WDTT-Plus-update.apk" + return if (cleaned.endsWith(".apk", ignoreCase = true)) cleaned else "$cleaned.apk" +} + +private fun File.sha256Hex(): String { + val digest = MessageDigest.getInstance("SHA-256") + inputStream().use { input -> + val buffer = ByteArray(DEFAULT_BUFFER_SIZE) + while (true) { + val read = input.read(buffer) + if (read < 0) break + digest.update(buffer, 0, read) + } + } + return digest.digest().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 8f868fc..60eb0e4 100644 --- a/app/src/main/java/com/wdtt/plus/MainActivity.kt +++ b/app/src/main/java/com/wdtt/plus/MainActivity.kt @@ -86,6 +86,7 @@ import com.wdtt.plus.ui.TransferCenterDialog import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.flow.first +import java.io.File import kotlin.math.PI import kotlin.math.abs import kotlin.math.cos @@ -666,10 +667,56 @@ fun MainScreen( initialValue = DEFAULT_UPDATE_CHECK_INTERVAL_HOURS ) var pendingRelease by remember { mutableStateOf(null) } + var updateDownloadProgress by remember { mutableStateOf(null) } + var updateDownloadStatus by rememberSaveable { mutableStateOf("") } + var updateDownloadBusy by remember { mutableStateOf(false) } + var pendingUpdateApkPath by rememberSaveable { mutableStateOf(null) } val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" } val safeBottomInset = with(density) { WindowInsets.safeDrawing.getBottom(density).toDp() } val navOverlayReserve = safeBottomInset + 96.dp var showTransferCenter by rememberSaveable { mutableStateOf(false) } + val updateInstallPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { + val apkFile = pendingUpdateApkPath?.let(::File) + if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) { + runCatching { + installUpdateApk(context, apkFile) + pendingRelease = null + updateDownloadStatus = "" + updateDownloadProgress = null + }.onFailure { error -> + updateDownloadStatus = error.message ?: "Не удалось открыть установку APK." + Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() + } + } else if (apkFile != null) { + updateDownloadStatus = "Разрешение на установку из WDTT Plus не выдано." + Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() + } + } + + fun requestDownloadedUpdateInstall(apkFile: File) { + pendingUpdateApkPath = apkFile.absolutePath + if (!canRequestApkInstall(context)) { + updateDownloadStatus = "Разрешите установку из WDTT Plus в настройках Android." + val intent = Intent( + Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:${context.packageName}") + ) + updateInstallPermissionLauncher.launch(intent) + return + } + + runCatching { + installUpdateApk(context, apkFile) + pendingRelease = null + updateDownloadStatus = "" + updateDownloadProgress = null + }.onFailure { error -> + updateDownloadStatus = error.message ?: "Не удалось открыть установку APK." + Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() + } + } if (interfaceRole.isBlank()) { RoleSelectionScreen( @@ -973,10 +1020,17 @@ fun MainScreen( } pendingRelease?.let { release -> + val apkAsset = remember(release) { selectUpdateApkAsset(release) } AppUpdateDialog( release = release, + apkAsset = apkAsset, + isDownloading = updateDownloadBusy, + downloadProgress = updateDownloadProgress, + downloadStatus = updateDownloadStatus, onPostpone = { pendingRelease = null + updateDownloadStatus = "" + updateDownloadProgress = null Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show() scope.launch { val now = System.currentTimeMillis() @@ -992,15 +1046,48 @@ fun MainScreen( } }, onUpdate = { - pendingRelease = null scope.launch { settingsStore.saveUpdateDialogAction( version = release.versionTag, action = UPDATE_DIALOG_ACTION_UPDATE, actedAt = System.currentTimeMillis() ) - openReleaseUrl(context, release.releaseUrl) + if (apkAsset == null) { + pendingRelease = null + openReleaseUrl(context, release.releaseUrl) + return@launch + } + + updateDownloadBusy = true + updateDownloadStatus = "Подготовка скачивания..." + updateDownloadProgress = null + runCatching { + val apkFile = downloadUpdateApk(context, apkAsset) { progress -> + updateDownloadProgress = progress + updateDownloadStatus = if (progress.percent != null) { + "Скачивание APK" + } else { + "Скачивание APK..." + } + } + updateDownloadStatus = if (apkAsset.sha256 != null) { + "APK скачан и проверен. Открываю установку..." + } else { + "APK скачан. Открываю установку..." + } + requestDownloadedUpdateInstall(apkFile) + }.onFailure { error -> + updateDownloadStatus = error.message ?: "Не удалось скачать обновление." + Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() + } + updateDownloadBusy = false } + }, + onOpenRelease = { + pendingRelease = null + updateDownloadStatus = "" + updateDownloadProgress = null + openReleaseUrl(context, release.releaseUrl) } ) } 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 924c644..9576460 100644 --- a/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt +++ b/app/src/main/java/com/wdtt/plus/ui/AppUpdateDialog.kt @@ -16,33 +16,52 @@ import androidx.compose.material.icons.filled.Update import androidx.compose.material3.Button import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon +import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Surface import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties import com.wdtt.plus.AppReleaseInfo +import com.wdtt.plus.AppReleaseAsset +import com.wdtt.plus.AppUpdateDownloadProgress import com.wdtt.plus.RemoteVersionSource @Composable fun AppUpdateDialog( release: AppReleaseInfo, + apkAsset: AppReleaseAsset?, + isDownloading: Boolean, + downloadProgress: AppUpdateDownloadProgress?, + downloadStatus: String, onPostpone: () -> Unit, - onUpdate: () -> Unit + onUpdate: () -> Unit, + onOpenRelease: () -> Unit ) { val isTagOnly = release.source == RemoteVersionSource.Tag val title = if (isTagOnly) "Найден новый tag" else "Доступно обновление" - val description = if (isTagOnly) { - "На GitHub обнаружен более новый tag ${release.versionTag}. Похоже, опубликованный release ещё не догнал его." - } else { - "Вышла новая версия приложения ${release.versionTag}. Можно открыть страницу релиза и обновиться вручную." + val canDownloadInApp = !isTagOnly && apkAsset != null + val description = when { + isTagOnly -> + "На GitHub обнаружен более новый tag ${release.versionTag}. Похоже, опубликованный release ещё не догнал его." + canDownloadInApp -> + "Вышла новая версия приложения ${release.versionTag}. WDTT Plus скачает подходящий APK и откроет системное окно установки Android." + else -> + "Вышла новая версия приложения ${release.versionTag}. Не удалось подобрать APK для этого устройства, можно открыть страницу релиза." + } + val primaryLabel = when { + isDownloading -> "Скачивается..." + canDownloadInApp -> "Скачать" + else -> "Открыть" } Dialog( @@ -97,6 +116,48 @@ fun AppUpdateDialog( lineHeight = 20.sp ) + if (canDownloadInApp) { + Text( + text = "Файл: ${apkAsset.name}", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 18.sp + ) + } + + if (isDownloading || downloadProgress != null || downloadStatus.isNotBlank()) { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + if (isDownloading) { + val fraction = downloadProgress?.fraction + if (fraction != null) { + LinearProgressIndicator( + progress = { fraction }, + modifier = Modifier + .fillMaxWidth() + .height(8.dp) + .clip(RoundedCornerShape(4.dp)) + ) + } else { + LinearProgressIndicator( + modifier = Modifier + .fillMaxWidth() + .height(8.dp) + .clip(RoundedCornerShape(4.dp)) + ) + } + } + val progressText = downloadProgress?.percent?.let { " $it%" }.orEmpty() + if (downloadStatus.isNotBlank() || progressText.isNotBlank()) { + Text( + text = "${downloadStatus.ifBlank { "Скачивание..." }}$progressText", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + lineHeight = 18.sp + ) + } + } + } + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f)) Row( @@ -105,6 +166,7 @@ fun AppUpdateDialog( ) { OutlinedButton( onClick = onPostpone, + enabled = !isDownloading, modifier = Modifier .weight(1f) .heightIn(min = 50.dp), @@ -115,12 +177,23 @@ fun AppUpdateDialog( Button( onClick = onUpdate, + enabled = !isDownloading, modifier = Modifier .weight(1f) .heightIn(min = 50.dp), shape = RoundedCornerShape(22.dp) ) { - Text("Обновить", fontWeight = FontWeight.Bold) + Text(primaryLabel, fontWeight = FontWeight.Bold) + } + } + + if (!isTagOnly) { + TextButton( + onClick = onOpenRelease, + enabled = !isDownloading, + modifier = Modifier.align(Alignment.CenterHorizontally) + ) { + Text("Открыть GitHub вручную") } } } 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 a3f7b44..d69fa70 100644 --- a/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt +++ b/app/src/main/java/com/wdtt/plus/ui/InfoTab.kt @@ -8,7 +8,10 @@ import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build +import android.provider.Settings import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.expandVertically @@ -94,9 +97,16 @@ import com.wdtt.plus.SettingsStore 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.AppUpdateDownloadProgress +import com.wdtt.plus.canRequestApkInstall +import com.wdtt.plus.downloadUpdateApk import com.wdtt.plus.fetchLatestReleaseInfo +import com.wdtt.plus.installUpdateApk import com.wdtt.plus.isNewerVersion +import com.wdtt.plus.selectUpdateApkAsset import kotlinx.coroutines.launch +import java.io.File import kotlin.math.PI import kotlin.math.cos import kotlin.math.min @@ -181,7 +191,11 @@ 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 pendingManualRelease by remember { mutableStateOf(null) } + var updateDownloadProgress by remember { mutableStateOf(null) } + var updateDownloadStatus by rememberSaveable { mutableStateOf("") } + var updateDownloadBusy by remember { mutableStateOf(false) } + var pendingUpdateApkPath by rememberSaveable { mutableStateOf(null) } var showHelpDialog by remember { mutableStateOf(false) } var showSupportDialog by remember { mutableStateOf(false) } var actionsExpanded by actionsExpandedState @@ -198,6 +212,49 @@ fun InfoTab( else -> "Проверить GitHub вручную" } } + val updateInstallPermissionLauncher = rememberLauncherForActivityResult( + ActivityResultContracts.StartActivityForResult() + ) { + val apkFile = pendingUpdateApkPath?.let(::File) + if (apkFile != null && apkFile.exists() && canRequestApkInstall(context)) { + runCatching { + installUpdateApk(context, apkFile) + pendingManualRelease = null + updateDownloadStatus = "" + updateDownloadProgress = null + }.onFailure { error -> + updateDownloadStatus = error.message ?: "Не удалось открыть установку APK." + Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() + } + } else if (apkFile != null) { + updateDownloadStatus = "Разрешение на установку из WDTT Plus не выдано." + Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() + } + } + + fun requestDownloadedUpdateInstall(apkFile: File) { + pendingUpdateApkPath = apkFile.absolutePath + if (!canRequestApkInstall(context)) { + updateDownloadStatus = "Разрешите установку из WDTT Plus в настройках Android." + updateInstallPermissionLauncher.launch( + Intent( + Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:${context.packageName}") + ) + ) + return + } + + runCatching { + installUpdateApk(context, apkFile) + pendingManualRelease = null + updateDownloadStatus = "" + updateDownloadProgress = null + }.onFailure { error -> + updateDownloadStatus = error.message ?: "Не удалось открыть установку APK." + Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() + } + } Column( modifier = Modifier @@ -347,10 +404,17 @@ fun InfoTab( } pendingManualRelease?.let { release -> + val apkAsset = remember(release) { selectUpdateApkAsset(release) } AppUpdateDialog( release = release, + apkAsset = apkAsset, + isDownloading = updateDownloadBusy, + downloadProgress = updateDownloadProgress, + downloadStatus = updateDownloadStatus, onPostpone = { pendingManualRelease = null + updateDownloadStatus = "" + updateDownloadProgress = null Toast.makeText(context, "Обновление отложено на 24 часа.", Toast.LENGTH_SHORT).show() scope.launch { val now = System.currentTimeMillis() @@ -366,15 +430,48 @@ fun InfoTab( } }, onUpdate = { - pendingManualRelease = null scope.launch { settingsStore.saveUpdateDialogAction( version = release.versionTag, action = UPDATE_DIALOG_ACTION_UPDATE, actedAt = System.currentTimeMillis() ) - openUrlInBrowser(context, release.releaseUrl) + if (apkAsset == null) { + pendingManualRelease = null + openUrlInBrowser(context, release.releaseUrl) + return@launch + } + + updateDownloadBusy = true + updateDownloadStatus = "Подготовка скачивания..." + updateDownloadProgress = null + runCatching { + val apkFile = downloadUpdateApk(context, apkAsset) { progress -> + updateDownloadProgress = progress + updateDownloadStatus = if (progress.percent != null) { + "Скачивание APK" + } else { + "Скачивание APK..." + } + } + updateDownloadStatus = if (apkAsset.sha256 != null) { + "APK скачан и проверен. Открываю установку..." + } else { + "APK скачан. Открываю установку..." + } + requestDownloadedUpdateInstall(apkFile) + }.onFailure { error -> + updateDownloadStatus = error.message ?: "Не удалось скачать обновление." + Toast.makeText(context, updateDownloadStatus, Toast.LENGTH_LONG).show() + } + updateDownloadBusy = false } + }, + onOpenRelease = { + pendingManualRelease = null + updateDownloadStatus = "" + updateDownloadProgress = null + openUrlInBrowser(context, release.releaseUrl) } ) } diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml index 86f0f2b..e06e0e5 100644 --- a/app/src/main/res/xml/file_paths.xml +++ b/app/src/main/res/xml/file_paths.xml @@ -3,4 +3,7 @@ +