diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 30124c9..c25fee9 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -13,6 +13,7 @@ + + + + + diff --git a/app/src/main/java/com/freeturn/app/domain/AppUpdater.kt b/app/src/main/java/com/freeturn/app/domain/AppUpdater.kt new file mode 100644 index 0000000..a664643 --- /dev/null +++ b/app/src/main/java/com/freeturn/app/domain/AppUpdater.kt @@ -0,0 +1,170 @@ +package com.freeturn.app.domain + +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import androidx.core.content.FileProvider +import com.freeturn.app.viewmodel.UpdateState +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.io.File +import java.net.HttpURLConnection +import java.net.URL + +class AppUpdater(private val context: Context) { + + private val _state = MutableStateFlow(UpdateState.Idle) + val state: StateFlow = _state.asStateFlow() + + private var latestApkUrl: String? = null + + private val apkFile: File + get() = File(context.cacheDir, "update.apk") + + private fun getCurrentVersion(): String = try { + context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: "0.0.0" + } catch (_: PackageManager.NameNotFoundException) { + "0.0.0" + } + + /** + * @param silent true — при ошибке сети остаёмся в [UpdateState.Idle] (автопроверка при запуске). + * false — показываем [UpdateState.Error] (ручная проверка из UI). + */ + suspend fun checkForUpdate(silent: Boolean = false) { + _state.value = UpdateState.Checking + try { + val release = withContext(Dispatchers.IO) { fetchLatestRelease() } + if (release == null) { + _state.value = if (silent) UpdateState.Idle + else UpdateState.Error("Не удалось получить информацию о релизе") + return + } + + val remoteVersion = release.getString("tag_name").removePrefix("v") + + if (isNewer(remoteVersion, getCurrentVersion())) { + latestApkUrl = findApkUrl(release) + if (latestApkUrl != null) { + val changelog = release.optString("body", "").trim() + _state.value = UpdateState.Available(remoteVersion, changelog) + } else { + _state.value = if (silent) UpdateState.Idle + else UpdateState.Error("APK не найден в релизе") + } + } else { + _state.value = UpdateState.NoUpdate + } + } catch (_: Exception) { + _state.value = if (silent) UpdateState.Idle + else UpdateState.Error("Нет соединения с сервером") + } + } + + suspend fun downloadUpdate() { + val url = latestApkUrl ?: run { + _state.value = UpdateState.Error("URL обновления не найден") + return + } + + _state.value = UpdateState.Downloading(0) + try { + withContext(Dispatchers.IO) { + val connection = URL(url).openConnection() as HttpURLConnection + connection.instanceFollowRedirects = true + connection.connect() + + val totalSize = connection.contentLength.toLong() + var downloaded = 0L + + connection.inputStream.use { input -> + apkFile.outputStream().use { output -> + val buffer = ByteArray(8192) + var bytesRead: Int + while (input.read(buffer).also { bytesRead = it } != -1) { + output.write(buffer, 0, bytesRead) + downloaded += bytesRead + if (totalSize > 0) { + _state.value = UpdateState.Downloading( + (downloaded * 100 / totalSize).toInt() + ) + } + } + } + } + } + _state.value = UpdateState.ReadyToInstall + } catch (e: Exception) { + apkFile.delete() + _state.value = UpdateState.Error("Ошибка загрузки: ${e.message}") + } + } + + fun installUpdate() { + if (!apkFile.exists()) { + _state.value = UpdateState.Error("Файл обновления не найден") + return + } + + val uri = FileProvider.getUriForFile( + context, "${context.packageName}.fileprovider", apkFile + ) + val intent = Intent(Intent.ACTION_VIEW).apply { + setDataAndType(uri, "application/vnd.android.package-archive") + flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION + } + context.startActivity(intent) + } + + fun resetState() { + _state.value = UpdateState.Idle + } + + // ── Private ─────────────────────────────────────────────────────────── + + private fun fetchLatestRelease(): JSONObject? { + val connection = URL(RELEASES_URL).openConnection() as HttpURLConnection + connection.setRequestProperty("Accept", "application/vnd.github+json") + connection.connectTimeout = 10_000 + connection.readTimeout = 10_000 + + return try { + if (connection.responseCode == 200) { + JSONObject(connection.inputStream.bufferedReader().readText()) + } else null + } finally { + connection.disconnect() + } + } + + private fun findApkUrl(release: JSONObject): String? { + val assets = release.getJSONArray("assets") + for (i in 0 until assets.length()) { + val asset = assets.getJSONObject(i) + if (asset.getString("name").endsWith(".apk")) { + return asset.getString("browser_download_url") + } + } + return null + } + + companion object { + private const val RELEASES_URL = + "https://api.github.com/repos/antongospod/turn-proxy-android/releases/latest" + + fun isNewer(remote: String, current: String): Boolean { + val r = remote.split(".").map { it.toIntOrNull() ?: 0 } + val c = current.split(".").map { it.toIntOrNull() ?: 0 } + for (i in 0 until maxOf(r.size, c.size)) { + val rv = r.getOrElse(i) { 0 } + val cv = c.getOrElse(i) { 0 } + if (rv != cv) return rv > cv + } + return false + } + } +} diff --git a/app/src/main/java/com/freeturn/app/ui/screens/HomeScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/HomeScreen.kt index c2de59d..2eacb29 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/HomeScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/HomeScreen.kt @@ -39,7 +39,9 @@ import androidx.compose.material3.CircularWavyProgressIndicator import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.ListItem +import androidx.compose.material3.ListItemColors import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.ModalBottomSheet @@ -75,6 +77,7 @@ import androidx.compose.ui.draw.scale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import androidx.lifecycle.compose.collectAsStateWithLifecycle @@ -86,6 +89,7 @@ import com.freeturn.app.ui.theme.StatusGreenDark import com.freeturn.app.viewmodel.MainViewModel import com.freeturn.app.viewmodel.ProxyState import com.freeturn.app.viewmodel.SshConnectionState +import com.freeturn.app.viewmodel.UpdateState import androidx.core.net.toUri @SuppressLint("BatteryLife") @@ -295,8 +299,95 @@ fun HomeScreen( } } + UpdateDialogs(viewModel) } +// ── Диалоги обновления ──────────────────────────────────────────────────── + +@Composable +private fun UpdateDialogs(viewModel: MainViewModel) { + val context = LocalContext.current + val updateState by viewModel.updateState.collectAsStateWithLifecycle() + var dismissed by rememberSaveable { mutableStateOf(false) } + + when (val state = updateState) { + is UpdateState.Available -> if (!dismissed) { + AlertDialog( + onDismissRequest = { dismissed = true }, + title = { Text(stringResource(R.string.update_available_title)) }, + text = { + Column { + Text(stringResource(R.string.update_available, state.version)) + if (state.changelog.isNotEmpty()) { + Spacer(Modifier.height(8.dp)) + Text( + state.changelog, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 10, + overflow = TextOverflow.Ellipsis + ) + } + } + }, + confirmButton = { + TextButton(onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + dismissed = true + viewModel.downloadUpdate() + }) { Text(stringResource(R.string.update_download)) } + }, + dismissButton = { + TextButton(onClick = { dismissed = true }) { + Text(stringResource(R.string.cancel)) + } + } + ) + } + + is UpdateState.Downloading -> { + AlertDialog( + onDismissRequest = {}, + title = { Text(stringResource(R.string.update_downloading_title)) }, + text = { + Column { + Text(stringResource(R.string.update_downloading, state.progress)) + Spacer(Modifier.height(12.dp)) + LinearProgressIndicator( + progress = { state.progress / 100f }, + modifier = Modifier.fillMaxWidth() + ) + } + }, + confirmButton = {} + ) + } + + is UpdateState.ReadyToInstall -> { + AlertDialog( + onDismissRequest = { viewModel.resetUpdateState() }, + title = { Text(stringResource(R.string.update_ready_title)) }, + text = { Text(stringResource(R.string.update_ready_desc)) }, + confirmButton = { + TextButton(onClick = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + viewModel.installUpdate() + }) { Text(stringResource(R.string.update_install)) } + }, + dismissButton = { + TextButton(onClick = { viewModel.resetUpdateState() }) { + Text(stringResource(R.string.cancel)) + } + } + ) + } + + else -> {} + } +} + +// ── Кнопка прокси ───────────────────────────────────────────────────────── + @Composable private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) { val containerColor by animateColorAsState( @@ -359,6 +450,8 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) { } } +// ── Bottom sheet ────────────────────────────────────────────────────────── + @Composable private fun InfoBottomSheet( viewModel: MainViewModel, @@ -371,6 +464,7 @@ private fun InfoBottomSheet( val uriHandler = LocalUriHandler.current val sshState by viewModel.sshState.collectAsStateWithLifecycle() val dynamicTheme by viewModel.dynamicTheme.collectAsStateWithLifecycle() + val updateState by viewModel.updateState.collectAsStateWithLifecycle() var showResetDialog by rememberSaveable { mutableStateOf(false) } val appVersion = remember { @@ -478,6 +572,28 @@ private fun InfoBottomSheet( item { HorizontalDivider() } + // ── Обновление ──────────────────────────────────────────────────── + item { + UpdateListItem( + state = updateState, + colors = listColors, + onCheck = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + viewModel.checkForUpdate() + }, + onDownload = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + viewModel.downloadUpdate() + }, + onInstall = { + HapticUtil.perform(context, HapticUtil.Pattern.CLICK) + viewModel.installUpdate() + } + ) + } + + item { HorizontalDivider() } + // ── Сброс ───────────────────────────────────────────────────────── item { ListItem( @@ -541,6 +657,111 @@ private fun InfoBottomSheet( } } +// ── Пункт обновления в bottom sheet ─────────────────────────────────────── + +@Composable +private fun UpdateListItem( + state: UpdateState, + colors: ListItemColors, + onCheck: () -> Unit, + onDownload: () -> Unit, + onInstall: () -> Unit +) { + when (state) { + is UpdateState.Idle -> { + ListItem( + headlineContent = { Text(stringResource(R.string.update_check)) }, + colors = colors, + modifier = Modifier.clickable(onClick = onCheck) + ) + } + + is UpdateState.Checking -> { + ListItem( + headlineContent = { Text(stringResource(R.string.update_checking)) }, + colors = colors + ) + } + + is UpdateState.Available -> { + ListItem( + headlineContent = { + Text(stringResource(R.string.update_available, state.version)) + }, + supportingContent = if (state.changelog.isNotEmpty()) { + { + Text( + state.changelog, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 3, + overflow = TextOverflow.Ellipsis + ) + } + } else null, + colors = colors, + trailingContent = { + TextButton(onClick = onDownload) { + Text(stringResource(R.string.update_download)) + } + } + ) + } + + is UpdateState.Downloading -> { + ListItem( + headlineContent = { + Text(stringResource(R.string.update_downloading, state.progress)) + }, + supportingContent = { + LinearProgressIndicator( + progress = { state.progress / 100f }, + modifier = Modifier + .fillMaxWidth() + .padding(top = 8.dp) + ) + }, + colors = colors + ) + } + + is UpdateState.ReadyToInstall -> { + ListItem( + headlineContent = { Text(stringResource(R.string.update_ready_title)) }, + colors = colors, + trailingContent = { + TextButton(onClick = onInstall) { + Text(stringResource(R.string.update_install)) + } + } + ) + } + + is UpdateState.NoUpdate -> { + ListItem( + headlineContent = { Text(stringResource(R.string.update_no_update)) }, + colors = colors, + modifier = Modifier.clickable(onClick = onCheck) + ) + } + + is UpdateState.Error -> { + ListItem( + headlineContent = { + Text( + stringResource(R.string.update_error, state.message), + color = MaterialTheme.colorScheme.error + ) + }, + colors = colors, + modifier = Modifier.clickable(onClick = onCheck) + ) + } + } +} + +// ── Общие компоненты ────────────────────────────────────────────────────── + @Composable private fun RepoLinkItem( title: String, diff --git a/app/src/main/java/com/freeturn/app/viewmodel/AppStates.kt b/app/src/main/java/com/freeturn/app/viewmodel/AppStates.kt index fa5d08b..815257e 100644 --- a/app/src/main/java/com/freeturn/app/viewmodel/AppStates.kt +++ b/app/src/main/java/com/freeturn/app/viewmodel/AppStates.kt @@ -24,3 +24,14 @@ sealed class ProxyState { object Running : ProxyState() data class Error(val message: String) : ProxyState() } + +// ── App update states ────────────────────────────────────────────────────── +sealed class UpdateState { + object Idle : UpdateState() + object Checking : UpdateState() + data class Available(val version: String, val changelog: String) : UpdateState() + object NoUpdate : UpdateState() + data class Downloading(val progress: Int) : UpdateState() + object ReadyToInstall : UpdateState() + data class Error(val message: String) : UpdateState() +} diff --git a/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt b/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt index 043385a..4d1ad82 100644 --- a/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt +++ b/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt @@ -11,6 +11,7 @@ import com.freeturn.app.ProxyServiceState import com.freeturn.app.data.AppPreferences import com.freeturn.app.data.ClientConfig import com.freeturn.app.data.SshConfig +import com.freeturn.app.domain.AppUpdater import com.freeturn.app.domain.LocalProxyManager import com.freeturn.app.domain.SshRepository import com.freeturn.app.ui.HapticUtil @@ -27,6 +28,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { private val prefs = AppPreferences(application) private val sshRepository = SshRepository() private val proxyManager = LocalProxyManager(application) + private val appUpdater = AppUpdater(application) val sshState: StateFlow = sshRepository.sshState val serverState: StateFlow = sshRepository.serverState @@ -37,6 +39,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { val proxyState: StateFlow = proxyManager.proxyState val logs: StateFlow> = ProxyServiceState.logs val customKernelExists: StateFlow = proxyManager.customKernelExists + val updateState: StateFlow = appUpdater.state private val _isInitialized = MutableStateFlow(false) val isInitialized: StateFlow = _isInitialized.asStateFlow() @@ -53,6 +56,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { proxyManager.observeProxyServiceStatus() } proxyManager.syncInitialState() + + // Автоматическая проверка обновлений при холодном запуске (silent — без ошибок) + viewModelScope.launch { + appUpdater.checkForUpdate(silent = true) + } } override fun onCleared() { @@ -197,6 +205,23 @@ class MainViewModel(application: Application) : AndroidViewModel(application) { _kernelError.value = null } + // ── App update ────────────────────────────────────────────────────── + fun checkForUpdate() { + viewModelScope.launch { appUpdater.checkForUpdate(silent = false) } + } + + fun downloadUpdate() { + viewModelScope.launch { appUpdater.downloadUpdate() } + } + + fun installUpdate() { + appUpdater.installUpdate() + } + + fun resetUpdateState() { + appUpdater.resetState() + } + fun resetAllSettings(context: Context) { viewModelScope.launch { if (ProxyServiceState.isRunning.value) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 07f8591..4e497d4 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -121,6 +121,20 @@ Настроить сервер Пропустить настройки + + Проверить обновления + Проверка… + Доступно обновление + Доступна версия %1$s + Скачать + Загрузка обновления + Загрузка: %1$d%% + Обновление загружено + APK готов к установке. Установить сейчас? + Установить + Установлена последняя версия + Ошибка: %1$s + Динамическая тема Использовать системные цвета (Material You) Приватный режим diff --git a/app/src/main/res/xml/file_paths.xml b/app/src/main/res/xml/file_paths.xml new file mode 100644 index 0000000..fb000a8 --- /dev/null +++ b/app/src/main/res/xml/file_paths.xml @@ -0,0 +1,4 @@ + + + +