From a22b6b6930f54d4ce2a444396de4b14915c77040 Mon Sep 17 00:00:00 2001 From: samosvalishe Date: Mon, 1 Jun 2026 15:04:54 +0300 Subject: [PATCH] =?UTF-8?q?refactor:=20=D1=80=D0=B0=D0=B7=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20MainViewModel=20=D0=BD=D0=B0?= =?UTF-8?q?=20=D1=81=D0=BF=D0=B5=D1=86=D0=B8=D0=B0=D0=BB=D0=B8=D0=B7=D0=B8?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=BD=D1=8B=D0=B5=20SettingsView?= =?UTF-8?q?Model=20ProxyViewModel=20=D0=B8=20ServerViewModel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/freeturn/app/MainActivity.kt | 12 +- .../freeturn/app/domain/LocalProxyManager.kt | 18 +- .../app/ui/navigation/AppNavigation.kt | 59 +- .../app/ui/screens/ClientSetupScreen.kt | 4 +- .../com/freeturn/app/ui/screens/HomeScreen.kt | 67 +- .../com/freeturn/app/ui/screens/LogsScreen.kt | 8 +- .../freeturn/app/ui/screens/ProfilesScreen.kt | 14 +- .../app/ui/screens/ServerManagementScreen.kt | 42 +- .../freeturn/app/ui/screens/SshSetupScreen.kt | 11 +- .../freeturn/app/viewmodel/MainViewModel.kt | 611 ------------------ .../freeturn/app/viewmodel/ProxyViewModel.kt | 49 ++ .../freeturn/app/viewmodel/ServerViewModel.kt | 171 +++++ .../app/viewmodel/SettingsViewModel.kt | 398 ++++++++++++ 13 files changed, 753 insertions(+), 711 deletions(-) delete mode 100644 app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt create mode 100644 app/src/main/java/com/freeturn/app/viewmodel/ProxyViewModel.kt create mode 100644 app/src/main/java/com/freeturn/app/viewmodel/ServerViewModel.kt create mode 100644 app/src/main/java/com/freeturn/app/viewmodel/SettingsViewModel.kt diff --git a/app/src/main/java/com/freeturn/app/MainActivity.kt b/app/src/main/java/com/freeturn/app/MainActivity.kt index 3d30716..01dc924 100644 --- a/app/src/main/java/com/freeturn/app/MainActivity.kt +++ b/app/src/main/java/com/freeturn/app/MainActivity.kt @@ -13,31 +13,31 @@ import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.freeturn.app.ui.HapticUtil import com.freeturn.app.ui.navigation.AppNavigation import com.freeturn.app.ui.theme.FreeTurnTheme -import com.freeturn.app.viewmodel.MainViewModel - +import org.koin.androidx.viewmodel.ext.android.viewModel +import com.freeturn.app.viewmodel.SettingsViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.runtime.getValue class MainActivity : ComponentActivity() { - private val viewModel: MainViewModel by viewModels() + private val settingsViewModel: SettingsViewModel by viewModel() override fun onCreate(savedInstanceState: Bundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) - splashScreen.setKeepOnScreenCondition { !viewModel.isInitialized.value } + splashScreen.setKeepOnScreenCondition { !settingsViewModel.isInitialized.value } HapticUtil.perform(this, HapticUtil.Pattern.LAUNCH) enableEdgeToEdge() setContent { - val dynamicTheme by viewModel.dynamicTheme.collectAsStateWithLifecycle() + val dynamicTheme by settingsViewModel.dynamicTheme.collectAsStateWithLifecycle() FreeTurnTheme(dynamicColor = dynamicTheme) { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { - AppNavigation(viewModel = viewModel) + AppNavigation() } } } diff --git a/app/src/main/java/com/freeturn/app/domain/LocalProxyManager.kt b/app/src/main/java/com/freeturn/app/domain/LocalProxyManager.kt index 4ffcae3..b55320e 100644 --- a/app/src/main/java/com/freeturn/app/domain/LocalProxyManager.kt +++ b/app/src/main/java/com/freeturn/app/domain/LocalProxyManager.kt @@ -30,13 +30,21 @@ class LocalProxyManager(private val context: Context) { private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob()) private var resetJob: kotlinx.coroutines.Job? = null - suspend fun observeProxyLifecycle() { + init { + scope.launch { observeProxyLifecycle() } + scope.launch { observeProxyServiceStatus() } + scope.launch { observeConnectionStats() } + scope.launch { observeCaptchaEvents() } + syncInitialState() + } + + private suspend fun observeProxyLifecycle() { ProxyServiceState.proxyFailed.collect { setErrorWithAutoReset("Прокси упал ${ProxyService.MAX_RESTARTS} раз — проверьте настройки") } } - suspend fun observeCaptchaEvents() { + private suspend fun observeCaptchaEvents() { ProxyServiceState.captchaSession.collect { session -> if (session != null) { _proxyState.value = ProxyState.CaptchaRequired(session.url, session.sessionId) @@ -51,7 +59,7 @@ class LocalProxyManager(private val context: Context) { } } - suspend fun observeProxyServiceStatus() { + private suspend fun observeProxyServiceStatus() { ProxyServiceState.isRunning.collect { running -> val current = _proxyState.value if (running) { @@ -79,7 +87,7 @@ class LocalProxyManager(private val context: Context) { * Captcha и Error имеют приоритет и не перезаписываются, пока активны. * Starting тоже не трогаем: он снимается StartupResult-логикой в startProxy. */ - suspend fun observeConnectionStats() { + private suspend fun observeConnectionStats() { ProxyServiceState.connectionStats.collect { stats -> val current = _proxyState.value if (current is ProxyState.Error || current is ProxyState.CaptchaRequired) return@collect @@ -96,7 +104,7 @@ class LocalProxyManager(private val context: Context) { } } - fun syncInitialState() { + private fun syncInitialState() { if (ProxyServiceState.isRunning.value) { val s = ProxyServiceState.connectionStats.value _proxyState.value = if (s.active > 0) { diff --git a/app/src/main/java/com/freeturn/app/ui/navigation/AppNavigation.kt b/app/src/main/java/com/freeturn/app/ui/navigation/AppNavigation.kt index 3c0ddc1..5c1a554 100644 --- a/app/src/main/java/com/freeturn/app/ui/navigation/AppNavigation.kt +++ b/app/src/main/java/com/freeturn/app/ui/navigation/AppNavigation.kt @@ -40,7 +40,10 @@ import com.freeturn.app.ui.screens.OnboardingScreen import com.freeturn.app.ui.screens.ServerManagementScreen import com.freeturn.app.ui.screens.SshSetupScreen import com.freeturn.app.viewmodel.ProxyState -import com.freeturn.app.viewmodel.MainViewModel +import com.freeturn.app.viewmodel.SettingsViewModel +import com.freeturn.app.viewmodel.ProxyViewModel +import com.freeturn.app.viewmodel.ServerViewModel +import org.koin.androidx.compose.koinViewModel object Routes { const val ONBOARDING = "onboarding" @@ -58,16 +61,20 @@ object Routes { private val BOTTOM_NAV_ROUTES = setOf(Routes.HOME, Routes.LOGS, Routes.SERVER_MANAGEMENT, Routes.CLIENT_SETUP) @Composable -fun AppNavigation(viewModel: MainViewModel) { - val isInitialized by viewModel.isInitialized.collectAsStateWithLifecycle() +fun AppNavigation( + settingsViewModel: SettingsViewModel = koinViewModel(), + proxyViewModel: ProxyViewModel = koinViewModel(), + serverViewModel: ServerViewModel = koinViewModel() +) { + val isInitialized by settingsViewModel.isInitialized.collectAsStateWithLifecycle() // Не строим NavHost пока DataStore не загружен — иначе startDestination // захватит дефолтный onboardingDone=false и всегда покажет онбординг if (!isInitialized) return - val proxyState by viewModel.proxyState.collectAsStateWithLifecycle() - val initialOnboardingDone by viewModel.initialOnboardingDone.collectAsStateWithLifecycle() - val initialTgSubscribeShown by viewModel.initialTgSubscribeShown.collectAsStateWithLifecycle() + val proxyState by proxyViewModel.proxyState.collectAsStateWithLifecycle() + val initialOnboardingDone by settingsViewModel.initialOnboardingDone.collectAsStateWithLifecycle() + val initialTgSubscribeShown by settingsViewModel.initialTgSubscribeShown.collectAsStateWithLifecycle() val startDestination = remember { if (initialOnboardingDone) Routes.HOME else Routes.ONBOARDING } val navController = rememberNavController() val backStackEntry by navController.currentBackStackEntryAsState() @@ -114,7 +121,9 @@ fun AppNavigation(viewModel: MainViewModel) { ) { AppNavHost( navController = navController, - viewModel = viewModel, + settingsViewModel = settingsViewModel, + proxyViewModel = proxyViewModel, + serverViewModel = serverViewModel, startDestination = startDestination ) } @@ -127,7 +136,7 @@ fun AppNavigation(viewModel: MainViewModel) { androidx.compose.runtime.key(captchaState.sessionId) { CaptchaWebViewDialog( captchaUrl = captchaState.url, - onDismiss = { viewModel.dismissCaptcha() } + onDismiss = { proxyViewModel.dismissCaptcha() } ) } } @@ -137,11 +146,11 @@ fun AppNavigation(viewModel: MainViewModel) { TelegramSubscribeDialog( onSubscribe = { uriHandler.openUri("https://t.me/+53nh4UNiSv5lNTgy") - viewModel.setTgSubscribeShown() + settingsViewModel.setTgSubscribeShown() showTgDialog = false }, onDismiss = { - viewModel.setTgSubscribeShown() + settingsViewModel.setTgSubscribeShown() showTgDialog = false } ) @@ -151,7 +160,9 @@ fun AppNavigation(viewModel: MainViewModel) { @Composable private fun AppNavHost( navController: NavHostController, - viewModel: MainViewModel, + settingsViewModel: SettingsViewModel, + proxyViewModel: ProxyViewModel, + serverViewModel: ServerViewModel, startDestination: String ) { NavHost( @@ -166,7 +177,7 @@ private fun AppNavHost( OnboardingScreen( onSetupServer = { navController.navigate(Routes.SSH_SETUP_OB) }, onSkip = { - viewModel.setOnboardingDone() + settingsViewModel.setOnboardingDone() navController.navigate(Routes.HOME) { popUpTo(navController.graph.startDestinationId) { inclusive = true } launchSingleTop = true @@ -177,7 +188,8 @@ private fun AppNavHost( composable(Routes.SSH_SETUP_OB) { SshSetupScreen( - viewModel = viewModel, + serverViewModel = serverViewModel, + settingsViewModel = settingsViewModel, onConnected = { navController.navigate(Routes.SERVER_MANAGEMENT_OB) { popUpTo(Routes.SSH_SETUP_OB) { inclusive = true } @@ -190,7 +202,8 @@ private fun AppNavHost( composable(Routes.SERVER_MANAGEMENT_OB) { ServerManagementScreen( - viewModel = viewModel, + serverViewModel = serverViewModel, + settingsViewModel = settingsViewModel, onContinue = { navController.navigate(Routes.CLIENT_SETUP_OB) { launchSingleTop = true @@ -201,10 +214,10 @@ private fun AppNavHost( composable(Routes.CLIENT_SETUP_OB) { ClientSetupScreen( - viewModel = viewModel, + settingsViewModel = settingsViewModel, showFinishButton = true, onFinish = { - viewModel.setOnboardingDone() + settingsViewModel.setOnboardingDone() navController.navigate(Routes.HOME) { popUpTo(navController.graph.startDestinationId) { inclusive = true } launchSingleTop = true @@ -216,7 +229,8 @@ private fun AppNavHost( // Основной поток (с навигацией) composable(Routes.SSH_SETUP) { SshSetupScreen( - viewModel = viewModel, + serverViewModel = serverViewModel, + settingsViewModel = settingsViewModel, onConnected = { navController.navigate(Routes.SERVER_MANAGEMENT) { popUpTo(Routes.SSH_SETUP) { inclusive = true } @@ -229,7 +243,8 @@ private fun AppNavHost( composable(Routes.SERVER_MANAGEMENT) { ServerManagementScreen( - viewModel = viewModel, + serverViewModel = serverViewModel, + settingsViewModel = settingsViewModel, onContinue = { navController.navigate(Routes.CLIENT_SETUP) { // Убираем SERVER_MANAGEMENT из back stack, @@ -243,20 +258,22 @@ private fun AppNavHost( composable(Routes.CLIENT_SETUP) { ClientSetupScreen( - viewModel = viewModel, + settingsViewModel = settingsViewModel, showFinishButton = false ) } composable(Routes.HOME) { HomeScreen( - viewModel = viewModel, + settingsViewModel = settingsViewModel, + proxyViewModel = proxyViewModel, + serverViewModel = serverViewModel, onNavigateToSshSetup = { navController.navigate(Routes.SSH_SETUP) } ) } composable(Routes.LOGS) { - LogsScreen(viewModel = viewModel) + LogsScreen(proxyViewModel = proxyViewModel) } } } diff --git a/app/src/main/java/com/freeturn/app/ui/screens/ClientSetupScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/ClientSetupScreen.kt index 276bd6b..4a4e029 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/ClientSetupScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/ClientSetupScreen.kt @@ -57,7 +57,7 @@ import com.freeturn.app.data.DnsMode import com.freeturn.app.data.ObfProfile import com.freeturn.app.data.Provider import com.freeturn.app.ui.HapticUtil -import com.freeturn.app.viewmodel.MainViewModel +import com.freeturn.app.viewmodel.SettingsViewModel import com.freeturn.app.viewmodel.SshConnectionState import kotlin.math.roundToInt import kotlinx.coroutines.delay @@ -69,7 +69,7 @@ import kotlinx.coroutines.delay */ @Composable fun ClientSetupScreen( - viewModel: MainViewModel, + viewModel: SettingsViewModel, showFinishButton: Boolean = false, onFinish: (() -> Unit)? = null ) { diff --git a/app/src/main/java/com/freeturn/app/ui/screens/HomeScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/HomeScreen.kt index d619283..fa0afae 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/HomeScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/HomeScreen.kt @@ -86,8 +86,13 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.delay import com.freeturn.app.ui.HapticUtil import com.freeturn.app.ui.theme.extendedColorScheme -import com.freeturn.app.viewmodel.MainViewModel import com.freeturn.app.viewmodel.ProxyState +import com.freeturn.app.viewmodel.SshConnectionState +import com.freeturn.app.viewmodel.UpdateState +import com.freeturn.app.viewmodel.SettingsViewModel +import com.freeturn.app.viewmodel.ProxyViewModel +import com.freeturn.app.viewmodel.ServerViewModel + import com.freeturn.app.viewmodel.SshConnectionState import com.freeturn.app.viewmodel.UpdateState import androidx.core.net.toUri @@ -95,16 +100,18 @@ import androidx.core.net.toUri @SuppressLint("BatteryLife") @Composable fun HomeScreen( - viewModel: MainViewModel, + settingsViewModel: SettingsViewModel, + proxyViewModel: ProxyViewModel, + serverViewModel: ServerViewModel, onNavigateToSshSetup: () -> Unit ) { val context = LocalContext.current - val proxyState by viewModel.proxyState.collectAsStateWithLifecycle() - val connectedSince by viewModel.connectedSince.collectAsStateWithLifecycle() + val proxyState by proxyViewModel.proxyState.collectAsStateWithLifecycle() + val connectedSince by proxyViewModel.connectedSince.collectAsStateWithLifecycle() val uptimeText = rememberProxyUptime(connectedSince) - val sshState by viewModel.sshState.collectAsStateWithLifecycle() - val sshConfig by viewModel.sshConfig.collectAsStateWithLifecycle() - val clientConfig by viewModel.clientConfig.collectAsStateWithLifecycle() + val sshState by serverViewModel.sshState.collectAsStateWithLifecycle() + val sshConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle() + val clientConfig by settingsViewModel.clientConfig.collectAsStateWithLifecycle() val isConfigured = sshConfig.ip.isNotBlank() // Запрос разрешений при первом открытии главного экрана @@ -148,8 +155,8 @@ fun HomeScreen( } } - val privacyMode by viewModel.privacyMode.collectAsStateWithLifecycle() - val profilesSnapshot by viewModel.profilesSnapshot.collectAsStateWithLifecycle() + val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle() + val profilesSnapshot by settingsViewModel.profilesSnapshot.collectAsStateWithLifecycle() val showBottomSheet = rememberSaveable { mutableStateOf(false) } val showProfilesSheet = rememberSaveable { mutableStateOf(false) } var showEasterEgg by rememberSaveable { mutableStateOf(false) } @@ -196,11 +203,11 @@ fun HomeScreen( when (proxyState) { is ProxyState.Idle, is ProxyState.Error -> { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_ON) - viewModel.startProxy() + proxyViewModel.startProxy() } is ProxyState.Running, is ProxyState.Connecting, is ProxyState.Starting -> { HapticUtil.perform(context, HapticUtil.Pattern.TOGGLE_OFF) - viewModel.stopProxy() + proxyViewModel.stopProxy() } else -> {} } @@ -304,7 +311,7 @@ fun HomeScreen( TextButton( onClick = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.reconnectSsh() + serverViewModel.reconnectSsh() }, enabled = sshState !is SshConnectionState.Connecting ) { @@ -343,10 +350,10 @@ fun HomeScreen( containerColor = sheetColor ) { InfoBottomSheet( - viewModel = viewModel, + settingsViewModel = settingsViewModel, containerColor = sheetColor, privacyMode = privacyMode, - onPrivacyModeChange = { viewModel.setPrivacyMode(it) }, + onPrivacyModeChange = { settingsViewModel.setPrivacyMode(it) }, onEasterEgg = { showBottomSheet.value = false showEasterEgg = true @@ -363,7 +370,7 @@ fun HomeScreen( containerColor = sheetColor ) { com.freeturn.app.ui.screens.ProfilesSheetContent( - viewModel = viewModel, + settingsViewModel = settingsViewModel, snapshot = profilesSnapshot, containerColor = sheetColor, onClose = { showProfilesSheet.value = false } @@ -371,7 +378,7 @@ fun HomeScreen( } } - UpdateDialogs(viewModel) + UpdateDialogs(settingsViewModel) if (showEasterEgg) { com.freeturn.app.ui.screens.easteregg.EasterEggDialog( @@ -384,9 +391,9 @@ fun HomeScreen( @Suppress("AssignedValueIsNeverRead") @Composable -private fun UpdateDialogs(viewModel: MainViewModel) { +private fun UpdateDialogs(settingsViewModel: SettingsViewModel) { val context = LocalContext.current - val updateState by viewModel.updateState.collectAsStateWithLifecycle() + val updateState by settingsViewModel.updateState.collectAsStateWithLifecycle() var dismissed by rememberSaveable { mutableStateOf(false) } when (val state = updateState) { @@ -417,7 +424,7 @@ private fun UpdateDialogs(viewModel: MainViewModel) { TextButton(onClick = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) dismissed = true - viewModel.downloadUpdate() + settingsViewModel.downloadUpdate() }) { Text(stringResource(R.string.update_download)) } }, dismissButton = { @@ -448,17 +455,17 @@ private fun UpdateDialogs(viewModel: MainViewModel) { is UpdateState.ReadyToInstall -> { AlertDialog( - onDismissRequest = { viewModel.resetUpdateState() }, + onDismissRequest = { settingsViewModel.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() + settingsViewModel.installUpdate() }) { Text(stringResource(R.string.update_install)) } }, dismissButton = { - TextButton(onClick = { viewModel.resetUpdateState() }) { + TextButton(onClick = { settingsViewModel.resetUpdateState() }) { Text(stringResource(R.string.cancel)) } } @@ -549,7 +556,7 @@ private fun ProxyToggleButton(state: ProxyState, onClick: () -> Unit) { @Suppress("AssignedValueIsNeverRead") @Composable private fun InfoBottomSheet( - viewModel: MainViewModel, + settingsViewModel: SettingsViewModel, containerColor: Color, privacyMode: Boolean, onPrivacyModeChange: (Boolean) -> Unit, @@ -557,8 +564,8 @@ private fun InfoBottomSheet( ) { val context = LocalContext.current val uriHandler = LocalUriHandler.current - val dynamicTheme by viewModel.dynamicTheme.collectAsStateWithLifecycle() - val updateState by viewModel.updateState.collectAsStateWithLifecycle() + val dynamicTheme by settingsViewModel.dynamicTheme.collectAsStateWithLifecycle() + val updateState by settingsViewModel.updateState.collectAsStateWithLifecycle() var showResetDialog by rememberSaveable { mutableStateOf(false) } val appVersion = remember { @@ -580,15 +587,15 @@ private fun InfoBottomSheet( colors = listColors, onCheck = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.checkForUpdate() + settingsViewModel.checkForUpdate() }, onDownload = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.downloadUpdate() + settingsViewModel.downloadUpdate() }, onInstall = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.installUpdate() + settingsViewModel.installUpdate() } ) } @@ -665,7 +672,7 @@ private fun InfoBottomSheet( context, if (it) HapticUtil.Pattern.TOGGLE_ON else HapticUtil.Pattern.TOGGLE_OFF ) - viewModel.setDynamicTheme(it) + settingsViewModel.setDynamicTheme(it) } ) } @@ -737,7 +744,7 @@ private fun InfoBottomSheet( TextButton( onClick = { showResetDialog = false - viewModel.resetAllSettings(context) + settingsViewModel.resetAllSettings() }, colors = ButtonDefaults.textButtonColors( contentColor = MaterialTheme.colorScheme.error diff --git a/app/src/main/java/com/freeturn/app/ui/screens/LogsScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/LogsScreen.kt index 2abbc0e..e3bc82c 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/LogsScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/LogsScreen.kt @@ -39,12 +39,12 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.freeturn.app.R import com.freeturn.app.ui.HapticUtil import com.freeturn.app.ui.theme.extendedColorScheme -import com.freeturn.app.viewmodel.MainViewModel +import com.freeturn.app.viewmodel.ProxyViewModel @Composable -fun LogsScreen(viewModel: MainViewModel) { +fun LogsScreen(proxyViewModel: ProxyViewModel) { val context = LocalContext.current - val logs by viewModel.logs.collectAsStateWithLifecycle() + val logs by proxyViewModel.logs.collectAsStateWithLifecycle() val listState = rememberLazyListState() LaunchedEffect(logs.size) { @@ -72,7 +72,7 @@ fun LogsScreen(viewModel: MainViewModel) { IconButton( onClick = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.clearLogs() + proxyViewModel.clearLogs() }, enabled = logs.isNotEmpty() ) { diff --git a/app/src/main/java/com/freeturn/app/ui/screens/ProfilesScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/ProfilesScreen.kt index 778c491..00fbabc 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/ProfilesScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/ProfilesScreen.kt @@ -56,11 +56,11 @@ import com.freeturn.app.data.ProfilesSnapshot import com.freeturn.app.ui.HapticUtil import com.freeturn.app.ui.components.ProfileNameDialog import com.freeturn.app.ui.util.hapticClickable -import com.freeturn.app.viewmodel.MainViewModel +import com.freeturn.app.viewmodel.SettingsViewModel @Composable fun ProfilesSheetContent( - viewModel: MainViewModel, + settingsViewModel: SettingsViewModel, snapshot: ProfilesSnapshot, containerColor: Color, @Suppress("UNUSED_PARAMETER") onClose: () -> Unit @@ -96,7 +96,7 @@ fun ProfilesSheetContent( leadingContent = { Icon(painterResource(R.drawable.cached_24px), null) }, colors = listColors, modifier = Modifier.hapticClickable(HapticUtil.Pattern.SUCCESS) { - viewModel.updateActiveProfileFromCurrent() + settingsViewModel.updateActiveProfileFromCurrent() android.widget.Toast.makeText(context, updatedMsg, android.widget.Toast.LENGTH_SHORT).show() } ) @@ -140,7 +140,7 @@ fun ProfilesSheetContent( isActive = snapshot.activeId == p.id, menuExpanded = menuTarget == p.id, onApply = { - if (snapshot.activeId != p.id) viewModel.applyProfile(p.id) + if (snapshot.activeId != p.id) settingsViewModel.applyProfile(p.id) }, onMenuToggle = { menuTarget = if (menuTarget == p.id) null else p.id }, onMenuDismiss = { menuTarget = null }, @@ -165,7 +165,7 @@ fun ProfilesSheetContent( takenNames = takenNames, onDismiss = { showSaveDialog = false }, onConfirm = { name -> - viewModel.saveCurrentAsProfile(name) + settingsViewModel.saveCurrentAsProfile(name) showSaveDialog = false } ) @@ -182,7 +182,7 @@ fun ProfilesSheetContent( takenNames = takenNames, onDismiss = { renameTarget = null }, onConfirm = { name -> - viewModel.renameProfile(id, name) + settingsViewModel.renameProfile(id, name) renameTarget = null } ) @@ -202,7 +202,7 @@ fun ProfilesSheetContent( TextButton( onClick = { HapticUtil.perform(context, HapticUtil.Pattern.ERROR) - viewModel.deleteProfile(id) + settingsViewModel.deleteProfile(id) deleteTarget = null }, colors = ButtonDefaults.textButtonColors( diff --git a/app/src/main/java/com/freeturn/app/ui/screens/ServerManagementScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/ServerManagementScreen.kt index cdd287b..34166a2 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/ServerManagementScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/ServerManagementScreen.kt @@ -66,26 +66,28 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.freeturn.app.ui.HapticUtil import com.freeturn.app.ui.theme.extendedColorScheme -import com.freeturn.app.viewmodel.MainViewModel import com.freeturn.app.viewmodel.ServerState import com.freeturn.app.viewmodel.SshConnectionState +import com.freeturn.app.viewmodel.ServerViewModel +import com.freeturn.app.viewmodel.SettingsViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun ServerManagementScreen( - viewModel: MainViewModel, + serverViewModel: ServerViewModel, + settingsViewModel: SettingsViewModel, onContinue: () -> Unit ) { - val sshState by viewModel.sshState.collectAsStateWithLifecycle() - val serverState by viewModel.serverState.collectAsStateWithLifecycle() - val sshConfig by viewModel.sshConfig.collectAsStateWithLifecycle() - val savedListen by viewModel.proxyListen.collectAsStateWithLifecycle() - val savedConnect by viewModel.proxyConnect.collectAsStateWithLifecycle() - val sshLog by viewModel.sshLog.collectAsStateWithLifecycle() - val privacyMode by viewModel.privacyMode.collectAsStateWithLifecycle() - val installStage by viewModel.serverInstallStage.collectAsStateWithLifecycle() - val clientCfg by viewModel.clientConfig.collectAsStateWithLifecycle() - val serverLogs by viewModel.serverLogs.collectAsStateWithLifecycle() + val sshState by serverViewModel.sshState.collectAsStateWithLifecycle() + val serverState by serverViewModel.serverState.collectAsStateWithLifecycle() + val sshConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle() + val savedListen by settingsViewModel.proxyListen.collectAsStateWithLifecycle() + val savedConnect by settingsViewModel.proxyConnect.collectAsStateWithLifecycle() + val sshLog by serverViewModel.sshLog.collectAsStateWithLifecycle() + val privacyMode by settingsViewModel.privacyMode.collectAsStateWithLifecycle() + val installStage by serverViewModel.serverInstallStage.collectAsStateWithLifecycle() + val clientCfg by settingsViewModel.clientConfig.collectAsStateWithLifecycle() + val serverLogs by serverViewModel.serverLogs.collectAsStateWithLifecycle() var proxyListenIp by rememberSaveable(savedListen) { mutableStateOf(savedListen.substringBeforeLast(":", "0.0.0.0").ifBlank { "0.0.0.0" }) @@ -98,7 +100,7 @@ fun ServerManagementScreen( val ip = proxyListenIp.ifBlank { "0.0.0.0" } val listen = "$ip:$proxyListenPort" if (listen != savedListen || proxyConnect != savedConnect) { - viewModel.saveProxyServerConfig(listen, proxyConnect) + settingsViewModel.saveProxyServerConfig(listen, proxyConnect) } } @@ -271,8 +273,8 @@ fun ServerManagementScreen( FilledTonalButton( onClick = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.saveProxyServerConfig("${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort", proxyConnect) - viewModel.installServer() + settingsViewModel.saveProxyServerConfig("${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort", proxyConnect) + serverViewModel.installServer() }, enabled = isConnected && !isWorking, modifier = Modifier.fillMaxWidth(), @@ -286,8 +288,8 @@ fun ServerManagementScreen( Button( onClick = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.saveProxyServerConfig("${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort", proxyConnect) - viewModel.startServer() + settingsViewModel.saveProxyServerConfig("${proxyListenIp.ifBlank { "0.0.0.0" }}:$proxyListenPort", proxyConnect) + serverViewModel.startServer() }, enabled = (isConnected && !isWorking && serverKnown?.installed == true) && !serverKnown.running, @@ -302,7 +304,7 @@ fun ServerManagementScreen( OutlinedButton( onClick = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.stopServer() + serverViewModel.stopServer() }, enabled = isConnected && !isWorking && serverKnown?.running == true, modifier = Modifier.fillMaxWidth(), @@ -349,7 +351,7 @@ fun ServerManagementScreen( androidx.compose.material3.IconButton( onClick = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.fetchServerLogs() + serverViewModel.fetchServerLogs() }, enabled = isConnected && serverLogs != "…" ) { @@ -362,7 +364,7 @@ fun ServerManagementScreen( androidx.compose.material3.IconButton( onClick = { HapticUtil.perform(context, HapticUtil.Pattern.CLICK) - viewModel.clearServerLogs() + serverViewModel.clearServerLogs() }, enabled = serverLogs != "…" ) { diff --git a/app/src/main/java/com/freeturn/app/ui/screens/SshSetupScreen.kt b/app/src/main/java/com/freeturn/app/ui/screens/SshSetupScreen.kt index baf0521..c11b00b 100644 --- a/app/src/main/java/com/freeturn/app/ui/screens/SshSetupScreen.kt +++ b/app/src/main/java/com/freeturn/app/ui/screens/SshSetupScreen.kt @@ -54,18 +54,19 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.freeturn.app.data.SshConfig import com.freeturn.app.ui.HapticUtil -import com.freeturn.app.viewmodel.MainViewModel +import com.freeturn.app.viewmodel.ServerViewModel import com.freeturn.app.viewmodel.SshConnectionState @OptIn(ExperimentalMaterial3Api::class) @Composable fun SshSetupScreen( - viewModel: MainViewModel, + serverViewModel: ServerViewModel, + settingsViewModel: com.freeturn.app.viewmodel.SettingsViewModel, onConnected: () -> Unit, onBack: () -> Unit ) { - val sshState by viewModel.sshState.collectAsStateWithLifecycle() - val savedConfig by viewModel.sshConfig.collectAsStateWithLifecycle() + val sshState by serverViewModel.sshState.collectAsStateWithLifecycle() + val savedConfig by serverViewModel.sshConfig.collectAsStateWithLifecycle() var ip by rememberSaveable(savedConfig.ip) { mutableStateOf(savedConfig.ip) } var port by rememberSaveable(savedConfig.port) { mutableStateOf(savedConfig.port.toString()) } @@ -128,7 +129,7 @@ fun SshSetupScreen( onAuthDropdownChange = { authDropdownExpanded = it }, sshState = sshState, onConnect = { - viewModel.connectSsh( + serverViewModel.connectSsh( SshConfig( ip = ip.trim(), port = port.toIntOrNull() ?: 22, diff --git a/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt b/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt deleted file mode 100644 index 0369c42..0000000 --- a/app/src/main/java/com/freeturn/app/viewmodel/MainViewModel.kt +++ /dev/null @@ -1,611 +0,0 @@ -package com.freeturn.app.viewmodel - -import android.app.Application -import android.content.Context -import android.content.Intent -import androidx.lifecycle.AndroidViewModel -import androidx.lifecycle.viewModelScope -import com.freeturn.app.ProxyService -import com.freeturn.app.ProxyServiceState -import com.freeturn.app.data.AppPreferences -import com.freeturn.app.data.ClientConfig -import com.freeturn.app.data.ObfProfile -import com.freeturn.app.data.Profile -import com.freeturn.app.data.ProfilesSnapshot -import com.freeturn.app.data.SshConfig -import java.util.UUID -import com.freeturn.app.domain.AppUpdater -import com.freeturn.app.domain.LocalProxyManager -import com.freeturn.app.domain.SshRepository -import com.freeturn.app.ui.HapticUtil -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 -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import kotlinx.coroutines.withTimeoutOrNull - -class MainViewModel(application: Application) : AndroidViewModel(application) { - - private val prefs = AppPreferences(application) - private val sshRepository = SshRepository(application) - private val proxyManager = LocalProxyManager(application) - private val appUpdater = AppUpdater(application) - - val sshState: StateFlow = sshRepository.sshState - val serverState: StateFlow = sshRepository.serverState - val sshLog: StateFlow> = sshRepository.sshLog - val serverLogs: StateFlow = sshRepository.serverLogs - - val proxyState: StateFlow = proxyManager.proxyState - val connectedSince: StateFlow = ProxyServiceState.connectedSince - val logs: StateFlow> = ProxyServiceState.logs - val updateState: StateFlow = appUpdater.state - - private val _isInitialized = MutableStateFlow(false) - val isInitialized: StateFlow = _isInitialized.asStateFlow() - - private val _initialOnboardingDone = MutableStateFlow(false) - val initialOnboardingDone: StateFlow = _initialOnboardingDone.asStateFlow() - - private val _initialTgSubscribeShown = MutableStateFlow(false) - val initialTgSubscribeShown: StateFlow = _initialTgSubscribeShown.asStateFlow() - - init { - viewModelScope.launch { - val done = prefs.onboardingDoneFlow.first() - val tgShown = prefs.tgSubscribeShownFlow.first() - _initialOnboardingDone.value = done - _initialTgSubscribeShown.value = tgShown - _isInitialized.value = true - } - viewModelScope.launch { - proxyManager.observeProxyLifecycle() - } - viewModelScope.launch { - proxyManager.observeProxyServiceStatus() - } - viewModelScope.launch { - proxyManager.observeConnectionStats() - } - viewModelScope.launch { - proxyManager.observeCaptchaEvents() - } - proxyManager.syncInitialState() - - viewModelScope.launch { - appUpdater.checkForUpdate(silent = true) - } - } - - override fun onCleared() { - super.onCleared() - proxyManager.destroy() - } - - val sshConfig: StateFlow = prefs.sshConfigFlow - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig()) - - val clientConfig: StateFlow = prefs.clientConfigFlow - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ClientConfig()) - - val onboardingDone: StateFlow = prefs.onboardingDoneFlow - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) - - val proxyListen: StateFlow = prefs.proxyListenFlow - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "0.0.0.0:56000") - - val proxyConnect: StateFlow = prefs.proxyConnectFlow - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "127.0.0.1:40537") - - val dynamicTheme: StateFlow = prefs.dynamicThemeFlow - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), true) - - val tgSubscribeShown: StateFlow = prefs.tgSubscribeShownFlow - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) - - val profilesSnapshot: StateFlow = prefs.profilesSnapshot - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot()) - - /** - * Сериализует все операции над списком профилей и зеркалирование активного - * профиля. Без этого параллельные viewModelScope.launch'и могли прочитать - * устаревший snapshot и затереть/перетянуть данные между профилями. - */ - private val profileMutex = Mutex() - - /** Сохранить текущие настройки как новый профиль и сделать активным. */ - fun saveCurrentAsProfile(name: String) { - viewModelScope.launch { - profileMutex.withLock { - val current = prefs.profilesSnapshot.first() - val ssh = prefs.sshConfigFlow.first() - val client = prefs.clientConfigFlow.first() - val listen = prefs.proxyListenFlow.first() - val connect = prefs.proxyConnectFlow.first() - val server = prefs.serverOptsFlow.first() - val base = name.trim().ifBlank { defaultProfileName(client.serverAddress) } - val profile = Profile( - id = UUID.randomUUID().toString(), - name = uniqueProfileName(base, current.list, excludingId = null), - ssh = ssh, - client = client, - proxyListen = listen, - proxyConnect = connect, - server = server - ) - prefs.saveProfiles(current.list + profile) - prefs.setActiveProfileId(profile.id) - } - } - } - - /** - * Гарантирует уникальность имени профиля. Защита от deep-link / автоматических - * сценариев, где UI-диалог не валидирует ввод. Дубль превращается в - * "имя (2)", "имя (3)" и т.д. - */ - private fun uniqueProfileName( - base: String, - existing: List, - excludingId: String? - ): String { - val taken = existing - .filter { it.id != excludingId } - .map { it.name.trim().lowercase() } - .toSet() - val trimmed = base.trim() - if (trimmed.lowercase() !in taken) return trimmed - var i = 2 - while ("$trimmed ($i)".lowercase() in taken) i++ - return "$trimmed ($i)" - } - - /** Публичный триггер пересохранения активного профиля текущими настройками. */ - fun updateActiveProfileFromCurrent() { - viewModelScope.launch { profileMutex.withLock { mirrorActiveProfile() } } - } - - /** - * Зеркалирует текущие prefs (ssh+client+server) в активный профиль. Источник истины — - * профиль, но legacy-ключи остаются «scratch»-областью для случая «нет профилей». - * Вызывается автоматически после каждой записи ssh/client/server конфига, чтобы - * пользовательские правки не терялись при переключении профилей. - * - * Параметры `*Override` позволяют передать значение, которое мы только что - * записали в DataStore, не полагаясь на асинхронную эмиссию Flow.first() — - * иначе возможен race, когда .first() возвращает доcоставочный snapshot. - * - * ВАЖНО: вызывать только под profileMutex. - */ - private suspend fun mirrorActiveProfile( - sshOverride: SshConfig? = null, - clientOverride: ClientConfig? = null, - listenOverride: String? = null, - connectOverride: String? = null, - serverOverride: AppPreferences.ServerOpts? = null, - ) { - val current = prefs.profilesSnapshot.first() - val activeId = current.activeId ?: return - val ssh = sshOverride ?: prefs.sshConfigFlow.first() - val client = clientOverride ?: prefs.clientConfigFlow.first() - val listen = listenOverride ?: prefs.proxyListenFlow.first() - val connect = connectOverride ?: prefs.proxyConnectFlow.first() - val server = serverOverride ?: prefs.serverOptsFlow.first() - val updated = current.list.map { - if (it.id == activeId) - it.copy( - ssh = ssh, - client = client, - proxyListen = listen, - proxyConnect = connect, - server = server - ) - else it - } - if (updated != current.list) prefs.saveProfiles(updated) - } - - fun renameProfile(id: String, name: String) { - viewModelScope.launch { - profileMutex.withLock { - val current = prefs.profilesSnapshot.first() - val target = current.list.firstOrNull { it.id == id } ?: return@withLock - val base = name.trim().ifBlank { target.name } - val unique = uniqueProfileName(base, current.list, excludingId = id) - val updated = current.list.map { - if (it.id == id) it.copy(name = unique) else it - } - prefs.saveProfiles(updated) - } - } - } - - /** - * Применяет профиль: загружает его ssh/client/server в legacy-ключи и помечает - * активным. Если прокси/сервер запущены — перезапускает. - */ - fun applyProfile(id: String) { - viewModelScope.launch { - val target = profileMutex.withLock { - val current = prefs.profilesSnapshot.first() - val t = current.list.firstOrNull { it.id == id } ?: return@withLock null - prefs.saveSshConfig(t.ssh) - prefs.saveClientConfig(t.client) - prefs.saveProxyConfig(t.proxyListen, t.proxyConnect) - prefs.saveServerOpts(t.server) - prefs.setActiveProfileId(t.id) - t - } ?: return@launch - - // Рестарт вне лока, чтобы не блокировать другие профильные операции - // на время stop/start (может занять секунды). - val serverRunning = (serverState.value as? ServerState.Known)?.running == true - if (serverRunning) restartServerIfRunning() - - if (ProxyServiceState.isRunning.value) { - proxyManager.stopProxy() - withTimeoutOrNull(2_000) { - ProxyServiceState.isRunning.first { !it } - } - proxyManager.startProxy(target.client) - } - } - } - - fun deleteProfile(id: String) { - viewModelScope.launch { - profileMutex.withLock { - val current = prefs.profilesSnapshot.first() - val remaining = current.list.filterNot { it.id == id } - prefs.saveProfiles(remaining) - if (current.activeId == id) { - val next = remaining.firstOrNull() - prefs.setActiveProfileId(next?.id) - if (next != null) { - prefs.saveSshConfig(next.ssh) - prefs.saveClientConfig(next.client) - prefs.saveProxyConfig(next.proxyListen, next.proxyConnect) - prefs.saveServerOpts(next.server) - } - } - } - } - } - - private fun defaultProfileName(serverAddr: String): String = - serverAddr.substringBefore(':').takeIf { it.isNotBlank() } - ?: getApplication().getString(com.freeturn.app.R.string.profile_default_name) - - fun setDynamicTheme(enabled: Boolean) { - viewModelScope.launch { prefs.setDynamicTheme(enabled) } - } - - fun setTgSubscribeShown() { - viewModelScope.launch { prefs.setTgSubscribeShown() } - } - - private val _privacyMode = MutableStateFlow(false) - val privacyMode: StateFlow = _privacyMode.asStateFlow() - - fun setPrivacyMode(enabled: Boolean) { _privacyMode.value = enabled } - - // SSH - fun connectSsh(config: SshConfig) { - viewModelScope.launch { - profileMutex.withLock { prefs.saveSshConfig(config) } - val (success, fp) = sshRepository.connectSsh(config) - if (success) { - if (config.hostFingerprint.isEmpty() && fp != null) { - profileMutex.withLock { prefs.saveSshFingerprint(fp) } - } - HapticUtil.perform(getApplication(), HapticUtil.Pattern.SUCCESS) - } else { - HapticUtil.perform(getApplication(), HapticUtil.Pattern.ERROR) - } - } - } - - fun reconnectSsh() { - viewModelScope.launch { - val cfg = sshRepository.activeSshConfig - ?: sshConfig.value.takeIf { it.ip.isNotEmpty() } - ?: prefs.sshConfigFlow.first() - if (cfg.ip.isNotEmpty()) connectSsh(cfg) - } - } - - // Server management - val serverOpts: StateFlow = prefs.serverOptsFlow - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AppPreferences.ServerOpts()) - - private val _serverInstallStage = MutableStateFlow(null) - /** Последний результат install: "cached" | "downloaded" | null. */ - val serverInstallStage: StateFlow = _serverInstallStage.asStateFlow() - - private val _isRegeneratingObfKey = MutableStateFlow(false) - /** true — пока крутится gen-obf-key + последующий рестарт сервера/клиента. */ - val isRegeneratingObfKey: StateFlow = _isRegeneratingObfKey.asStateFlow() - - fun installServer() { - viewModelScope.launch { - _serverInstallStage.value = null - val outcome = sshRepository.installServer() - if (outcome is com.freeturn.app.domain.InstallOutcome.Success) { - _serverInstallStage.value = outcome.stage - // Авто-генерация obf-key после первого скачивания, если ещё нет. - if (outcome.stage == "downloaded") { - val current = prefs.serverOptsFlow.first() - if (current.obfKey.isBlank()) { - val key = sshRepository.generateObfKey() - if (!key.isNullOrBlank()) { - val next = current.copy(obfKey = key) - profileMutex.withLock { prefs.saveServerOpts(next) } - } - } - } - // Скрипт переустановил бинарь поверх работающего процесса — - // SshRepository уже вызвал stop, осталось стартануть с актуальными - // listen/connect и serverOpts (их знает только VM). - if (outcome.needsRestart) { - startServer() - restartProxyIfRunning() - } - } - } - } - - fun consumeInstallStage() { _serverInstallStage.value = null } - - fun startServer() { - val l = proxyListen.value - val c = proxyConnect.value - if (!l.matches(Regex("""^[\w.\-]+:\d{1,5}$""")) || !c.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))) { - sshRepository.updateServerState(ServerState.Error("Неверный формат адреса (ожидается host:port)")) - return - } - val tcpMode = clientConfig.value.tcpForward - val opts = serverOpts.value - viewModelScope.launch { - sshRepository.startServer( - listen = l, connect = c, - tcpMode = tcpMode, - obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", - obfKey = if (opts.obfEnabled) opts.obfKey else "" - ) - } - } - - /** - * Bond — client-only флаг в новом ядре (сервер детектит его сам). Пишем - * только в ClientConfig и перезапускаем локальный клиент; сервер не трогаем. - */ - fun setBond(enabled: Boolean) { - viewModelScope.launch { - val current = prefs.clientConfigFlow.first() - if (current.bond == enabled) return@launch - val next = current.copy(bond = enabled) - profileMutex.withLock { prefs.saveClientConfig(next) } - restartProxyIfRunning() - } - } - - /** Выбор профиля обфускации (none|rtpopus). При sync ON — рестарт сервера. */ - fun setObfProfile(profile: String) { - viewModelScope.launch { - val current = prefs.serverOptsFlow.first() - val known = serverState.value as? ServerState.Known - val storedMatches = current.obfProfile == profile - val effectiveMatches = known?.obfProfile?.let { it == profile } ?: true - if (storedMatches && effectiveMatches) return@launch - val sync = clientConfig.value.syncServerSwitches - var next = current.copy(obfProfile = profile) - // При включении реального профиля, если ключа ещё нет и sync включён — - // пробуем взять с сервера. В !sync режиме сервер не трогаем. - if (profile != ObfProfile.NONE && next.obfKey.isBlank() && sync) { - val key = sshRepository.generateObfKey() - if (!key.isNullOrBlank()) next = next.copy(obfKey = key) - } - if (!storedMatches || next.obfKey != current.obfKey) { - profileMutex.withLock { prefs.saveServerOpts(next) } - } - if (sync) restartServerIfRunning() - restartProxyIfRunning() - } - } - - /** - * Глобальный sync-флаг. При включении (false→true) выравниваем сервер с - * клиентскими свитчами разовым рестартом, иначе разъехавшиеся ключ/флаги - * провалят DTLS handshake. - */ - fun setSyncServerSwitches(enabled: Boolean) { - viewModelScope.launch { - val current = prefs.clientConfigFlow.first() - if (current.syncServerSwitches == enabled) return@launch - val next = current.copy(syncServerSwitches = enabled) - profileMutex.withLock { prefs.saveClientConfig(next) } - if (enabled) { - restartServerIfRunning() - restartProxyIfRunning() - } - } - } - - /** - * Прямое редактирование obf-key пользователем. Принимает любую строку - * (валидация формата — на стороне ProxyService/скрипта); если ключ - * меняется в sync-режиме, перезапускаем сервер. - */ - fun setObfKey(key: String) { - viewModelScope.launch { - val current = prefs.serverOptsFlow.first() - val trimmed = key.trim() - if (current.obfKey == trimmed) return@launch - val next = current.copy(obfKey = trimmed) - profileMutex.withLock { prefs.saveServerOpts(next) } - if (clientConfig.value.syncServerSwitches) restartServerIfRunning() - restartProxyIfRunning() - } - } - - fun regenerateObfKey() { - viewModelScope.launch { - if (_isRegeneratingObfKey.value) return@launch - _isRegeneratingObfKey.value = true - try { - val key = sshRepository.generateObfKey() ?: return@launch - val current = prefs.serverOptsFlow.first() - val next = current.copy(obfKey = key) - profileMutex.withLock { prefs.saveServerOpts(next) } - if (clientConfig.value.syncServerSwitches) restartServerIfRunning() - restartProxyIfRunning() - } finally { - _isRegeneratingObfKey.value = false - } - } - } - - /** Перезапускает сервер с актуальными опциями, если он сейчас запущен. */ - private suspend fun restartServerIfRunning() { - val running = (serverState.value as? ServerState.Known)?.running == true - if (!running) return - val l = proxyListen.value - val c = proxyConnect.value - if (!l.matches(Regex("""^[\w.\-]+:\d{1,5}$""")) || - !c.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))) return - val opts = prefs.serverOptsFlow.first() - val tcpMode = clientConfig.value.tcpForward - sshRepository.stopServer() - sshRepository.startServer( - listen = l, connect = c, - tcpMode = tcpMode, - obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", - obfKey = if (opts.obfEnabled) opts.obfKey else "" - ) - } - - /** - * Перезапускает локальный клиент с актуальным ClientConfig + serverOpts, - * если он сейчас работает. Используется после изменения sync-флагов - * (tcpForward/obf*) и client-only bond, чтобы клиент и сервер не разъехались - * по параметрам после отдельного рестарта сервера. - */ - private suspend fun restartProxyIfRunning() { - if (!ProxyServiceState.isRunning.value) return - proxyManager.stopProxy() - withTimeoutOrNull(2_000) { - ProxyServiceState.isRunning.first { !it } - } - proxyManager.startProxy(clientConfig.value) - } - - fun stopServer() { - viewModelScope.launch { sshRepository.stopServer() } - } - - fun fetchServerLogs(lines: Int = 200) { - viewModelScope.launch { sshRepository.fetchServerLogs(lines) } - } - - fun clearServerLogs() { - sshRepository.clearServerLogs() - } - - /** Переключает TCP-форвард режим (-mode tcp). Если sync ON и сервер запущен — автоперезапуск. */ - fun setTcpForward(enabled: Boolean) { - val current = clientConfig.value - val known = serverState.value as? ServerState.Known - val storedMatches = current.tcpForward == enabled - val effectiveMatches = known?.tcpMode?.let { it == enabled } ?: true - if (storedMatches && effectiveMatches) return - viewModelScope.launch { - if (!storedMatches) { - val next = current.copy(tcpForward = enabled) - profileMutex.withLock { prefs.saveClientConfig(next) } - } - if (current.syncServerSwitches) { - val serverRunning = (serverState.value as? ServerState.Known)?.running == true - if (serverRunning) { - sshRepository.stopServer() - startServer() - } - } - restartProxyIfRunning() - } - } - - // Local proxy - fun startProxy() { - viewModelScope.launch { - proxyManager.startProxy(clientConfig.value) - } - } - - fun stopProxy() { - proxyManager.stopProxy() - } - - fun dismissCaptcha() { - proxyManager.dismissCaptcha() - } - - fun clearLogs() { - ProxyServiceState.clearLogs() - } - - // Preferences - fun saveClientConfig(config: ClientConfig) { - viewModelScope.launch { - profileMutex.withLock { prefs.saveClientConfig(config) } - } - } - - fun saveProxyServerConfig(listen: String, connect: String) { - viewModelScope.launch { - profileMutex.withLock { prefs.saveProxyConfig(listen, connect) } - } - } - - fun setOnboardingDone() { - viewModelScope.launch { prefs.setOnboardingDone(true) } - } - - // App update - fun checkForUpdate() { - viewModelScope.launch { appUpdater.checkForUpdate(silent = false) } - } - - fun downloadUpdate() { - viewModelScope.launch { appUpdater.downloadUpdate() } - } - - fun installUpdate() { - appUpdater.installUpdate() - } - - fun resetUpdateState() { - appUpdater.resetState() - } - - fun resetAllSettings(context: Context) { - viewModelScope.launch { - if (ProxyServiceState.isRunning.value) { - context.stopService(Intent(context, ProxyService::class.java)) - } - prefs.resetAll() - sshRepository.resetAll() - proxyManager.clearState() - ProxyServiceState.clearLogs() - - val intent = (context as? android.app.Activity)?.intent - ?: Intent(context, com.freeturn.app.MainActivity::class.java) - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) - context.startActivity(intent) - } - } -} diff --git a/app/src/main/java/com/freeturn/app/viewmodel/ProxyViewModel.kt b/app/src/main/java/com/freeturn/app/viewmodel/ProxyViewModel.kt new file mode 100644 index 0000000..186f7c3 --- /dev/null +++ b/app/src/main/java/com/freeturn/app/viewmodel/ProxyViewModel.kt @@ -0,0 +1,49 @@ +package com.freeturn.app.viewmodel + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.freeturn.app.ProxyServiceState +import com.freeturn.app.data.AppPreferences +import com.freeturn.app.data.ClientConfig +import com.freeturn.app.domain.LocalProxyManager +import kotlinx.coroutines.flow.SharingStarted +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.stateIn +import kotlinx.coroutines.launch + +class ProxyViewModel( + private val proxyManager: LocalProxyManager, + private val prefs: AppPreferences +) : ViewModel() { + + val proxyState: StateFlow = proxyManager.proxyState + val connectedSince: StateFlow = ProxyServiceState.connectedSince + val logs: StateFlow> = ProxyServiceState.logs + + val clientConfig: StateFlow = prefs.clientConfigFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ClientConfig()) + + val proxyListen: StateFlow = prefs.proxyListenFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "0.0.0.0:56000") + + val proxyConnect: StateFlow = prefs.proxyConnectFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "127.0.0.1:40537") + + fun startProxy() { + viewModelScope.launch { + proxyManager.startProxy(clientConfig.value) + } + } + + fun stopProxy() { + proxyManager.stopProxy() + } + + fun dismissCaptcha() { + proxyManager.dismissCaptcha() + } + + fun clearLogs() { + ProxyServiceState.clearLogs() + } +} diff --git a/app/src/main/java/com/freeturn/app/viewmodel/ServerViewModel.kt b/app/src/main/java/com/freeturn/app/viewmodel/ServerViewModel.kt new file mode 100644 index 0000000..6e80931 --- /dev/null +++ b/app/src/main/java/com/freeturn/app/viewmodel/ServerViewModel.kt @@ -0,0 +1,171 @@ +package com.freeturn.app.viewmodel + +import android.content.Context +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.freeturn.app.ProxyServiceState +import com.freeturn.app.data.AppPreferences +import com.freeturn.app.data.SshConfig +import com.freeturn.app.domain.LocalProxyManager +import com.freeturn.app.domain.SshRepository +import com.freeturn.app.ui.HapticUtil +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 +import kotlinx.coroutines.withTimeoutOrNull + +class ServerViewModel( + private val sshRepository: SshRepository, + private val proxyManager: LocalProxyManager, + private val prefs: AppPreferences, + private val context: Context +) : ViewModel() { + + val sshState: StateFlow = sshRepository.sshState + val serverState: StateFlow = sshRepository.serverState + val sshLog: StateFlow> = sshRepository.sshLog + val serverLogs: StateFlow = sshRepository.serverLogs + + val serverOpts: StateFlow = prefs.serverOptsFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), AppPreferences.ServerOpts()) + + val sshConfig: StateFlow = prefs.sshConfigFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), SshConfig()) + + private val _serverInstallStage = MutableStateFlow(null) + val serverInstallStage: StateFlow = _serverInstallStage.asStateFlow() + + private val _isRegeneratingObfKey = MutableStateFlow(false) + val isRegeneratingObfKey: StateFlow = _isRegeneratingObfKey.asStateFlow() + + fun connectSsh(config: SshConfig) { + viewModelScope.launch { + prefs.saveSshConfig(config) + val (success, fp) = sshRepository.connectSsh(config) + if (success) { + if (config.hostFingerprint.isEmpty() && fp != null) { + prefs.saveSshFingerprint(fp) + } + HapticUtil.perform(context, HapticUtil.Pattern.SUCCESS) + } else { + HapticUtil.perform(context, HapticUtil.Pattern.ERROR) + } + } + } + + fun reconnectSsh() { + viewModelScope.launch { + val cfg = sshRepository.activeSshConfig + ?: sshConfig.value.takeIf { it.ip.isNotEmpty() } + ?: prefs.sshConfigFlow.first() + if (cfg.ip.isNotEmpty()) connectSsh(cfg) + } + } + + fun installServer() { + viewModelScope.launch { + _serverInstallStage.value = null + val outcome = sshRepository.installServer() + if (outcome is com.freeturn.app.domain.InstallOutcome.Success) { + _serverInstallStage.value = outcome.stage + if (outcome.stage == "downloaded") { + val current = prefs.serverOptsFlow.first() + if (current.obfKey.isBlank()) { + val key = sshRepository.generateObfKey() + if (!key.isNullOrBlank()) { + prefs.saveServerOpts(current.copy(obfKey = key)) + } + } + } + if (outcome.needsRestart) { + startServer() + restartProxyIfRunning() + } + } + } + } + + fun consumeInstallStage() { _serverInstallStage.value = null } + + fun startServer() { + viewModelScope.launch { + val l = prefs.proxyListenFlow.first() + val c = prefs.proxyConnectFlow.first() + if (!l.matches(Regex("""^[\w.\-]+:\d{1,5}$""")) || !c.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))) { + sshRepository.updateServerState(ServerState.Error("Неверный формат адреса (ожидается host:port)")) + return@launch + } + val tcpMode = prefs.clientConfigFlow.first().tcpForward + val opts = serverOpts.value + sshRepository.startServer( + listen = l, connect = c, + tcpMode = tcpMode, + obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", + obfKey = if (opts.obfEnabled) opts.obfKey else "" + ) + } + } + + fun stopServer() { + viewModelScope.launch { sshRepository.stopServer() } + } + + fun fetchServerLogs(lines: Int = 200) { + viewModelScope.launch { sshRepository.fetchServerLogs(lines) } + } + + fun clearServerLogs() { + sshRepository.clearServerLogs() + } + + fun regenerateObfKey() { + viewModelScope.launch { + if (_isRegeneratingObfKey.value) return@launch + _isRegeneratingObfKey.value = true + try { + val key = sshRepository.generateObfKey() ?: return@launch + val current = prefs.serverOptsFlow.first() + val next = current.copy(obfKey = key) + prefs.saveServerOpts(next) + + val clientConfig = prefs.clientConfigFlow.first() + if (clientConfig.syncServerSwitches) restartServerIfRunning() + restartProxyIfRunning() + } finally { + _isRegeneratingObfKey.value = false + } + } + } + + private suspend fun restartServerIfRunning() { + val running = (serverState.value as? ServerState.Known)?.running == true + if (!running) return + val l = prefs.proxyListenFlow.first() + val c = prefs.proxyConnectFlow.first() + if (!l.matches(Regex("""^[\w.\-]+:\d{1,5}$""")) || + !c.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))) return + val opts = prefs.serverOptsFlow.first() + val tcpMode = prefs.clientConfigFlow.first().tcpForward + sshRepository.stopServer() + sshRepository.startServer( + listen = l, connect = c, + tcpMode = tcpMode, + obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", + obfKey = if (opts.obfEnabled) opts.obfKey else "" + ) + } + + private suspend fun restartProxyIfRunning() { + if (!ProxyServiceState.isRunning.value) return + proxyManager.stopProxy() + withTimeoutOrNull(2_000) { + ProxyServiceState.isRunning.first { !it } + } + val clientConfig = prefs.clientConfigFlow.first() + proxyManager.startProxy(clientConfig) + } +} diff --git a/app/src/main/java/com/freeturn/app/viewmodel/SettingsViewModel.kt b/app/src/main/java/com/freeturn/app/viewmodel/SettingsViewModel.kt new file mode 100644 index 0000000..d10b3a7 --- /dev/null +++ b/app/src/main/java/com/freeturn/app/viewmodel/SettingsViewModel.kt @@ -0,0 +1,398 @@ +package com.freeturn.app.viewmodel + +import android.content.Context +import android.content.Intent +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.freeturn.app.ProxyService +import com.freeturn.app.ProxyServiceState +import com.freeturn.app.data.AppPreferences +import com.freeturn.app.data.ClientConfig +import com.freeturn.app.data.ObfProfile +import com.freeturn.app.data.Profile +import com.freeturn.app.data.ProfilesSnapshot +import com.freeturn.app.data.SshConfig +import com.freeturn.app.domain.AppUpdater +import com.freeturn.app.domain.LocalProxyManager +import com.freeturn.app.domain.SshRepository +import 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 +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeoutOrNull +import java.util.UUID + +class SettingsViewModel( + private val prefs: AppPreferences, + private val proxyManager: LocalProxyManager, + private val sshRepository: SshRepository, + private val appUpdater: AppUpdater, + private val context: Context +) : ViewModel() { + + val clientConfig: StateFlow = prefs.clientConfigFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ClientConfig()) + + val proxyListen: StateFlow = prefs.proxyListenFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "0.0.0.0:56000") + + val proxyConnect: StateFlow = prefs.proxyConnectFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "127.0.0.1:40537") + + val dynamicTheme: StateFlow = prefs.dynamicThemeFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), true) + + val tgSubscribeShown: StateFlow = prefs.tgSubscribeShownFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) + + val profilesSnapshot: StateFlow = prefs.profilesSnapshot + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfilesSnapshot()) + + val updateState: StateFlow = appUpdater.state + + private val _isInitialized = MutableStateFlow(false) + val isInitialized: StateFlow = _isInitialized.asStateFlow() + + private val _initialOnboardingDone = MutableStateFlow(false) + val initialOnboardingDone: StateFlow = _initialOnboardingDone.asStateFlow() + + private val _initialTgSubscribeShown = MutableStateFlow(false) + val initialTgSubscribeShown: StateFlow = _initialTgSubscribeShown.asStateFlow() + + val onboardingDone: StateFlow = prefs.onboardingDoneFlow + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) + + private val _privacyMode = MutableStateFlow(false) + val privacyMode: StateFlow = _privacyMode.asStateFlow() + + private val profileMutex = Mutex() + + init { + viewModelScope.launch { + val done = prefs.onboardingDoneFlow.first() + val tgShown = prefs.tgSubscribeShownFlow.first() + _initialOnboardingDone.value = done + _initialTgSubscribeShown.value = tgShown + _isInitialized.value = true + } + viewModelScope.launch { + appUpdater.checkForUpdate(silent = true) + } + } + + fun setPrivacyMode(enabled: Boolean) { _privacyMode.value = enabled } + + fun setDynamicTheme(enabled: Boolean) { + viewModelScope.launch { prefs.setDynamicTheme(enabled) } + } + + fun setTgSubscribeShown() { + viewModelScope.launch { prefs.setTgSubscribeShown() } + } + + fun setOnboardingDone() { + viewModelScope.launch { prefs.setOnboardingDone(true) } + } + + fun saveClientConfig(config: ClientConfig) { + viewModelScope.launch { + profileMutex.withLock { prefs.saveClientConfig(config) } + } + } + + fun saveProxyServerConfig(listen: String, connect: String) { + viewModelScope.launch { + profileMutex.withLock { prefs.saveProxyConfig(listen, connect) } + } + } + + // --- Profiles --- + fun saveCurrentAsProfile(name: String) { + viewModelScope.launch { + profileMutex.withLock { + val current = prefs.profilesSnapshot.first() + val ssh = prefs.sshConfigFlow.first() + val client = prefs.clientConfigFlow.first() + val listen = prefs.proxyListenFlow.first() + val connect = prefs.proxyConnectFlow.first() + val server = prefs.serverOptsFlow.first() + val base = name.trim().ifBlank { + serverAddrToProfileName(client.serverAddress) + } + val profile = Profile( + id = UUID.randomUUID().toString(), + name = uniqueProfileName(base, current.list, null), + ssh = ssh, + client = client, + proxyListen = listen, + proxyConnect = connect, + server = server + ) + prefs.saveProfiles(current.list + profile) + prefs.setActiveProfileId(profile.id) + } + } + } + + fun updateActiveProfileFromCurrent() { + viewModelScope.launch { profileMutex.withLock { mirrorActiveProfile() } } + } + + private suspend fun mirrorActiveProfile() { + val current = prefs.profilesSnapshot.first() + val activeId = current.activeId ?: return + val ssh = prefs.sshConfigFlow.first() + val client = prefs.clientConfigFlow.first() + val listen = prefs.proxyListenFlow.first() + val connect = prefs.proxyConnectFlow.first() + val server = prefs.serverOptsFlow.first() + val updated = current.list.map { + if (it.id == activeId) + it.copy( + ssh = ssh, + client = client, + proxyListen = listen, + proxyConnect = connect, + server = server + ) + else it + } + if (updated != current.list) prefs.saveProfiles(updated) + } + + fun renameProfile(id: String, name: String) { + viewModelScope.launch { + profileMutex.withLock { + val current = prefs.profilesSnapshot.first() + val target = current.list.firstOrNull { it.id == id } ?: return@withLock + val base = name.trim().ifBlank { target.name } + val unique = uniqueProfileName(base, current.list, id) + val updated = current.list.map { + if (it.id == id) it.copy(name = unique) else it + } + prefs.saveProfiles(updated) + } + } + } + + fun applyProfile(id: String) { + viewModelScope.launch { + val target = profileMutex.withLock { + val current = prefs.profilesSnapshot.first() + val t = current.list.firstOrNull { it.id == id } ?: return@withLock null + prefs.saveSshConfig(t.ssh) + prefs.saveClientConfig(t.client) + prefs.saveProxyConfig(t.proxyListen, t.proxyConnect) + prefs.saveServerOpts(t.server) + prefs.setActiveProfileId(t.id) + t + } ?: return@launch + + val serverRunning = (sshRepository.serverState.value as? ServerState.Known)?.running == true + if (serverRunning) restartServerIfRunning() + + if (ProxyServiceState.isRunning.value) { + proxyManager.stopProxy() + withTimeoutOrNull(2_000) { + ProxyServiceState.isRunning.first { !it } + } + proxyManager.startProxy(target.client) + } + } + } + + fun deleteProfile(id: String) { + viewModelScope.launch { + profileMutex.withLock { + val current = prefs.profilesSnapshot.first() + val remaining = current.list.filterNot { it.id == id } + prefs.saveProfiles(remaining) + if (current.activeId == id) { + val next = remaining.firstOrNull() + prefs.setActiveProfileId(next?.id) + if (next != null) { + prefs.saveSshConfig(next.ssh) + prefs.saveClientConfig(next.client) + prefs.saveProxyConfig(next.proxyListen, next.proxyConnect) + prefs.saveServerOpts(next.server) + } + } + } + } + } + + private fun serverAddrToProfileName(serverAddr: String): String = + serverAddr.substringBefore(':').takeIf { it.isNotBlank() } + ?: context.getString(com.freeturn.app.R.string.profile_default_name) + + private fun uniqueProfileName(base: String, existing: List, excludingId: String?): String { + val taken = existing + .filter { it.id != excludingId } + .map { it.name.trim().lowercase() } + .toSet() + val trimmed = base.trim() + if (trimmed.lowercase() !in taken) return trimmed + var i = 2 + while ("$trimmed ($i)".lowercase() in taken) i++ + return "$trimmed ($i)" + } + + // --- Server & Proxy Switches (TcpForward, Bond, Obf, Sync) --- + fun setBond(enabled: Boolean) { + viewModelScope.launch { + val current = prefs.clientConfigFlow.first() + if (current.bond == enabled) return@launch + val next = current.copy(bond = enabled) + profileMutex.withLock { prefs.saveClientConfig(next) } + restartProxyIfRunning() + } + } + + fun setObfProfile(profile: String) { + viewModelScope.launch { + val current = prefs.serverOptsFlow.first() + val known = sshRepository.serverState.value as? ServerState.Known + val storedMatches = current.obfProfile == profile + val effectiveMatches = known?.obfProfile?.let { it == profile } ?: true + if (storedMatches && effectiveMatches) return@launch + val sync = clientConfig.value.syncServerSwitches + var next = current.copy(obfProfile = profile) + if (profile != ObfProfile.NONE && next.obfKey.isBlank() && sync) { + val key = sshRepository.generateObfKey() + if (!key.isNullOrBlank()) next = next.copy(obfKey = key) + } + if (!storedMatches || next.obfKey != current.obfKey) { + profileMutex.withLock { prefs.saveServerOpts(next) } + } + if (sync) restartServerIfRunning() + restartProxyIfRunning() + } + } + + fun setSyncServerSwitches(enabled: Boolean) { + viewModelScope.launch { + val current = prefs.clientConfigFlow.first() + if (current.syncServerSwitches == enabled) return@launch + val next = current.copy(syncServerSwitches = enabled) + profileMutex.withLock { prefs.saveClientConfig(next) } + if (enabled) { + restartServerIfRunning() + restartProxyIfRunning() + } + } + } + + fun setObfKey(key: String) { + viewModelScope.launch { + val current = prefs.serverOptsFlow.first() + val trimmed = key.trim() + if (current.obfKey == trimmed) return@launch + val next = current.copy(obfKey = trimmed) + profileMutex.withLock { prefs.saveServerOpts(next) } + if (clientConfig.value.syncServerSwitches) restartServerIfRunning() + restartProxyIfRunning() + } + } + + fun setTcpForward(enabled: Boolean) { + val current = clientConfig.value + val known = sshRepository.serverState.value as? ServerState.Known + val storedMatches = current.tcpForward == enabled + val effectiveMatches = known?.tcpMode?.let { it == enabled } ?: true + if (storedMatches && effectiveMatches) return + viewModelScope.launch { + if (!storedMatches) { + val next = current.copy(tcpForward = enabled) + profileMutex.withLock { prefs.saveClientConfig(next) } + } + if (current.syncServerSwitches) { + val serverRunning = (sshRepository.serverState.value as? ServerState.Known)?.running == true + if (serverRunning) { + sshRepository.stopServer() + startServerFromPrefs() + } + } + restartProxyIfRunning() + } + } + + private suspend fun startServerFromPrefs() { + val l = prefs.proxyListenFlow.first() + val c = prefs.proxyConnectFlow.first() + val tcpMode = prefs.clientConfigFlow.first().tcpForward + val opts = prefs.serverOptsFlow.first() + sshRepository.startServer( + listen = l, connect = c, + tcpMode = tcpMode, + obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", + obfKey = if (opts.obfEnabled) opts.obfKey else "" + ) + } + + private suspend fun restartServerIfRunning() { + val running = (sshRepository.serverState.value as? ServerState.Known)?.running == true + if (!running) return + val l = prefs.proxyListenFlow.first() + val c = prefs.proxyConnectFlow.first() + if (!l.matches(Regex("""^[\w.\-]+:\d{1,5}$""")) || + !c.matches(Regex("""^[\w.\-]+:\d{1,5}$"""))) return + val opts = prefs.serverOptsFlow.first() + val tcpMode = prefs.clientConfigFlow.first().tcpForward + sshRepository.stopServer() + sshRepository.startServer( + listen = l, connect = c, + tcpMode = tcpMode, + obfProfile = if (opts.obfEnabled) opts.obfProfile else "none", + obfKey = if (opts.obfEnabled) opts.obfKey else "" + ) + } + + private suspend fun restartProxyIfRunning() { + if (!ProxyServiceState.isRunning.value) return + proxyManager.stopProxy() + withTimeoutOrNull(2_000) { + ProxyServiceState.isRunning.first { !it } + } + proxyManager.startProxy(prefs.clientConfigFlow.first()) + } + + // --- Updates --- + fun checkForUpdate() { + viewModelScope.launch { appUpdater.checkForUpdate(silent = false) } + } + + fun downloadUpdate() { + viewModelScope.launch { appUpdater.downloadUpdate() } + } + + fun installUpdate() { + appUpdater.installUpdate() + } + + fun resetUpdateState() { + appUpdater.resetState() + } + + fun resetAllSettings() { + viewModelScope.launch { + if (ProxyServiceState.isRunning.value) { + context.stopService(Intent(context, ProxyService::class.java)) + } + prefs.resetAll() + sshRepository.resetAll() + proxyManager.clearState() + ProxyServiceState.clearLogs() + + val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) + if (intent != null) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + context.startActivity(intent) + } + } + } +}