ProfileBackupsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/profiles/ProfileBackupsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.profiles23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.app.profiles.*6import eu.friedcutlet.yokan.services.backup.*7import eu.friedcutlet.yokan.services.catchingNonCancellation8import eu.friedcutlet.yokan.services.files.pickFile9import kotlinx.coroutines.CoroutineDispatcher10import kotlinx.coroutines.Dispatchers11import kotlinx.coroutines.flow.MutableStateFlow12import kotlinx.coroutines.flow.asStateFlow13import kotlinx.coroutines.flow.update14import kotlinx.coroutines.launch15import kotlinx.coroutines.withContext16import org.jetbrains.compose.resources.getString17import yokan.composeapp.generated.resources.*18import eu.friedcutlet.yokan.domain.ProfileId19import eu.friedcutlet.yokan.app.profiles.ProfileBackupOperations20import eu.friedcutlet.yokan.app.profiles.TargetedBackupPlan2122internal data class ProfileBackupsState(23 val profiles: List<ProfileRecord> = emptyList(),24 val target: ProfileId = ProfileId.Default,25 val available: Boolean = false,26 val busy: Boolean = false,27 val password: String = "",28 val format: BackupFormat = BackupFormat.Yokan,29 val mode: RestoreMode = RestoreMode.Merge,30 val plan: TargetedBackupPlan? = null,31 val snapshots: List<SafetySnapshot> = emptyList(),32 val message: String? = null,33 val error: String? = null,34)3536/** Lives in the device store, so an active-target restore survives navigator retirement. */37internal class ProfileBackupsViewModel(38 private val registry: ProfileRegistry,39 private val operations: ProfileBackupOperations,40 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,41) : ViewModel() {42 private val _state = MutableStateFlow(ProfileBackupsState())43 val state = _state.asStateFlow()44 private var input: ByteArray? = null45 init {46 viewModelScope.launch {47 registry.state.collect { value ->48 val snapshot = (value as? ProfileRegistryState.Ready)?.snapshot49 _state.update { current ->50 val records = snapshot?.profiles?.filter { it.status == ProfileStatus.Ready }.orEmpty()51 val target = if (records.any { it.id == current.target }) current.target else ProfileId.Default52 if (target != current.target) input = null53 current.copy(profiles = records, available = snapshot != null, target = target,54 plan = current.plan.takeIf { target == current.target }, snapshots = current.snapshots.takeIf { target == current.target }.orEmpty())55 }56 }57 }58 }59 fun select(id: ProfileId) {60 if (_state.value.busy || _state.value.profiles.none { it.id == id }) return61 input = null62 _state.update { it.copy(target = id, plan = null, snapshots = emptyList(), password = "", message = null, error = null) }63 refreshSnapshots(id)64 }65 fun password(value: String) = _state.update { it.copy(password = value, error = null) }66 fun format(value: BackupFormat) = _state.update { it.copy(format = value) }67 fun mode(value: RestoreMode) = _state.update { it.copy(mode = value) }68 fun refreshSnapshots(id: ProfileId = _state.value.target) = command {69 val snapshots = operations.snapshots(id)70 _state.update { if (it.target == id) it.copy(snapshots = snapshots) else it }71 }72 fun export() {73 val selected = _state.value74 command {75 val result = operations.export(selected.target, BackupOptions(format = selected.format), selected.password.takeIf { it.isNotEmpty() })76 _state.update { it.copy(message = result?.let { result -> result.path }, password = "") }77 }78 }79 fun chooseFile() {80 val id = _state.value.target81 command {82 val path = pickFile(listOf("tachibk", "proto", "json", "gz", "backup", "yokanbak")) ?: return@command83 input = operations.read(id, path)84 open(id, _state.value.password.takeIf { it.isNotEmpty() })85 }86 }87 fun unlock() {88 val selected = _state.value89 command { open(selected.target, selected.password.takeIf { it.isNotEmpty() }) }90 }91 private suspend fun open(id: ProfileId, password: String?) {92 val bytes = input ?: return93 when (val opened = operations.open(id, bytes, password)) {94 is BackupOpenResult.Ready -> _state.update { if (it.target == id) it.copy(plan = TargetedBackupPlan(id, opened.plan), password = "", error = null) else it }95 is BackupOpenResult.Failure -> {96 val message = getString(Res.string.profiles_backup_open_failed)97 _state.update { it.copy(plan = null, error = message) }98 }99 }100 }101 fun apply() {102 val selected = _state.value103 val plan = selected.plan ?: return104 command {105 val result = operations.apply(plan, selected.mode)106 input = null107 val snapshots = operations.snapshots(plan.target)108 val message = getString(Res.string.profiles_backup_restored, result.itemCount)109 _state.update { it.copy(plan = null, password = "", snapshots = snapshots, message = message) }110 }111 }112 fun rollback(id: ProfileId, snapshot: SafetySnapshot) = command {113 operations.rollback(id, snapshot)114 val snapshots = operations.snapshots(id)115 val message = getString(Res.string.profiles_backup_rolled_back)116 _state.update { if (it.target == id) it.copy(snapshots = snapshots, message = message) else it }117 }118 private fun command(action: suspend () -> Unit) {119 if (_state.value.busy) return120 _state.update { it.copy(busy = true, error = null, message = null) }121 viewModelScope.launch {122 try {123 catchingNonCancellation { withContext(workDispatcher) { action() } }124 .onFailure { error -> _state.update { it.copy(error = error.message ?: "Backup operation failed") } }125 } finally { _state.update { it.copy(busy = false) } }126 }127 }128}129