refactor(viewmodel): разнести SettingsViewModel и увести вибрацию за интерфейс

Серверы и бэкап - свои VM (события бэкапа через Channel). HapticUtil ушёл в ui/util, VM знают только исход операции. Флаг вывода логов ведёт один сборщик в App.
This commit is contained in:
samosvalishe committed 2026-09-20 10:07:33 +03:00
1 parent 2cfa906606
commit 377e0f74ce
50 files changed
+531 -451

No files matched your search

+10
View File
@@ -15,6 +15,7 @@ import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
@@ -47,9 +48,18 @@ class App : Application() {
ProxyNotifier.createChannels(this)
reportPreviousExit()
warmUpCore()
observeLogsEnabled()
observeWidgetState()
}
private fun observeLogsEnabled() {
appPreferences.clientConfigFlow
.map { it.logsEnabled }
.distinctUntilChanged()
.onEach(ProxyStore::setLogsEnabled)
.launchIn(scope)
}
// Незакрытая сессия не доказывает причину завершения процесса.
private fun reportPreviousExit() {
scope.launch {
@@ -12,7 +12,7 @@ import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.freeturn.app.domain.share.LinkImportBus
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.navigation.AppNavigation
import com.freeturn.app.ui.theme.FreeTurnTheme
import org.koin.android.ext.android.inject
@@ -17,7 +17,11 @@ import com.freeturn.app.viewmodel.proxy.ProxyViewModel
import com.freeturn.app.viewmodel.server.ServerSetupViewModel
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import com.freeturn.app.viewmodel.settings.BackupViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.share.ShareViewModel
import com.freeturn.app.ui.util.AndroidHaptics
import com.freeturn.app.viewmodel.Haptics
import org.koin.android.ext.koin.androidContext
import org.koin.core.module.dsl.viewModelOf
import org.koin.dsl.module
@@ -40,10 +44,13 @@ val appModule = module {
// factory по той же причине: SSH-операции шаринга не делят сессию с активным сервером.
factory { ShareRepository(androidContext(), get()) }
single { LinkImportBus() }
single<Haptics> { AndroidHaptics(androidContext()) }
viewModelOf(::ProxyViewModel)
viewModelOf(::ServerViewModel)
viewModelOf(::SettingsViewModel)
viewModelOf(::ServerConfigViewModel)
viewModelOf(::BackupViewModel)
viewModelOf(::ServerSetupViewModel)
viewModelOf(::ShareViewModel)
viewModelOf(::ImportViewModel)
@@ -167,7 +167,6 @@ class ProxyService : VpnService() {
private suspend fun startSession(session: Long, fresh: Boolean) {
val cfg = prefs.clientConfigFlow.first()
if (!isCurrent(session)) return
ProxyStore.setLogsEnabled(cfg.logsEnabled)
// Лог рестарта не чистим: строка "Процесс запущен" от App - единственный след того,
// что процесс убивали, и после clearLogs от неё ничего бы не осталось.
if (fresh) ProxyStore.clearLogs()
@@ -28,7 +28,7 @@ import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.util.hapticClickable
import com.freeturn.app.ui.theme.Spacing
@@ -32,7 +32,7 @@ import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.util.hapticClickable
import kotlin.math.roundToInt
@@ -30,7 +30,7 @@ import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.config.SshConfig
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
@Composable
fun SshFormFields(
@@ -15,7 +15,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.theme.Spacing
/**
@@ -8,7 +8,7 @@ import androidx.navigation.compose.navigation
import com.freeturn.app.ui.screens.addserver.AddServerScreen
import com.freeturn.app.ui.screens.setup.ServerSetupScreen
import com.freeturn.app.ui.screens.share.QrScannerScreen
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
/**
* Вкладка "+": мастер self-hosted живёт целиком в этом графе. Кросс-графовый push
@@ -17,18 +17,17 @@ import com.freeturn.app.viewmodel.settings.SettingsViewModel
*/
internal fun NavGraphBuilder.addGraph(
navController: NavHostController,
settingsViewModel: SettingsViewModel
serverConfigViewModel: ServerConfigViewModel
) {
navigation<AddGraph>(startDestination = AddServer) {
composable<AddServer> { entry ->
AddServerScreen(
settingsViewModel = settingsViewModel,
onSelfHosted = { if (entry.isResumed()) navController.navigate(SelfHostedSetup) },
// Ручная настройка: создаём пустой сервер и уводим в его хаб. Хаб живёт в
// графе настроек - тот же tab-switch + singleTop-push, что у HomeScreen
// (кросс-графовый push ломает restoreState вкладок).
onManualCreate = { name ->
settingsViewModel.addManualServer(name) { id ->
serverConfigViewModel.addManualServer(name) { id ->
navController.navigateToTab(SettingsGraph)
navController.navigate(ServerDetail(id)) { launchSingleTop = true }
}
@@ -44,11 +44,12 @@ import androidx.navigation.compose.NavHost
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.screens.captcha.CaptchaWebViewDialog
import com.freeturn.app.ui.screens.share.ImportSheet
import com.freeturn.app.ui.theme.LocalReducedMotion
import com.freeturn.app.viewmodel.proxy.ProxyViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import kotlinx.coroutines.flow.distinctUntilChanged
@@ -65,7 +66,8 @@ private const val NAV_FADE_OUT_MS = 120
fun AppNavigation(
settingsViewModel: SettingsViewModel = koinViewModel(),
proxyViewModel: ProxyViewModel = koinViewModel(),
serverViewModel: ServerViewModel = koinViewModel()
serverViewModel: ServerViewModel = koinViewModel(),
serverConfigViewModel: ServerConfigViewModel = koinViewModel()
) {
val isInitialized by settingsViewModel.isInitialized.collectAsStateWithLifecycle()
@@ -77,7 +79,7 @@ fun AppNavigation(
val initialTgSubscribeShown by settingsViewModel.initialTgSubscribeShown.collectAsStateWithLifecycle()
val initialSuppressTgPrompt by settingsViewModel.initialSuppressTgPrompt.collectAsStateWithLifecycle()
val nerdMode by settingsViewModel.nerdMode.collectAsStateWithLifecycle()
val clientConfig by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val clientConfig by serverConfigViewModel.clientConfig.collectAsStateWithLifecycle()
val logsTabVisible = nerdMode && clientConfig.logsEnabled
val navController = rememberNavController()
val backStackEntry by navController.currentBackStackEntryAsState()
@@ -93,7 +95,7 @@ fun AppNavigation(
// (там мог остаться хаб другого сервера) - сбрасываем его к корню. Если стек
// настроек сейчас активен (не сохранён), clearBackStack - no-op.
LaunchedEffect(navController) {
settingsViewModel.serversSnapshot
serverConfigViewModel.serversSnapshot
.map { it.activeId }
.distinctUntilChanged()
.drop(1) // первая эмиссия - текущее значение, не смена
@@ -147,7 +149,8 @@ fun AppNavigation(
navController = navController,
settingsViewModel = settingsViewModel,
proxyViewModel = proxyViewModel,
serverViewModel = serverViewModel
serverViewModel = serverViewModel,
serverConfigViewModel = serverConfigViewModel
)
}
@@ -188,7 +191,8 @@ private fun AppNavHost(
navController: NavHostController,
settingsViewModel: SettingsViewModel,
proxyViewModel: ProxyViewModel,
serverViewModel: ServerViewModel
serverViewModel: ServerViewModel,
serverConfigViewModel: ServerConfigViewModel
) {
// Системная настройка reduced motion отключает shared-axis переходы.
val reducedMotion = LocalReducedMotion.current
@@ -229,11 +233,11 @@ private fun AppNavHost(
slideOutHorizontally(tween(NAV_SLIDE_MS, easing = EmphasizedEasing)) { it / 12 }
}
) {
homeGraph(navController, settingsViewModel, proxyViewModel)
homeGraph(navController, settingsViewModel, serverConfigViewModel, proxyViewModel)
logsGraph(proxyViewModel)
shareGraph(navController)
addGraph(navController, settingsViewModel)
settingsGraph(navController, settingsViewModel, proxyViewModel, serverViewModel)
addGraph(navController, serverConfigViewModel)
settingsGraph(navController, settingsViewModel, serverConfigViewModel, proxyViewModel, serverViewModel)
}
}
@@ -6,18 +6,21 @@ import androidx.navigation.compose.composable
import androidx.navigation.compose.navigation
import com.freeturn.app.ui.screens.home.HomeScreen
import com.freeturn.app.viewmodel.proxy.ProxyViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
/** Вкладка "Главная". Логи - отдельная вкладка нижнего меню (см. [logsGraph]). */
internal fun NavGraphBuilder.homeGraph(
navController: NavHostController,
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
proxyViewModel: ProxyViewModel
) {
navigation<HomeGraph>(startDestination = Home) {
composable<Home> { entry ->
HomeScreen(
settingsViewModel = settingsViewModel,
serverConfigViewModel = serverConfigViewModel,
proxyViewModel = proxyViewModel,
// Хаб живёт в графе настроек. Прямой navigate отсюда пушил бы settings-экраны
// в стек вкладки "Главная" - save/restore вкладок портится. Поэтому сперва
@@ -17,6 +17,7 @@ import com.freeturn.app.ui.screens.settings.ServersListScreen
import com.freeturn.app.ui.screens.settings.SettingsScreen
import com.freeturn.app.ui.screens.sshsetup.SshSetupScreen
import com.freeturn.app.viewmodel.proxy.ProxyViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
@@ -24,6 +25,7 @@ import com.freeturn.app.viewmodel.settings.SettingsViewModel
internal fun NavGraphBuilder.settingsGraph(
navController: NavHostController,
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
proxyViewModel: ProxyViewModel,
serverViewModel: ServerViewModel
) {
@@ -58,6 +60,7 @@ internal fun NavGraphBuilder.settingsGraph(
composable<ServersList> {
ServersListScreen(
settingsViewModel = settingsViewModel,
serverConfigViewModel = serverConfigViewModel,
onBack = { navController.popBackStack() },
onOpenServer = { id -> navController.navigate(ServerDetail(id)) }
)
@@ -68,6 +71,7 @@ internal fun NavGraphBuilder.settingsGraph(
ServerDetailScreen(
serverId = id,
settingsViewModel = settingsViewModel,
serverConfigViewModel = serverConfigViewModel,
serverViewModel = serverViewModel,
onBack = { navController.popBackStack() },
onOpenConnection = { navController.navigate(ClientSetup(id)) },
@@ -83,6 +87,7 @@ internal fun NavGraphBuilder.settingsGraph(
NerdScreen(
serverId = id,
settingsViewModel = settingsViewModel,
serverConfigViewModel = serverConfigViewModel,
serverViewModel = serverViewModel,
onBack = { navController.popBackStack() }
)
@@ -92,6 +97,7 @@ internal fun NavGraphBuilder.settingsGraph(
val id = entry.toRoute<ConnectionMode>().serverId
ConnectionModeScreen(
settingsViewModel = settingsViewModel,
serverConfigViewModel = serverConfigViewModel,
proxyViewModel = proxyViewModel,
serverId = id,
onBack = { navController.popBackStack() }
@@ -103,6 +109,7 @@ internal fun NavGraphBuilder.settingsGraph(
ServerManagementScreen(
serverViewModel = serverViewModel,
settingsViewModel = settingsViewModel,
serverConfigViewModel = serverConfigViewModel,
serverId = id,
onBack = { navController.popBackStack() },
onEditConnection = { navController.navigate(SshSetup) }
@@ -113,6 +120,7 @@ internal fun NavGraphBuilder.settingsGraph(
val id = entry.toRoute<ClientSetup>().serverId
ClientSetupScreen(
settingsViewModel = settingsViewModel,
serverConfigViewModel = serverConfigViewModel,
serverViewModel = serverViewModel,
serverId = id,
onBack = { navController.popBackStack() }
@@ -122,7 +130,7 @@ internal fun NavGraphBuilder.settingsGraph(
composable<SshSetup> {
SshSetupScreen(
serverViewModel = serverViewModel,
settingsViewModel = settingsViewModel,
serverConfigViewModel = serverConfigViewModel,
// Форма поверх настроек сервера - после успеха возвращаемся назад.
onConnected = { navController.popBackStack() },
onBack = { navController.popBackStack() }
@@ -50,8 +50,9 @@ import com.freeturn.app.ui.components.SettingsGroup
import com.freeturn.app.ui.components.SettingsGroupItem
import com.freeturn.app.ui.screens.settings.backupEventMessage
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import com.freeturn.app.viewmodel.settings.BackupViewModel
import kotlinx.coroutines.launch
import org.koin.androidx.compose.koinViewModel
import org.koin.compose.koinInject
/**
@@ -63,10 +64,10 @@ import org.koin.compose.koinInject
*/
@Composable
fun AddServerScreen(
settingsViewModel: SettingsViewModel,
onSelfHosted: () -> Unit,
onManualCreate: (String) -> Unit,
onScanQr: () -> Unit
onScanQr: () -> Unit,
backupViewModel: BackupViewModel = koinViewModel()
) {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
var showManualDialog by rememberSaveable { mutableStateOf(false) }
@@ -89,7 +90,7 @@ fun AddServerScreen(
}
LaunchedEffect(Unit) {
settingsViewModel.backupEvents.collect { event ->
backupViewModel.events.collect { event ->
snackbarHostState.showSnackbar(backupEventMessage(context, event))
}
}
@@ -191,7 +192,7 @@ fun AddServerScreen(
requireConfirmation = false,
onConfirm = { password ->
showRestoreDialog = false
restoreUri?.let { settingsViewModel.restoreBackup(it, password) }
restoreUri?.let { backupViewModel.restoreBackup(it, password) }
},
onDismiss = { showRestoreDialog = false },
warning = stringResource(R.string.backup_restore_warning)
@@ -14,7 +14,7 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
/** Диалог ручной настройки: только имя будущего сервера, остальное - потом в хабе. */
@Composable
@@ -18,7 +18,7 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.theme.Spacing
/** Поле импорта по ссылке: кнопка читает буфер обмена и отдаёт его в LinkImportBus. */
@@ -135,7 +135,8 @@ private fun CaptchaWebView(url: String) {
}
loadUrl(url)
}
}
},
onRelease = { it.destroy() }
)
if (progress < 1f) {
LinearProgressIndicator(
@@ -44,10 +44,11 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R
import com.freeturn.app.data.config.ClientConfig
import com.freeturn.app.data.config.Provider
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import kotlin.math.roundToInt
import kotlinx.coroutines.delay
@@ -55,15 +56,16 @@ import kotlinx.coroutines.delay
@Composable
fun ClientSetupScreen(
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
serverViewModel: ServerViewModel,
// null = активный сервер; не-null = конкретный сервер по id (Settings-флоу).
serverId: String? = null,
onBack: (() -> Unit)? = null
) {
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val activeClient by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val snapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()
val activeClient by serverConfigViewModel.clientConfig.collectAsStateWithLifecycle()
val sshConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle()
val activeProxyListen by settingsViewModel.proxyListen.collectAsStateWithLifecycle()
val activeProxyListen by serverConfigViewModel.proxyListen.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
// Источник данных: конкретный сервер по id либо активный.
@@ -74,7 +76,7 @@ fun ClientSetupScreen(
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
val targetId = serverId ?: snapshot.activeId ?: return
settingsViewModel.updateServerClient(targetId, transform)
serverConfigViewModel.updateServerClient(targetId, transform)
}
val context = LocalContext.current
@@ -51,7 +51,7 @@ import com.freeturn.app.data.config.ClientConfig
import com.freeturn.app.data.config.ProxyMode
import com.freeturn.app.data.config.TunnelTransport
import com.freeturn.app.data.server.ServerOpts
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.ApplyFab
import com.freeturn.app.ui.components.FabClearance
import com.freeturn.app.ui.components.InlineNoticeCard
@@ -64,6 +64,7 @@ import com.freeturn.app.ui.components.UdpTcpSegmented
import com.freeturn.app.ui.screens.splittunnel.SplitTunnelModal
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.viewmodel.proxy.ProxyViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
@@ -73,12 +74,13 @@ import kotlinx.coroutines.withContext
@Composable
fun ConnectionModeScreen(
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
proxyViewModel: ProxyViewModel,
serverId: String? = null,
onBack: (() -> Unit)? = null
) {
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val activeClient by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val snapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()
val activeClient by serverConfigViewModel.clientConfig.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val status by proxyViewModel.status.collectAsStateWithLifecycle()
@@ -89,7 +91,7 @@ fun ConnectionModeScreen(
fun clientEdit(transform: (ClientConfig) -> ClientConfig) {
val targetId = serverId ?: snapshot.activeId ?: return
settingsViewModel.updateServerClient(targetId, transform)
serverConfigViewModel.updateServerClient(targetId, transform)
}
val context = LocalContext.current
@@ -112,7 +114,7 @@ fun ConnectionModeScreen(
fun applyForward() {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
settingsViewModel.applyForwardConfig(
serverConfigViewModel.applyForwardConfig(
serverId,
if (isTcp) ProxyMode.TCP else ProxyMode.UDP,
kcpDraft
@@ -229,7 +231,7 @@ fun ConnectionModeScreen(
// Встроенный туннель живёт только поверх udp: иначе сервер
// остался бы поднят в tcp и отклонял бы наши сессии.
isTcp = false
if (savedOpts.tcpMode) settingsViewModel.setProxyMode(serverId, ProxyMode.UDP)
if (savedOpts.tcpMode) serverConfigViewModel.setProxyMode(serverId, ProxyMode.UDP)
},
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
) { Text(stringResource(R.string.mode_vpn)) }
@@ -301,8 +303,8 @@ fun ConnectionModeScreen(
mode = saved.splitTunnelMode,
apps = saved.splitTunnelApps,
locked = status.busy,
onModeChange = settingsViewModel::setSplitTunnelMode,
onAppsChange = settingsViewModel::setSplitTunnelApps,
onModeChange = serverConfigViewModel::setSplitTunnelMode,
onAppsChange = serverConfigViewModel::setSplitTunnelApps,
onDismiss = { showSplitSheet = false },
containerColor = MaterialTheme.colorScheme.surfaceContainerLow
)
@@ -35,7 +35,7 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import kotlinx.coroutines.launch
import kotlin.math.abs
import kotlin.math.atan2
@@ -38,9 +38,10 @@ import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.data.config.SplitTunnelMode
import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.screens.splittunnel.SplitTunnelModal
import com.freeturn.app.viewmodel.proxy.ProxyViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import kotlinx.coroutines.launch
import com.freeturn.app.ui.theme.Spacing
@@ -49,6 +50,7 @@ import com.freeturn.app.ui.theme.Spacing
@Composable
fun HomeScreen(
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
proxyViewModel: ProxyViewModel,
onOpenServerSettings: (String) -> Unit,
onAddServer: () -> Unit
@@ -56,12 +58,12 @@ fun HomeScreen(
val context = LocalContext.current
val status by proxyViewModel.status.collectAsStateWithLifecycle()
val uptimeText = rememberProxyUptime(status.connectedSince)
val clientConfig by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val clientConfig by serverConfigViewModel.clientConfig.collectAsStateWithLifecycle()
val updateState by settingsViewModel.updateState.collectAsStateWithLifecycle()
val suppressUpdatePrompt by settingsViewModel.suppressUpdatePrompt.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val seasonalDecor by settingsViewModel.seasonalDecor.collectAsStateWithLifecycle()
val serversSnapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val serversSnapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()
RequestStartupPermissions(settingsViewModel)
@@ -129,7 +131,7 @@ fun HomeScreen(
// Правка ссылки только пока прокси стоит (новая комната = реконнект).
callLinkLocked = status.busy,
onApplyServer = { id ->
settingsViewModel.applyServer(id)
serverConfigViewModel.applyServer(id)
scope.launch { sheetScaffoldState.bottomSheetState.partialExpand() }
},
onOpenServerSettings = { id ->
@@ -137,7 +139,7 @@ fun HomeScreen(
scope.launch { sheetScaffoldState.bottomSheetState.partialExpand() }
onOpenServerSettings(id)
},
onSaveCallLink = { settingsViewModel.setActiveVkLink(it) }
onSaveCallLink = { serverConfigViewModel.setActiveVkLink(it) }
)
},
snackbarHost = { SnackbarHost(snackbarHostState) }
@@ -191,8 +193,8 @@ fun HomeScreen(
mode = clientConfig.splitTunnelMode,
apps = clientConfig.splitTunnelApps,
locked = status.busy,
onModeChange = settingsViewModel::setSplitTunnelMode,
onAppsChange = settingsViewModel::setSplitTunnelApps,
onModeChange = serverConfigViewModel::setSplitTunnelMode,
onAppsChange = serverConfigViewModel::setSplitTunnelApps,
onDismiss = { showSplitSheet.value = false },
containerColor = sheetColor
)
@@ -55,7 +55,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.data.config.Provider
import com.freeturn.app.data.server.ServersSnapshot
import com.freeturn.app.ui.components.ServerRow
@@ -19,7 +19,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.domain.UpdateState
import com.freeturn.app.ui.components.BusyProgressIndicator
@@ -60,7 +60,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R
import com.freeturn.app.ui.components.EmptyState
import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.domain.proxy.LogEntry
import com.freeturn.app.domain.proxy.LogLevel
import com.freeturn.app.ui.theme.Spacing
@@ -19,11 +19,11 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.data.control.UninstallData
import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.viewmodel.settings.ServerCleanupState
import com.freeturn.app.viewmodel.server.ServerCleanupState
/** Подтверждение удаления сервера из приложения (без серверной очистки). */
@Composable
@@ -42,7 +42,7 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.domain.SshConnectionState
import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.components.SettingsBackButton
@@ -58,12 +58,14 @@ import com.freeturn.app.ui.util.redact
import com.freeturn.app.viewmodel.server.ServerHubState
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.server.serverSettingsAvailable
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
@Composable
fun ServerDetailScreen(
serverId: String,
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
serverViewModel: ServerViewModel,
onBack: () -> Unit,
onOpenConnection: (String) -> Unit,
@@ -73,7 +75,7 @@ fun ServerDetailScreen(
onCloned: (String) -> Unit
) {
val context = LocalContext.current
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val snapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val sshState by serverViewModel.sshState.collectAsStateWithLifecycle()
val sshConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle()
@@ -149,7 +151,7 @@ fun ServerDetailScreen(
onRename = { showRename = true },
onClone = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
settingsViewModel.cloneServer(serverId, onCloned)
serverConfigViewModel.cloneServer(serverId, onCloned)
}
)
}
@@ -177,7 +179,7 @@ fun ServerDetailScreen(
syncOn = sshConfigured && server.client.syncServerSwitches,
onActivate = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
settingsViewModel.applyServer(serverId)
serverConfigViewModel.applyServer(serverId)
},
onRetry = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
@@ -192,8 +194,8 @@ fun ServerDetailScreen(
checked = sshConfigured && server.client.syncServerSwitches,
enabled = sshConfigured,
onCheckedChange = { v ->
if (isActive) settingsViewModel.setSyncServerSwitches(v)
else settingsViewModel.updateServerClient(serverId) { it.copy(syncServerSwitches = v) }
if (isActive) serverConfigViewModel.setSyncServerSwitches(v)
else serverConfigViewModel.updateServerClient(serverId) { it.copy(syncServerSwitches = v) }
}
)
}
@@ -297,7 +299,7 @@ fun ServerDetailScreen(
DeleteServerDialog(
serverName = server.name,
onConfirm = {
settingsViewModel.deleteServer(serverId)
serverConfigViewModel.deleteServer(serverId)
showDelete = false
},
onDismiss = { showDelete = false }
@@ -305,13 +307,13 @@ fun ServerDetailScreen(
}
if (showCleanup && server != null) {
val cleanupState by settingsViewModel.cleanupState.collectAsStateWithLifecycle()
val cleanupState by serverConfigViewModel.cleanupState.collectAsStateWithLifecycle()
ServerCleanupDialog(
state = cleanupState,
onConfirm = { settingsViewModel.cleanupServer(serverId) },
onConfirm = { serverConfigViewModel.cleanupServer(serverId) },
onClose = {
showCleanup = false
settingsViewModel.resetCleanupState()
serverConfigViewModel.resetCleanupState()
}
)
}
@@ -320,7 +322,7 @@ fun ServerDetailScreen(
RenameServerDialog(
currentName = server.name,
onSave = { name ->
settingsViewModel.renameServer(serverId, name)
serverConfigViewModel.renameServer(serverId, name)
showRename = false
},
onDismiss = { showRename = false }
@@ -56,13 +56,14 @@ import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.config.ProxyMode
import com.freeturn.app.domain.ServerState
import com.freeturn.app.domain.SshConnectionState
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.ApplyFab
import com.freeturn.app.ui.components.FabClearance
import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.ui.util.copyToClipboard
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import com.freeturn.app.viewmodel.server.serverSettingsAvailable
import kotlinx.coroutines.delay
@@ -71,23 +72,24 @@ import kotlinx.coroutines.delay
fun ServerManagementScreen(
serverViewModel: ServerViewModel,
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
onEditConnection: (() -> Unit)? = null,
// null = активный сервер; не-null = настройки конкретного сервера по id (Settings).
serverId: String? = null,
onBack: () -> Unit
) {
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val snapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()
val server = serverId?.let { id -> snapshot.list.firstOrNull { it.id == id } }
// Управление ядром доступно только для активного сервера.
val isActive = serverId == null || serverId == snapshot.activeId
val sshState by serverViewModel.sshState.collectAsStateWithLifecycle()
val serverState by serverViewModel.serverState.collectAsStateWithLifecycle()
val activeListen by settingsViewModel.proxyListen.collectAsStateWithLifecycle()
val activeConnect by settingsViewModel.proxyConnect.collectAsStateWithLifecycle()
val activeListen by serverConfigViewModel.proxyListen.collectAsStateWithLifecycle()
val activeConnect by serverConfigViewModel.proxyConnect.collectAsStateWithLifecycle()
val savedListen = server?.proxyListen ?: activeListen
val savedConnect = server?.proxyConnect ?: activeConnect
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val clientCfg by settingsViewModel.clientConfig.collectAsStateWithLifecycle()
val clientCfg by serverConfigViewModel.clientConfig.collectAsStateWithLifecycle()
val serverOpts by serverViewModel.serverOpts.collectAsStateWithLifecycle()
// Источник черновиков: живой конфиг (активный) или снимок (неактивный).
val effClient = if (isActive) clientCfg else (server?.client ?: clientCfg)
@@ -137,10 +139,10 @@ fun ServerManagementScreen(
// Пейсинг без профиля ядро отвергает.
val timing = if (obfDraft == ObfProfile.NONE) 0 else timingDraft
if (isActive) {
settingsViewModel.applyServerConfig(listenFull, proxyConnect, mode, obfDraft, keyDraft, timing)
serverConfigViewModel.applyServerConfig(listenFull, proxyConnect, mode, obfDraft, keyDraft, timing)
} else {
// !isActive ⇒ serverId != null (см. isActive выше) - smart cast.
settingsViewModel.updateServerConfig(serverId, listenFull, proxyConnect, mode, obfDraft, keyDraft, timing)
serverConfigViewModel.updateServerConfig(serverId, listenFull, proxyConnect, mode, obfDraft, keyDraft, timing)
}
onBack()
}
@@ -218,7 +220,7 @@ fun ServerManagementScreen(
actionLabel = stringResource(R.string.make_active),
onAction = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
settingsViewModel.applyServer(serverId)
serverConfigViewModel.applyServer(serverId)
}
)
Spacer(Modifier.height(Spacing.xxl))
@@ -40,7 +40,7 @@ import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.components.SettingsBackButton
import com.freeturn.app.ui.components.SettingsContentMaxWidth
@@ -61,7 +61,7 @@ import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R
import com.freeturn.app.domain.UpdateState
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.BackupPasswordDialog
import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.components.SectionLabel
@@ -77,7 +77,9 @@ import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.ui.util.hapticClickable
import com.freeturn.app.viewmodel.settings.BackupEvent
import com.freeturn.app.viewmodel.settings.RestoreFailReason
import com.freeturn.app.viewmodel.settings.BackupViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import org.koin.androidx.compose.koinViewModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
@@ -87,7 +89,8 @@ import java.util.Locale
@Composable
fun AppScreen(
settingsViewModel: SettingsViewModel,
onBack: () -> Unit
onBack: () -> Unit,
backupViewModel: BackupViewModel = koinViewModel()
) {
val context = LocalContext.current
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
@@ -108,12 +111,12 @@ fun AppScreen(
val exportLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.CreateDocument("application/octet-stream")
) { uri: Uri? ->
if (uri != null) settingsViewModel.exportBackup(uri, exportPassword)
if (uri != null) backupViewModel.exportBackup(uri, exportPassword)
}
// Снекбар по результату экспорта/импорта.
LaunchedEffect(Unit) {
settingsViewModel.backupEvents.collect { event ->
backupViewModel.events.collect { event ->
snackbarHostState.showSnackbar(backupEventMessage(context, event))
}
}
@@ -263,7 +266,7 @@ fun AppScreen(
TextButton(
onClick = {
showResetDialog = false
settingsViewModel.resetAllSettings()
backupViewModel.resetAllSettings()
},
colors = ButtonDefaults.textButtonColors(
contentColor = MaterialTheme.colorScheme.error
@@ -44,7 +44,7 @@ import com.freeturn.app.domain.proxy.ProxyEngine
import com.freeturn.app.data.server.Server
import com.freeturn.app.domain.server.ServerCommand
import com.freeturn.app.domain.server.ServerStartOptions
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.SettingsBackButton
import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.ui.components.SettingsGroup
@@ -53,6 +53,7 @@ import com.freeturn.app.ui.components.SettingsSwitchRow
import com.freeturn.app.ui.util.redact
import com.freeturn.app.viewmodel.server.ServerHubState
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import com.freeturn.app.ui.theme.Spacing
import org.koin.compose.koinInject
@@ -64,11 +65,12 @@ private fun versionLabel(version: String): String = "v${version.removePrefix("v"
fun NerdScreen(
serverId: String,
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
serverViewModel: ServerViewModel,
onBack: () -> Unit
) {
val context = LocalContext.current
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val snapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val coreStatus by serverViewModel.hubState.collectAsStateWithLifecycle()
val sshLog by serverViewModel.sshLog.collectAsStateWithLifecycle()
@@ -118,10 +120,10 @@ fun NerdScreen(
sshLog = sshLog,
logsLoading = logsLoading,
onDebugModeChange = { v ->
settingsViewModel.updateServerClient(serverId) { it.copy(debugMode = v) }
serverConfigViewModel.updateServerClient(serverId) { it.copy(debugMode = v) }
},
onLogsEnabledChange = { v ->
settingsViewModel.updateServerClient(serverId) { it.copy(logsEnabled = v) }
serverConfigViewModel.updateServerClient(serverId) { it.copy(logsEnabled = v) }
},
onFetchJournal = {
HapticUtil.perform(context, HapticUtil.Pattern.CLICK)
@@ -35,6 +35,7 @@ import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.ui.components.SettingsGroup
import com.freeturn.app.ui.components.settingsItemShape
import com.freeturn.app.ui.util.redact
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import com.freeturn.app.ui.theme.Spacing
@@ -42,10 +43,11 @@ import com.freeturn.app.ui.theme.Spacing
@Composable
fun ServersListScreen(
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
onBack: () -> Unit,
onOpenServer: (String) -> Unit
) {
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val snapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()
val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle()
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
@@ -70,7 +70,7 @@ import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.SettingsBackButton
import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.ui.theme.LocalReducedMotion
@@ -44,7 +44,7 @@ import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.config.AccessProtocol
import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.components.SettingsCard
import com.freeturn.app.ui.components.SettingsEntryRow
@@ -45,7 +45,7 @@ import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.BusyProgressIndicator
import com.freeturn.app.ui.components.InlineErrorCard
import com.freeturn.app.ui.theme.LocalReducedMotion
@@ -56,7 +56,7 @@ import androidx.lifecycle.LifecycleEventObserver
import com.freeturn.app.R
import com.freeturn.app.data.share.FreeturnLink
import com.freeturn.app.domain.share.LinkImportBus
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
@@ -25,7 +25,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import com.freeturn.app.R
import com.freeturn.app.data.server.Server
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.SettingsCard
import com.freeturn.app.ui.components.SettingsRowIcon
import com.freeturn.app.ui.util.hapticClickable
@@ -26,7 +26,7 @@ import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.data.config.ClientId
import com.freeturn.app.ui.components.SectionLabel
import com.freeturn.app.ui.theme.LocalReducedMotion
@@ -46,7 +46,7 @@ import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.share.ShareInfo
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.ProtocolPills
import com.freeturn.app.ui.components.QrCode
import com.freeturn.app.ui.theme.LocalReducedMotion
@@ -50,7 +50,7 @@ import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.EmptyState
import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.ui.theme.LocalReducedMotion
@@ -20,7 +20,7 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import com.freeturn.app.R
import com.freeturn.app.data.config.SplitTunnelMode
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
/** Выбор режима split-tunnel: include / exclude. */
@Composable
@@ -39,7 +39,7 @@ import androidx.compose.ui.unit.dp
import com.freeturn.app.R
import com.freeturn.app.data.config.SplitTunnelMode
import com.freeturn.app.data.config.splitTunnelSelection
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.data.AppChoice
import com.freeturn.app.data.installedInternetApps
import com.freeturn.app.ui.components.EmptyState
@@ -52,25 +52,25 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.freeturn.app.R
import com.freeturn.app.data.config.SshConfig
import com.freeturn.app.domain.SshConnectionState
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.ui.util.HapticUtil
import com.freeturn.app.ui.components.InlineErrorCard
import com.freeturn.app.ui.components.SettingsContentMaxWidth
import com.freeturn.app.ui.components.SshFormFields
import com.freeturn.app.ui.theme.LocalReducedMotion
import com.freeturn.app.ui.theme.Spacing
import com.freeturn.app.viewmodel.server.ServerViewModel
import com.freeturn.app.viewmodel.settings.SettingsViewModel
import com.freeturn.app.viewmodel.server.ServerConfigViewModel
@Composable
fun SshSetupScreen(
serverViewModel: ServerViewModel,
settingsViewModel: SettingsViewModel,
serverConfigViewModel: ServerConfigViewModel,
onConnected: () -> Unit,
onBack: () -> Unit
) {
// Экран не сервер-скоупный (правит активный SSH). Все серверы удалены, пока экран
// висел в стеке вкладки - выходим назад: иначе форма пишет в осиротевший конфиг.
val snapshot by settingsViewModel.serversSnapshot.collectAsStateWithLifecycle()
val snapshot by serverConfigViewModel.serversSnapshot.collectAsStateWithLifecycle()
if (snapshot.loaded && snapshot.list.isEmpty()) {
LaunchedEffect(Unit) { onBack() }
return
@@ -4,7 +4,6 @@ import androidx.compose.foundation.clickable
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import com.freeturn.app.data.HapticUtil
/**
* Кликабельность с тактильным откликом. Унифицирует haptic feedback для всех
@@ -1,4 +1,4 @@
package com.freeturn.app.data
package com.freeturn.app.ui.util
import android.content.Context
import android.media.AudioAttributes
@@ -8,6 +8,8 @@ import android.os.VibrationEffect
import android.os.Vibrator
import android.provider.Settings
import androidx.annotation.RequiresApi
import com.freeturn.app.viewmodel.HapticEvent
import com.freeturn.app.viewmodel.Haptics
object HapticUtil {
@@ -116,3 +118,14 @@ object HapticUtil {
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
}
class AndroidHaptics(private val context: Context) : Haptics {
override fun perform(event: HapticEvent) = HapticUtil.perform(
context,
when (event) {
HapticEvent.SUCCESS -> HapticUtil.Pattern.SUCCESS
HapticEvent.ERROR -> HapticUtil.Pattern.ERROR
HapticEvent.STEP -> HapticUtil.Pattern.SELECTION
}
)
}
@@ -0,0 +1,7 @@
package com.freeturn.app.viewmodel
enum class HapticEvent { SUCCESS, ERROR, STEP }
fun interface Haptics {
fun perform(event: HapticEvent)
}
@@ -0,0 +1,216 @@
package com.freeturn.app.viewmodel.server
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.config.ClientConfig
import com.freeturn.app.data.config.KcpProfile
import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.control.UninstallData
import com.freeturn.app.data.server.Server
import com.freeturn.app.data.server.ServerOpts
import com.freeturn.app.data.server.ServersSnapshot
import com.freeturn.app.domain.proxy.ProxyOrchestrator
import com.freeturn.app.domain.server.ServerSetupRepository
import com.freeturn.app.viewmodel.uiError
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
sealed interface ServerCleanupState {
data object Idle : ServerCleanupState
data object Running : ServerCleanupState
data class Done(val data: UninstallData) : ServerCleanupState
data class Error(val message: String) : ServerCleanupState
}
/**
* Список серверов и их сохранённый конфиг: CRUD, правки клиента и серверных опций,
* снос с VPS. Живая SSH-сессия активного сервера - в [ServerViewModel].
*/
class ServerConfigViewModel(
private val prefs: AppPreferences,
private val orchestrator: ProxyOrchestrator,
private val serverSetup: ServerSetupRepository,
context: Context
) : ViewModel() {
private val appContext = context.applicationContext
val serversSnapshot: StateFlow<ServersSnapshot> = prefs.serversSnapshot
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ServersSnapshot())
val clientConfig: StateFlow<ClientConfig> = prefs.clientConfigFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ClientConfig())
val proxyListen: StateFlow<String> = prefs.proxyListenFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "0.0.0.0:56000")
val proxyConnect: StateFlow<String> = prefs.proxyConnectFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "127.0.0.1:40537")
private val _cleanupState = MutableStateFlow<ServerCleanupState>(ServerCleanupState.Idle)
val cleanupState: StateFlow<ServerCleanupState> = _cleanupState.asStateFlow()
// Ручной сервер создаётся неактивным и с sync OFF, чтобы его можно было донастроить без SSH.
fun addManualServer(name: String, onAdded: (String) -> Unit) {
viewModelScope.launch {
val server = Server(name = name, client = ClientConfig(syncServerSwitches = false))
onAdded(prefs.addServer(server))
}
}
fun renameServer(id: String, name: String) {
viewModelScope.launch { prefs.renameServer(id, name) }
}
fun cloneServer(id: String, onCloned: (String) -> Unit) {
viewModelScope.launch { prefs.cloneServer(id)?.let(onCloned) }
}
fun deleteServer(id: String) {
viewModelScope.launch { prefs.deleteServer(id) }
}
fun applyServer(id: String) {
viewModelScope.launch {
val target = prefs.serversSnapshot.first().list.firstOrNull { it.id == id }
?: return@launch
prefs.setActiveServerId(target.id)
orchestrator.onActiveServerChanged(target)
}
}
fun resetCleanupState() {
_cleanupState.value = ServerCleanupState.Idle
}
fun cleanupServer(id: String) {
viewModelScope.launch {
val cfg = serversSnapshot.value.list.firstOrNull { it.id == id }?.ssh ?: return@launch
_cleanupState.value = ServerCleanupState.Running
// Перед удалением обновляем rootMode: сохранённое значение могло устареть.
val mode = serverSetup.detectRootMode(cfg) ?: cfg.rootMode
serverSetup.uninstall(cfg.copy(rootMode = mode), withWgPkg = true)
.onSuccess { _cleanupState.value = ServerCleanupState.Done(it) }
.onFailure { _cleanupState.value = ServerCleanupState.Error(it.uiError(appContext)) }
}
}
fun updateServerClient(id: String, transform: (ClientConfig) -> ClientConfig) {
viewModelScope.launch {
prefs.updateServer(id) { it.copy(client = transform(it.client)) }
}
}
private fun updateActiveClient(transform: (ClientConfig) -> ClientConfig) {
viewModelScope.launch {
prefs.updateActiveServer { it.copy(client = transform(it.client)) }
}
}
fun setActiveVkLink(link: String) = updateActiveClient { it.copy(vkLink = link.trim()) }
fun setSplitTunnelMode(value: String) = updateActiveClient { it.copy(splitTunnelMode = value) }
fun setSplitTunnelApps(value: String) =
updateActiveClient { it.copy(splitTunnelApps = value.trim()) }
fun setSyncServerSwitches(enabled: Boolean) {
viewModelScope.launch {
val changed = prefs.updateActiveServer {
it.copy(client = it.client.copy(syncServerSwitches = enabled))
}
if (changed) orchestrator.scheduleSync()
}
}
fun setProxyMode(id: String?, mode: String) = updateOpts(id) { it.copy(proxyMode = mode) }
/** Режим и ARQ одной транзакцией: рестарт пары идёт один раз на "Применить". */
fun applyForwardConfig(id: String?, mode: String, kcp: KcpProfile) =
updateOpts(id) { it.copy(proxyMode = mode, kcp = kcp) }
/**
* Режим и ARQ обязаны совпадать с сервером, поэтому правка активного сервера
* тянет за собой рестарт обеих сторон - как в apply-модели экрана сервера.
*/
private fun updateOpts(id: String?, transform: (ServerOpts) -> ServerOpts) {
viewModelScope.launch {
val changed = if (id == null) {
prefs.updateActiveServer { it.copy(opts = transform(it.opts)) }
} else {
prefs.updateServer(id) { it.copy(opts = transform(it.opts)) }
}
if (!changed) return@launch
if (id != null && id != prefs.serversSnapshot.first().activeId) return@launch
orchestrator.scheduleSync()
}
}
// Одна транзакция и один рестарт сохраняют атомарность apply-модели.
fun applyServerConfig(
listen: String,
connect: String,
proxyMode: String,
obfProfile: String,
obfKey: String,
obfTimingMs: Int
) {
viewModelScope.launch {
val sync = prefs.clientConfigFlow.first().syncServerSwitches
val changed = prefs.updateActiveServer {
it.withServerConfig(listen, connect, proxyMode, obfProfile, obfKey, obfTimingMs)
}
if (changed) orchestrator.restartPair(syncServer = sync)
}
}
// Неактивный сервер обновляется без вмешательства в рантайм активного.
fun updateServerConfig(
id: String,
listen: String,
connect: String,
proxyMode: String,
obfProfile: String,
obfKey: String,
obfTimingMs: Int
) {
viewModelScope.launch {
prefs.updateServer(id) {
it.withServerConfig(listen, connect, proxyMode, obfProfile, obfKey, obfTimingMs)
}
}
}
}
/** Пустой ключ при включённой обфускации - сохранённый, а без него свежий. */
private fun Server.withServerConfig(
listen: String,
connect: String,
proxyMode: String,
obfProfile: String,
obfKey: String,
obfTimingMs: Int
): Server {
val key = obfKey.trim().ifBlank {
opts.obfKey.ifBlank {
if (obfProfile != ObfProfile.NONE) ObfProfile.generateKey() else ""
}
}
return copy(
proxyListen = listen,
proxyConnect = connect,
opts = opts.copy(
proxyMode = proxyMode,
obfProfile = obfProfile,
obfKey = key,
obfTimingMs = obfTimingMs
)
)
}
@@ -14,7 +14,8 @@ import com.freeturn.app.data.config.TunnelTransport
import com.freeturn.app.domain.proxy.ProxyOrchestrator
import com.freeturn.app.domain.server.ServerSetupRepository
import com.freeturn.app.domain.server.ServerStartOptions
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.viewmodel.HapticEvent
import com.freeturn.app.viewmodel.Haptics
import com.freeturn.app.viewmodel.uiError
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
@@ -137,6 +138,7 @@ class ServerSetupViewModel(
private val repo: ServerSetupRepository,
private val prefs: AppPreferences,
private val orchestrator: ProxyOrchestrator,
private val haptics: Haptics,
context: Context
) : ViewModel() {
@@ -195,7 +197,7 @@ class ServerSetupViewModel(
val ip = s.ssh.ip.trim()
val duplicate = prefs.serversSnapshot.first().list
.any { it.ssh.ip.isNotBlank() && it.ssh.ip.equals(ip, ignoreCase = true) }
HapticUtil.perform(appContext, HapticUtil.Pattern.SUCCESS)
haptics.perform(HapticEvent.SUCCESS)
_uiState.update {
it.copy(
checkingSsh = false,
@@ -212,7 +214,7 @@ class ServerSetupViewModel(
}
}
.onFailure { e ->
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
haptics.perform(HapticEvent.ERROR)
_uiState.update {
it.copy(checkingSsh = false, sshError = e.uiError(appContext))
}
@@ -247,12 +249,12 @@ class ServerSetupViewModel(
}
val st = _uiState.value.install
if (st != null && st.current < st.tasks.size) {
HapticUtil.perform(appContext, HapticUtil.Pattern.SELECTION)
haptics.perform(HapticEvent.STEP)
}
}
private fun fail(message: String?) {
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
haptics.perform(HapticEvent.ERROR)
_uiState.update { s ->
s.copy(install = s.install?.copy(error = message ?: "unknown error"))
}
@@ -315,7 +317,7 @@ class ServerSetupViewModel(
}
advance()
HapticUtil.perform(appContext, HapticUtil.Pattern.SUCCESS)
haptics.perform(HapticEvent.SUCCESS)
_uiState.update { st ->
st.copy(
install = st.install?.copy(
@@ -0,0 +1,105 @@
package com.freeturn.app.viewmodel.settings
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.backup.BackupCrypto
import com.freeturn.app.domain.backup.BackupManager
import com.freeturn.app.domain.proxy.ProxyServiceLauncher
import com.freeturn.app.domain.proxy.ProxyStore
import com.freeturn.app.domain.ssh.SshRepository
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
enum class RestoreFailReason { BAD_PASSWORD, BAD_FILE, IO }
sealed interface BackupEvent {
data object ExportSuccess : BackupEvent
data object ExportFailed : BackupEvent
data class RestoreSuccess(val count: Int) : BackupEvent
data class RestoreFailed(val reason: RestoreFailReason) : BackupEvent
}
/** Профиль целиком: экспорт/восстановление зашифрованного бэкапа и полный сброс. */
class BackupViewModel(
private val prefs: AppPreferences,
private val proxyLauncher: ProxyServiceLauncher,
private val sshRepository: SshRepository,
private val backupManager: BackupManager,
context: Context
) : ViewModel() {
private val appContext = context.applicationContext
private val _events = Channel<BackupEvent>(Channel.BUFFERED)
val events: Flow<BackupEvent> = _events.receiveAsFlow()
fun exportBackup(uri: Uri, password: String) {
viewModelScope.launch {
val event = try {
val bytes = backupManager.export(password)
withContext(Dispatchers.IO) {
appContext.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
?: throw IOException("no output stream")
}
BackupEvent.ExportSuccess
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
BackupEvent.ExportFailed
}
_events.send(event)
}
}
fun restoreBackup(uri: Uri, password: String) {
viewModelScope.launch {
val event = try {
val bytes = withContext(Dispatchers.IO) {
appContext.contentResolver.openInputStream(uri)?.use { it.readBytes() }
?: throw IOException("no input stream")
}
val data = backupManager.decode(bytes, password)
proxyLauncher.stop()
val count = backupManager.restore(data)
sshRepository.resetAll()
ProxyStore.clearLogs()
BackupEvent.RestoreSuccess(count)
} catch (e: CancellationException) {
throw e
} catch (_: BackupCrypto.BadPasswordException) {
BackupEvent.RestoreFailed(RestoreFailReason.BAD_PASSWORD)
} catch (_: BackupCrypto.FormatException) {
BackupEvent.RestoreFailed(RestoreFailReason.BAD_FILE)
} catch (_: Exception) {
BackupEvent.RestoreFailed(RestoreFailReason.IO)
}
_events.send(event)
}
}
fun resetAllSettings() {
viewModelScope.launch {
proxyLauncher.stop()
prefs.resetAll()
sshRepository.resetAll()
ProxyStore.clearLogs()
val intent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
appContext.startActivity(intent)
}
}
}
}
@@ -1,80 +1,42 @@
package com.freeturn.app.viewmodel.settings
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences
import com.freeturn.app.data.backup.BackupCrypto
import com.freeturn.app.data.config.ClientConfig
import com.freeturn.app.data.config.KcpProfile
import com.freeturn.app.data.config.ObfProfile
import com.freeturn.app.data.control.UninstallData
import com.freeturn.app.data.server.Server
import com.freeturn.app.data.server.ServerOpts
import com.freeturn.app.data.server.ServersSnapshot
import com.freeturn.app.domain.backup.BackupManager
import com.freeturn.app.domain.update.AppUpdater
import com.freeturn.app.domain.proxy.ProxyServiceLauncher
import com.freeturn.app.domain.proxy.ProxyOrchestrator
import com.freeturn.app.domain.server.ServerSetupRepository
import com.freeturn.app.domain.ssh.SshRepository
import com.freeturn.app.viewmodel.uiError
import com.freeturn.app.domain.UpdateState
import com.freeturn.app.domain.proxy.ProxyStore
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.flow.MutableSharedFlow
import com.freeturn.app.domain.update.AppUpdater
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.io.IOException
sealed interface ServerCleanupState {
data object Idle : ServerCleanupState
data object Running : ServerCleanupState
data class Done(val data: UninstallData) : ServerCleanupState
data class Error(val message: String) : ServerCleanupState
}
/**
* Настройки самого приложения и его обновления. Серверы - [com.freeturn.app.viewmodel.server.ServerConfigViewModel],
* бэкап и сброс - [BackupViewModel].
*/
class SettingsViewModel(
private val prefs: AppPreferences,
private val proxyLauncher: ProxyServiceLauncher,
private val sshRepository: SshRepository,
private val serverSetup: ServerSetupRepository,
private val appUpdater: AppUpdater,
private val orchestrator: ProxyOrchestrator,
private val backupManager: BackupManager,
context: Context
private val appUpdater: AppUpdater
) : ViewModel() {
private val appContext = context.applicationContext
// Стартовые значения - те же, что дефолты AppPreferences: иначе тумблер моргает
// до первой эмиссии DataStore.
private fun <T> Flow<T>.state(initial: T): StateFlow<T> =
stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial)
val clientConfig: StateFlow<ClientConfig> = prefs.clientConfigFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ClientConfig())
val proxyListen: StateFlow<String> = prefs.proxyListenFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "0.0.0.0:56000")
val proxyConnect: StateFlow<String> = prefs.proxyConnectFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "127.0.0.1:40537")
val dynamicTheme: StateFlow<Boolean> = prefs.dynamicThemeFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), true)
val nerdMode: StateFlow<Boolean> = prefs.nerdModeFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val serversSnapshot: StateFlow<ServersSnapshot> = prefs.serversSnapshot
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ServersSnapshot())
val dynamicTheme: StateFlow<Boolean> = prefs.dynamicThemeFlow.state(true)
val nerdMode: StateFlow<Boolean> = prefs.nerdModeFlow.state(true)
val privacyMode: StateFlow<Boolean> = prefs.privacyModeFlow.state(false)
val seasonalDecor: StateFlow<Boolean> = prefs.seasonalDecorFlow.state(true)
val autoConnect: StateFlow<Boolean> = prefs.autoConnectFlow.state(false)
val restartServerOnSwitch: StateFlow<Boolean> = prefs.restartServerOnSwitchFlow.state(false)
val hotspotProxyEnabled: StateFlow<Boolean> = prefs.hotspotProxyEnabledFlow.state(false)
val suppressUpdatePrompt: StateFlow<Boolean> = prefs.suppressUpdatePromptFlow.state(false)
val suppressTgPrompt: StateFlow<Boolean> = prefs.suppressTgPromptFlow.state(false)
val updateState: StateFlow<UpdateState> = appUpdater.state
@@ -88,27 +50,6 @@ class SettingsViewModel(
private val _initialSuppressTgPrompt = MutableStateFlow(false)
val initialSuppressTgPrompt: StateFlow<Boolean> = _initialSuppressTgPrompt.asStateFlow()
val suppressUpdatePrompt: StateFlow<Boolean> = prefs.suppressUpdatePromptFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val suppressTgPrompt: StateFlow<Boolean> = prefs.suppressTgPromptFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val autoConnect: StateFlow<Boolean> = prefs.autoConnectFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val privacyMode: StateFlow<Boolean> = prefs.privacyModeFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val seasonalDecor: StateFlow<Boolean> = prefs.seasonalDecorFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), true)
val restartServerOnSwitch: StateFlow<Boolean> = prefs.restartServerOnSwitchFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
val hotspotProxyEnabled: StateFlow<Boolean> = prefs.hotspotProxyEnabledFlow
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)
// Ожидаем DataStore, чтобы дефолт StateFlow не пропустил диалог первой сессии.
suspend fun batteryPromptShownOnce(): Boolean = prefs.batteryPromptShownFlow.first()
@@ -116,7 +57,6 @@ class SettingsViewModel(
viewModelScope.launch {
_initialTgSubscribeShown.value = prefs.tgSubscribeShownFlow.first()
_initialSuppressTgPrompt.value = prefs.suppressTgPromptFlow.first()
ProxyStore.setLogsEnabled(prefs.clientConfigFlow.first().logsEnabled)
_isInitialized.value = true
}
viewModelScope.launch {
@@ -169,184 +109,6 @@ class SettingsViewModel(
viewModelScope.launch { prefs.setAutoConnect(enabled) }
}
fun setSplitTunnelMode(value: String) {
viewModelScope.launch {
prefs.updateActiveServer {
it.copy(client = it.client.copy(splitTunnelMode = value))
}
}
}
fun setSplitTunnelApps(value: String) {
viewModelScope.launch {
val trimmed = value.trim()
prefs.updateActiveServer {
it.copy(client = it.client.copy(splitTunnelApps = trimmed))
}
}
}
// Ручной сервер создаётся неактивным и с sync OFF, чтобы его можно было донастроить без SSH.
fun addManualServer(name: String, onAdded: (String) -> Unit) {
viewModelScope.launch {
val server = Server(name = name, client = ClientConfig(syncServerSwitches = false))
onAdded(prefs.addServer(server))
}
}
fun renameServer(id: String, name: String) {
viewModelScope.launch { prefs.renameServer(id, name) }
}
fun cloneServer(id: String, onCloned: (String) -> Unit) {
viewModelScope.launch { prefs.cloneServer(id)?.let(onCloned) }
}
fun applyServer(id: String) {
viewModelScope.launch {
val target = prefs.serversSnapshot.first().list.firstOrNull { it.id == id }
?: return@launch
prefs.setActiveServerId(target.id)
orchestrator.onActiveServerChanged(target)
}
}
private val _cleanupState = MutableStateFlow<ServerCleanupState>(ServerCleanupState.Idle)
val cleanupState: StateFlow<ServerCleanupState> = _cleanupState.asStateFlow()
fun resetCleanupState() { _cleanupState.value = ServerCleanupState.Idle }
fun deleteServer(id: String) {
viewModelScope.launch { prefs.deleteServer(id) }
}
fun cleanupServer(id: String) {
viewModelScope.launch {
val cfg = serversSnapshot.value.list.firstOrNull { it.id == id }?.ssh ?: return@launch
_cleanupState.value = ServerCleanupState.Running
// Перед удалением обновляем rootMode: сохранённое значение могло устареть.
val mode = serverSetup.detectRootMode(cfg) ?: cfg.rootMode
serverSetup.uninstall(cfg.copy(rootMode = mode), withWgPkg = true)
.onSuccess { _cleanupState.value = ServerCleanupState.Done(it) }
.onFailure { _cleanupState.value = ServerCleanupState.Error(it.uiError(appContext)) }
}
}
fun updateServerClient(id: String, transform: (ClientConfig) -> ClientConfig) {
viewModelScope.launch {
if (!prefs.updateServer(id) { it.copy(client = transform(it.client)) }) return@launch
val snap = prefs.serversSnapshot.first()
snap.active?.takeIf { it.id == id }?.let {
ProxyStore.setLogsEnabled(it.client.logsEnabled)
}
}
}
fun setActiveVkLink(link: String) {
viewModelScope.launch {
prefs.updateActiveServer {
it.copy(client = it.client.copy(vkLink = link.trim()))
}
}
}
fun setSyncServerSwitches(enabled: Boolean) {
viewModelScope.launch {
val changed = prefs.updateActiveServer {
it.copy(client = it.client.copy(syncServerSwitches = enabled))
}
if (!changed) return@launch
orchestrator.scheduleSync()
}
}
fun setProxyMode(id: String?, mode: String) = updateOpts(id) { it.copy(proxyMode = mode) }
/** Режим и ARQ одной транзакцией: рестарт пары идёт один раз на "Применить". */
fun applyForwardConfig(id: String?, mode: String, kcp: KcpProfile) =
updateOpts(id) { it.copy(proxyMode = mode, kcp = kcp) }
/**
* Режим и ARQ обязаны совпадать с сервером, поэтому правка активного сервера
* тянет за собой рестарт обеих сторон - как в apply-модели экрана сервера.
*/
private fun updateOpts(id: String?, transform: (ServerOpts) -> ServerOpts) {
viewModelScope.launch {
val changed = if (id == null) {
prefs.updateActiveServer { it.copy(opts = transform(it.opts)) }
} else {
prefs.updateServer(id) { it.copy(opts = transform(it.opts)) }
}
if (!changed) return@launch
if (id != null && id != prefs.serversSnapshot.first().activeId) return@launch
orchestrator.scheduleSync()
}
}
// Одна транзакция и один рестарт сохраняют атомарность apply-модели.
fun applyServerConfig(
listen: String,
connect: String,
proxyMode: String,
obfProfile: String,
obfKey: String,
obfTimingMs: Int
) {
viewModelScope.launch {
val sync = prefs.clientConfigFlow.first().syncServerSwitches
val trimmedKey = obfKey.trim()
val changed = prefs.updateActiveServer { s ->
val effKey = trimmedKey.ifBlank {
s.opts.obfKey.ifBlank {
if (obfProfile != ObfProfile.NONE) ObfProfile.generateKey() else ""
}
}
s.copy(
proxyListen = listen,
proxyConnect = connect,
opts = s.opts.copy(
proxyMode = proxyMode,
obfProfile = obfProfile,
obfKey = effKey,
obfTimingMs = obfTimingMs
)
)
}
if (changed) orchestrator.restartPair(syncServer = sync)
}
}
// Неактивный сервер обновляется без вмешательства в рантайм активного.
fun updateServerConfig(
id: String,
listen: String,
connect: String,
proxyMode: String,
obfProfile: String,
obfKey: String,
obfTimingMs: Int
) {
viewModelScope.launch {
prefs.updateServer(id) { target ->
val effKey = obfKey.trim().ifBlank {
target.opts.obfKey.ifBlank {
if (obfProfile != ObfProfile.NONE) ObfProfile.generateKey() else ""
}
}
target.copy(
proxyListen = listen,
proxyConnect = connect,
opts = target.opts.copy(
proxyMode = proxyMode,
obfProfile = obfProfile,
obfKey = effKey,
obfTimingMs = obfTimingMs
)
)
}
}
}
fun checkForUpdate() {
viewModelScope.launch { appUpdater.checkForUpdate(silent = false) }
}
@@ -362,77 +124,4 @@ class SettingsViewModel(
fun resetUpdateState() {
appUpdater.resetState()
}
// Буфер сохраняет событие, пока экран не подписан.
private val _backupEvents = MutableSharedFlow<BackupEvent>(extraBufferCapacity = 1)
val backupEvents: SharedFlow<BackupEvent> = _backupEvents.asSharedFlow()
fun exportBackup(uri: Uri, password: String) {
viewModelScope.launch {
val event = try {
val bytes = backupManager.export(password)
withContext(Dispatchers.IO) {
appContext.contentResolver.openOutputStream(uri)?.use { it.write(bytes) }
?: throw IOException("no output stream")
}
BackupEvent.ExportSuccess
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
BackupEvent.ExportFailed
}
_backupEvents.emit(event)
}
}
fun restoreBackup(uri: Uri, password: String) {
viewModelScope.launch {
val event = try {
val bytes = withContext(Dispatchers.IO) {
appContext.contentResolver.openInputStream(uri)?.use { it.readBytes() }
?: throw IOException("no input stream")
}
// Разбор до остановки рантайма: неверный пароль не должен гасить подключение.
val data = backupManager.decode(bytes, password)
proxyLauncher.stop()
val count = backupManager.restore(data)
sshRepository.resetAll()
ProxyStore.clearLogs()
BackupEvent.RestoreSuccess(count)
} catch (e: CancellationException) {
throw e
} catch (_: BackupCrypto.BadPasswordException) {
BackupEvent.RestoreFailed(RestoreFailReason.BAD_PASSWORD)
} catch (_: BackupCrypto.FormatException) {
BackupEvent.RestoreFailed(RestoreFailReason.BAD_FILE)
} catch (_: Exception) {
BackupEvent.RestoreFailed(RestoreFailReason.IO)
}
_backupEvents.emit(event)
}
}
fun resetAllSettings() {
viewModelScope.launch {
proxyLauncher.stop()
prefs.resetAll()
sshRepository.resetAll()
ProxyStore.clearLogs()
val intent = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
appContext.startActivity(intent)
}
}
}
}
enum class RestoreFailReason { BAD_PASSWORD, BAD_FILE, IO }
sealed interface BackupEvent {
data object ExportSuccess : BackupEvent
data object ExportFailed : BackupEvent
data class RestoreSuccess(val count: Int) : BackupEvent
data class RestoreFailed(val reason: RestoreFailReason) : BackupEvent
}
@@ -1,6 +1,5 @@
package com.freeturn.app.viewmodel.share
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freeturn.app.data.AppPreferences
@@ -17,7 +16,8 @@ import com.freeturn.app.data.config.SshConfig
import com.freeturn.app.data.config.TunnelTransport
import com.freeturn.app.data.share.FreeturnLink
import com.freeturn.app.domain.share.LinkImportBus
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.viewmodel.HapticEvent
import com.freeturn.app.viewmodel.Haptics
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
@@ -46,11 +46,9 @@ data class ImportUiState(
class ImportViewModel(
private val prefs: AppPreferences,
bus: LinkImportBus,
context: Context
private val haptics: Haptics
) : ViewModel() {
private val appContext = context.applicationContext
private val _uiState = MutableStateFlow(ImportUiState())
val uiState: StateFlow<ImportUiState> = _uiState.asStateFlow()
@@ -82,7 +80,7 @@ class ImportViewModel(
)
},
onFailure = {
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
haptics.perform(HapticEvent.ERROR)
_uiState.value = ImportUiState(parseError = true)
}
)
@@ -103,11 +101,11 @@ class ImportViewModel(
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
haptics.perform(HapticEvent.ERROR)
_uiState.update { it.copy(saving = false, saveError = true) }
return@launch
}
HapticUtil.perform(appContext, HapticUtil.Pattern.SUCCESS)
haptics.perform(HapticEvent.SUCCESS)
_uiState.update { it.copy(saving = false, saved = true) }
}
}
@@ -13,7 +13,8 @@ import com.freeturn.app.data.share.ShareLinkBuilder
import com.freeturn.app.data.share.SharedClient
import com.freeturn.app.data.share.WgPeer
import com.freeturn.app.domain.share.ShareRepository
import com.freeturn.app.data.HapticUtil
import com.freeturn.app.viewmodel.HapticEvent
import com.freeturn.app.viewmodel.Haptics
import com.freeturn.app.viewmodel.uiError
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -79,6 +80,7 @@ data class ShareUiState(
class ShareViewModel(
private val repo: ShareRepository,
private val prefs: AppPreferences,
private val haptics: Haptics,
context: Context
) : ViewModel() {
@@ -297,7 +299,7 @@ class ShareViewModel(
newPeer: WgPeer? = null,
newClient: SharedClient? = null
) {
HapticUtil.perform(appContext, HapticUtil.Pattern.SUCCESS)
haptics.perform(HapticEvent.SUCCESS)
_uiState.update { cur ->
val appendable = cur.selectedServerId == serverId && cur.peersLoaded
cur.copy(
@@ -311,7 +313,7 @@ class ShareViewModel(
}
private fun commitCreateError(e: Throwable) {
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
haptics.perform(HapticEvent.ERROR)
_uiState.update { it.copy(creating = false, createError = e.uiError(appContext)) }
}
@@ -372,7 +374,7 @@ class ShareViewModel(
}
}
.onFailure { e ->
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
haptics.perform(HapticEvent.ERROR)
_uiState.update {
it.copy(resharePubkey = null, peersError = e.uiError(appContext))
}
@@ -420,7 +422,7 @@ class ShareViewModel(
else repo.removeClient(server.ssh, target.clientId.orEmpty())
result
.onSuccess {
HapticUtil.perform(appContext, HapticUtil.Pattern.SUCCESS)
haptics.perform(HapticEvent.SUCCESS)
_uiState.update {
it.copy(
revoking = false,
@@ -431,7 +433,7 @@ class ShareViewModel(
}
}
.onFailure { e ->
HapticUtil.perform(appContext, HapticUtil.Pattern.ERROR)
haptics.perform(HapticEvent.ERROR)
_uiState.update {
it.copy(
revoking = false,