DataAndStorageViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/data/DataAndStorageViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.data23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import coil3.ImageLoader6import eu.friedcutlet.yokan.data.YokanRepository7import eu.friedcutlet.yokan.database.DbSettings8import eu.friedcutlet.yokan.database.configuredLocalFolders9import eu.friedcutlet.yokan.services.backup.BackupOpenError10import eu.friedcutlet.yokan.services.backup.BackupOpenResult11import eu.friedcutlet.yokan.services.backup.BackupPlan12import eu.friedcutlet.yokan.services.backup.BackupService13import eu.friedcutlet.yokan.services.backup.RestoreMode14import eu.friedcutlet.yokan.services.backup.RestorePreview15import eu.friedcutlet.yokan.services.backup.SafetySnapshot16import eu.friedcutlet.yokan.services.catchingNonCancellation17import eu.friedcutlet.yokan.services.files.LocalFileService18import eu.friedcutlet.yokan.services.notifications.NotificationService19import eu.friedcutlet.yokan.ui.image.clearCaches20import kotlinx.coroutines.CoroutineDispatcher21import kotlinx.coroutines.Dispatchers22import kotlinx.coroutines.Job23import kotlinx.coroutines.flow.MutableStateFlow24import kotlinx.coroutines.flow.StateFlow25import kotlinx.coroutines.flow.asStateFlow26import kotlinx.coroutines.flow.update27import kotlinx.coroutines.launch28import kotlinx.coroutines.withContext2930internal data class StorageUsage(31 val downloads: Long,32 val cache: Long,33 val backups: Long,34 val localFolders: Long,35)3637internal data class DataAndStorageState(38 val storage: StorageUsage? = null,39 val safetySnapshots: List<SafetySnapshot> = emptyList(),40 val restoreStatus: String? = null,41 val restoreError: String? = null,42 val restorePreview: RestorePreview? = null,43 val restorePlan: BackupPlan? = null,44 val restoreMode: RestoreMode = RestoreMode.Merge,45 val restorePasswordOpen: Boolean = false,46)4748/** Backup restore/rollback and storage usage for the Data and storage page. */49internal class DataAndStorageViewModel(50 private val backup: BackupService,51 private val files: LocalFileService,52 private val notifications: NotificationService,53 private val repository: YokanRepository,54 private val imageLoader: ImageLoader,55 private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,56) : ViewModel() {57 private val _state = MutableStateFlow(DataAndStorageState())58 val state: StateFlow<DataAndStorageState> = _state.asStateFlow()5960 val downloadRoot: String get() = files.downloadRoot61 val backupRoot: String get() = files.backupRoot6263 // Bytes of an encrypted backup awaiting its password.64 private var restoreBytes: ByteArray? = null65 private var storageJob: Job? = null6667 init {68 viewModelScope.launch {69 val snapshots = catchingNonCancellation { backup.listSafetySnapshots() }.getOrDefault(emptyList())70 _state.update { it.copy(safetySnapshots = snapshots) }71 }72 }7374 fun requestNotificationPermission() = notifications.requestPermission()7576 /** Recomputes usage for the storage-relevant [settings]; a newer call supersedes a running one. */77 fun refreshStorage(settings: DbSettings) {78 storageJob?.cancel()79 storageJob = viewModelScope.launch {80 val usage = computeStorageUsage(settings)81 _state.update { it.copy(storage = usage) }82 }83 }8485 /**86 * The chapter cache: page images (through Coil, which keeps its cache directory open) and saved87 * page lists. Other files under cacheRoot (logs, imported models, archive extraction) stay.88 */89 fun clearCache(settings: DbSettings) {90 viewModelScope.launch {91 withContext(workDispatcher) {92 imageLoader.clearCaches()93 repository.clearPageCache()94 }95 val usage = computeStorageUsage(settings)96 _state.update { it.copy(storage = usage) }97 }98 }99100 fun rollback(snapshot: SafetySnapshot) {101 viewModelScope.launch {102 catchingNonCancellation { backup.rollbackSafetySnapshot(snapshot) }103 .onSuccess {104 _state.update { it.copy(restoreStatus = "Rolled back successfully") }105 val snapshots = backup.listSafetySnapshots()106 _state.update { it.copy(safetySnapshots = snapshots) }107 }108 .onFailure { error -> _state.update { it.copy(restoreError = error.message ?: "Rollback failed") } }109 }110 }111112 fun clearRestoreCandidate() {113 restoreBytes = null114 _state.update { it.copy(restorePlan = null, restorePreview = null) }115 }116117 /** Opens the backup at [path], asking for a password when it is encrypted. */118 fun openBackupFile(path: String) {119 _state.update { it.copy(restoreError = null) }120 viewModelScope.launch {121 catchingNonCancellation {122 val bytes = backup.readBackupFile(path)123 restoreBytes = bytes124 when (val opened = backup.openBackup(bytes)) {125 is BackupOpenResult.Ready -> {126 restoreBytes = null127 _state.update {128 it.copy(129 restorePlan = opened.plan,130 restorePreview = opened.plan.preview,131 restoreMode = RestoreMode.Merge,132 restoreError = null,133 )134 }135 }136 is BackupOpenResult.Failure -> when (opened.error) {137 BackupOpenError.PasswordRequired -> _state.update { it.copy(restorePasswordOpen = true) }138 BackupOpenError.AuthenticationFailed -> _state.update {139 it.copy(restorePasswordOpen = true, restoreError = "Incorrect password, try again.")140 }141 else -> _state.update { it.copy(restoreError = "Unable to open backup.") }142 }143 }144 }.onFailure { error -> _state.update { it.copy(restoreError = error.message ?: "Restore failed") } }145 }146 }147148 fun submitPassword(password: String) {149 val bytes = restoreBytes ?: return150 viewModelScope.launch {151 _state.update { it.copy(restoreError = null) }152 when (val opened = backup.openBackup(bytes, password)) {153 is BackupOpenResult.Ready -> {154 restoreBytes = null155 _state.update {156 it.copy(157 restorePlan = opened.plan,158 restorePreview = opened.plan.preview,159 restoreError = null,160 restorePasswordOpen = false,161 )162 }163 }164 is BackupOpenResult.Failure -> {165 val message = if (opened.error == BackupOpenError.AuthenticationFailed) {166 "Wrong password or damaged backup"167 } else "Unable to open backup."168 _state.update { it.copy(restoreError = message, restorePasswordOpen = false) }169 clearRestoreCandidate()170 }171 }172 }173 }174175 fun dismissPassword() {176 _state.update { it.copy(restorePasswordOpen = false) }177 clearRestoreCandidate()178 }179180 fun selectRestoreMode(mode: RestoreMode) = _state.update { it.copy(restoreMode = mode) }181182 fun applyRestore() {183 val plan = _state.value.restorePlan ?: return184 val mode = _state.value.restoreMode185 viewModelScope.launch {186 catchingNonCancellation { backup.applyBackup(plan, mode) }187 .onSuccess { preview ->188 restoreBytes = null189 _state.update {190 it.copy(191 restoreStatus = "Restored ${preview.itemCount} items (${if (mode == RestoreMode.Merge) "Merge" else "Replace"})",192 restorePlan = null,193 restorePreview = null,194 )195 }196 val snapshots = backup.listSafetySnapshots()197 _state.update { it.copy(safetySnapshots = snapshots) }198 }199 .onFailure { error -> _state.update { it.copy(restoreError = error.message ?: "Restore failed") } }200 }201 }202203 private suspend fun computeStorageUsage(settings: DbSettings): StorageUsage = withContext(workDispatcher) {204 val downloads = files.directorySize(settings.downloadLocation.takeIf { it.isNotBlank() } ?: files.downloadRoot)205 val cache = files.directorySize(files.cacheRoot)206 val backups = files.directorySize(settings.autoBackupLocation ?: files.backupRoot)207 val local = settings.configuredLocalFolders().sumOf { files.directorySize(it.path) }208 StorageUsage(downloads = downloads, cache = cache, backups = backups, localFolders = local)209 }210}211