feat: функция автообновления

This commit is contained in:
samosvalishe committed 2026-04-07 12:06:42 +03:00
1 parent fc2c680255
commit fe5bed40b4
7 files changed
+456

No files matched your search

+11
View File
@@ -13,6 +13,7 @@
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /> <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<application <application
android:allowBackup="true" android:allowBackup="true"
@@ -50,6 +51,16 @@
android:value="Поддержание активного сетевого прокси-соединения через TURN-серверы для обхода ограничений сети." /> android:value="Поддержание активного сетевого прокси-соединения через TURN-серверы для обхода ограничений сети." />
</service> </service>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<receiver <receiver
android:name=".ProxyReceiver" android:name=".ProxyReceiver"
android:exported="true"> android:exported="true">
@@ -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>(UpdateState.Idle)
val state: StateFlow<UpdateState> = _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
}
}
}
@@ -39,7 +39,9 @@ import androidx.compose.material3.CircularWavyProgressIndicator
import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.ListItem import androidx.compose.material3.ListItem
import androidx.compose.material3.ListItemColors
import androidx.compose.material3.ListItemDefaults import androidx.compose.material3.ListItemDefaults
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet 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.LocalContext
import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle 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.MainViewModel
import com.freeturn.app.viewmodel.ProxyState import com.freeturn.app.viewmodel.ProxyState
import com.freeturn.app.viewmodel.SshConnectionState import com.freeturn.app.viewmodel.SshConnectionState
import com.freeturn.app.viewmodel.UpdateState
import androidx.core.net.toUri import androidx.core.net.toUri
@SuppressLint("BatteryLife") @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 @Composable
private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) { private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
val containerColor by animateColorAsState( val containerColor by animateColorAsState(
@@ -359,6 +450,8 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) {
} }
} }
// ── Bottom sheet ──────────────────────────────────────────────────────────
@Composable @Composable
private fun InfoBottomSheet( private fun InfoBottomSheet(
viewModel: MainViewModel, viewModel: MainViewModel,
@@ -371,6 +464,7 @@ private fun InfoBottomSheet(
val uriHandler = LocalUriHandler.current val uriHandler = LocalUriHandler.current
val sshState by viewModel.sshState.collectAsStateWithLifecycle() val sshState by viewModel.sshState.collectAsStateWithLifecycle()
val dynamicTheme by viewModel.dynamicTheme.collectAsStateWithLifecycle() val dynamicTheme by viewModel.dynamicTheme.collectAsStateWithLifecycle()
val updateState by viewModel.updateState.collectAsStateWithLifecycle()
var showResetDialog by rememberSaveable { mutableStateOf(false) } var showResetDialog by rememberSaveable { mutableStateOf(false) }
val appVersion = remember { val appVersion = remember {
@@ -478,6 +572,28 @@ private fun InfoBottomSheet(
item { HorizontalDivider() } 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 { item {
ListItem( 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 @Composable
private fun RepoLinkItem( private fun RepoLinkItem(
title: String, title: String,
@@ -24,3 +24,14 @@ sealed class ProxyState {
object Running : ProxyState() object Running : ProxyState()
data class Error(val message: String) : 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()
}
@@ -11,6 +11,7 @@ import com.freeturn.app.ProxyServiceState
import com.freeturn.app.data.AppPreferences import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.ClientConfig import com.freeturn.app.data.ClientConfig
import com.freeturn.app.data.SshConfig import com.freeturn.app.data.SshConfig
import com.freeturn.app.domain.AppUpdater
import com.freeturn.app.domain.LocalProxyManager import com.freeturn.app.domain.LocalProxyManager
import com.freeturn.app.domain.SshRepository import com.freeturn.app.domain.SshRepository
import com.freeturn.app.ui.HapticUtil import com.freeturn.app.ui.HapticUtil
@@ -27,6 +28,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
private val prefs = AppPreferences(application) private val prefs = AppPreferences(application)
private val sshRepository = SshRepository() private val sshRepository = SshRepository()
private val proxyManager = LocalProxyManager(application) private val proxyManager = LocalProxyManager(application)
private val appUpdater = AppUpdater(application)
val sshState: StateFlow<SshConnectionState> = sshRepository.sshState val sshState: StateFlow<SshConnectionState> = sshRepository.sshState
val serverState: StateFlow<ServerState> = sshRepository.serverState val serverState: StateFlow<ServerState> = sshRepository.serverState
@@ -37,6 +39,7 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
val proxyState: StateFlow<ProxyState> = proxyManager.proxyState val proxyState: StateFlow<ProxyState> = proxyManager.proxyState
val logs: StateFlow<List<String>> = ProxyServiceState.logs val logs: StateFlow<List<String>> = ProxyServiceState.logs
val customKernelExists: StateFlow<Boolean> = proxyManager.customKernelExists val customKernelExists: StateFlow<Boolean> = proxyManager.customKernelExists
val updateState: StateFlow<UpdateState> = appUpdater.state
private val _isInitialized = MutableStateFlow(false) private val _isInitialized = MutableStateFlow(false)
val isInitialized: StateFlow<Boolean> = _isInitialized.asStateFlow() val isInitialized: StateFlow<Boolean> = _isInitialized.asStateFlow()
@@ -53,6 +56,11 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
proxyManager.observeProxyServiceStatus() proxyManager.observeProxyServiceStatus()
} }
proxyManager.syncInitialState() proxyManager.syncInitialState()
// Автоматическая проверка обновлений при холодном запуске (silent — без ошибок)
viewModelScope.launch {
appUpdater.checkForUpdate(silent = true)
}
} }
override fun onCleared() { override fun onCleared() {
@@ -197,6 +205,23 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
_kernelError.value = null _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) { fun resetAllSettings(context: Context) {
viewModelScope.launch { viewModelScope.launch {
if (ProxyServiceState.isRunning.value) { if (ProxyServiceState.isRunning.value) {
+14
View File
@@ -121,6 +121,20 @@
<string name="setup_server">Настроить сервер</string> <string name="setup_server">Настроить сервер</string>
<string name="skip_setup">Пропустить настройки</string> <string name="skip_setup">Пропустить настройки</string>
<!-- Update -->
<string name="update_check">Проверить обновления</string>
<string name="update_checking">Проверка…</string>
<string name="update_available_title">Доступно обновление</string>
<string name="update_available">Доступна версия %1$s</string>
<string name="update_download">Скачать</string>
<string name="update_downloading_title">Загрузка обновления</string>
<string name="update_downloading">Загрузка: %1$d%%</string>
<string name="update_ready_title">Обновление загружено</string>
<string name="update_ready_desc">APK готов к установке. Установить сейчас?</string>
<string name="update_install">Установить</string>
<string name="update_no_update">Установлена последняя версия</string>
<string name="update_error">Ошибка: %1$s</string>
<string name="dynamic_theme_title">Динамическая тема</string> <string name="dynamic_theme_title">Динамическая тема</string>
<string name="dynamic_theme_desc">Использовать системные цвета (Material You)</string> <string name="dynamic_theme_desc">Использовать системные цвета (Material You)</string>
<string name="privacy_mode_title">Приватный режим</string> <string name="privacy_mode_title">Приватный режим</string>
+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="updates" path="." />
</paths>