SyncSettingsViewModel.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/sync/SyncSettingsViewModel.kt
1package eu.friedcutlet.yokan.ui.screens.settings.sync23import androidx.lifecycle.ViewModel4import androidx.lifecycle.viewModelScope5import eu.friedcutlet.yokan.data.SettingsStore6import eu.friedcutlet.yokan.database.DbSettings7import eu.friedcutlet.yokan.database.DbSyncPreference8import eu.friedcutlet.yokan.database.DbSyncTriggerPreferences9import eu.friedcutlet.yokan.database.SyncServerProvider10import eu.friedcutlet.yokan.database.YokanDatabase11import eu.friedcutlet.yokan.services.backup.BackupOptions12import eu.friedcutlet.yokan.services.catchingNonCancellation13import eu.friedcutlet.yokan.services.http.HttpService14import eu.friedcutlet.yokan.services.http.normalizeHubServer15import eu.friedcutlet.yokan.services.notifications.NotificationService16import eu.friedcutlet.yokan.services.sync.BrowserLoginAttempt17import eu.friedcutlet.yokan.services.sync.CloudBackupSyncService18import eu.friedcutlet.yokan.services.sync.CloudProviderDescriptor19import eu.friedcutlet.yokan.services.sync.HubServerEntry20import eu.friedcutlet.yokan.services.sync.SyncResult21import eu.friedcutlet.yokan.services.sync.SyncService22import eu.friedcutlet.yokan.services.sync.fetchHubServers23import kotlinx.coroutines.flow.MutableStateFlow24import kotlinx.coroutines.flow.StateFlow25import kotlinx.coroutines.flow.asStateFlow26import kotlinx.coroutines.flow.distinctUntilChanged27import kotlinx.coroutines.flow.combine28import kotlinx.coroutines.flow.map29import kotlinx.coroutines.flow.update30import kotlinx.coroutines.Job31import kotlinx.coroutines.CancellationException32import kotlinx.coroutines.launch33import org.jetbrains.compose.resources.StringResource34import org.jetbrains.compose.resources.getString35import yokan.composeapp.generated.resources.Res36import yokan.composeapp.generated.resources.sync_cloud_restored37import yokan.composeapp.generated.resources.sync_cloud_uploaded38import yokan.composeapp.generated.resources.sync_device_id_copied39import yokan.composeapp.generated.resources.sync_enter_valid_client_id40import yokan.composeapp.generated.resources.sync_enter_valid_server41import yokan.composeapp.generated.resources.sync_logged_out42import yokan.composeapp.generated.resources.sync_operation_cloud_backup43import yokan.composeapp.generated.resources.sync_operation_cloud_restore44import yokan.composeapp.generated.resources.sync_operation_counts45import yokan.composeapp.generated.resources.sync_operation_download46import yokan.composeapp.generated.resources.sync_operation_failed47import yokan.composeapp.generated.resources.sync_operation_label_failed48import yokan.composeapp.generated.resources.sync_operation_result49import yokan.composeapp.generated.resources.sync_operation_sync50import yokan.composeapp.generated.resources.sync_operation_upload51import yokan.composeapp.generated.resources.sync_provider_change_failed52import yokan.composeapp.generated.resources.sync_provider_changed5354internal data class SyncSettingsState(55 val loginMessage: String? = null,56 val syncMessage: String? = null,57 val syncInProgress: Boolean = false,58 val externalOperationInProgress: Boolean = false,59 val pendingChanges: Int = 0,60 /** Servers published in the app's GitHub repository; empty until (or unless) the list loads. */61 val publishedServers: List<HubServerEntry> = emptyList(),62 /** Non-null while the hub's sign-in page is open in the in-app browser. */63 val browserLogin: BrowserLogin? = null,64) {65 val operationInProgress: Boolean get() = syncInProgress || externalOperationInProgress66}6768internal data class BrowserLogin(val attempt: BrowserLoginAttempt) {69 val server: String get() = attempt.server70 val url: String get() = attempt.url71}7273internal class SyncSettingsViewModel(74 private val sync: SyncService,75 private val cloudSync: CloudBackupSyncService,76 private val notifications: NotificationService,77 private val database: YokanDatabase,78 private val settings: SettingsStore,79 http: HttpService,80) : ViewModel() {81 val cloudProviders: List<CloudProviderDescriptor> = cloudSync.providers()8283 private val _state = MutableStateFlow(SyncSettingsState(pendingChanges = database.outbox().size))84 val state: StateFlow<SyncSettingsState> = _state.asStateFlow()85 private var browserCompletionJob: Job? = null86 private var browserCompletionGeneration = 0L8788 init {89 viewModelScope.launch {90 database.snapshots().map { it.outbox.size }.distinctUntilChanged().collect { pending ->91 _state.update { it.copy(pendingChanges = pending) }92 }93 }94 viewModelScope.launch {95 combine(sync.operationState, cloudSync.operationState) { server, cloud -> server.isActive || cloud.isActive }96 .distinctUntilChanged()97 .collect { active -> _state.update { it.copy(externalOperationInProgress = active) } }98 }99 viewModelScope.launch {100 val servers = fetchHubServers(http)101 _state.update { it.copy(publishedServers = servers) }102 }103 }104105 fun isCloudPreference(preference: DbSyncPreference): Boolean = cloudSync.isCloudPreference(preference)106107 fun requestNotificationPermission() = notifications.requestPermission()108109 fun login(syncId: Long, server: String, email: String, password: String) {110 if (_state.value.operationInProgress) return111 cancelBrowserLogin()112 runExclusive {113 val result = sync.login(syncId, server, email, password)114 if (result.success && database.syncPreferences().firstOrNull { it.syncId == syncId }?.serverProvider == SyncServerProvider.YokanHub) rememberServer(server)115 result.message116 }117 }118119 fun selectServerProvider(syncId: Long, provider: SyncServerProvider) {120 if (_state.value.operationInProgress) return121 val current = database.syncPreferences().firstOrNull { it.syncId == syncId } ?: DbSyncPreference(syncId = syncId)122 if (current.serverProvider == provider) return123 browserCompletionGeneration++124 cancelBrowserLogin()125 _state.update { it.copy(syncInProgress = true, loginMessage = null, syncMessage = null) }126 viewModelScope.launch {127 try {128 val result = catchingNonCancellation { sync.logout(syncId) }129 if (result.isSuccess) database.upsertSyncPreference(130 (database.syncPreferences().firstOrNull { it.syncId == syncId } ?: current).copy(131 serverProvider = provider,132 server = null,133 email = null,134 authToken = null,135 syncOn = false,136 autoSyncFrequency = 0,137 lastSyncManga = null,138 lastSyncHistory = null,139 lastSyncUpdate = null,140 hubHead = 0,141 hubEpoch = 0,142 hubHlc = 0,143 hubBootstrapComplete = false,144 hubRecoveryPending = false,145 deviceId = null,146 ),147 )148 val message = result.exceptionOrNull()?.message ?: getString(Res.string.sync_provider_changed)149 _state.update { it.copy(loginMessage = message) }150 } catch (cancelled: CancellationException) {151 throw cancelled152 } catch (error: Throwable) {153 val message = error.message ?: getString(Res.string.sync_provider_change_failed)154 _state.update { it.copy(loginMessage = message) }155 } finally {156 _state.update { it.copy(syncInProgress = false) }157 }158 }159 }160161 fun startBrowserLogin(syncId: Long, server: String) {162 if (_state.value.operationInProgress) return163 cancelBrowserLogin()164 val attempt = sync.beginBrowserLogin(syncId, server)165 if (attempt == null) {166 showLoginMessage(Res.string.sync_enter_valid_server)167 return168 }169 _state.update { it.copy(browserLogin = BrowserLogin(attempt), loginMessage = null) }170 }171172 /**173 * Google Drive consent URL for the user's own OAuth client, opened in the system browser (Google refuses embedded174 * web views). The pasted loopback address then completes sign-in through [login]; null when the client ID is invalid.175 */176 fun startGoogleDriveSignIn(syncId: Long, clientId: String): String? {177 if (_state.value.operationInProgress) return null178 val url = sync.beginBrowserLogin(syncId, clientId)?.url179 if (url == null) showLoginMessage(Res.string.sync_enter_valid_client_id) else _state.update { it.copy(loginMessage = null) }180 return url181 }182183 /** Every page the sign-in browser finishes loading, or the intercepted OAuth callback; the service decides which ends the flow. */184 fun browserNavigated(attempt: BrowserLoginAttempt, loadedUrl: String) {185 if (_state.value.browserLogin?.attempt !== attempt) return186 // With an intercepted callback, ordinary page loads can't finish the flow; skipping them keeps a187 // just-started no-op completion from swallowing the real callback below.188 if (attempt.callbackUrl != null && !loadedUrl.startsWith("${attempt.callbackUrl}?")) return189 if (browserCompletionJob?.isActive == true) return190 val generation = ++browserCompletionGeneration191 browserCompletionJob = viewModelScope.launch {192 _state.update { it.copy(syncInProgress = true) }193 try {194 val result = sync.completeBrowserLogin(attempt, loadedUrl) ?: return@launch195 if (_state.value.browserLogin?.attempt !== attempt) return@launch196 if (result.success && database.syncPreferences().firstOrNull { it.syncId == attempt.syncId }?.serverProvider == SyncServerProvider.YokanHub) {197 rememberServer(attempt.server)198 }199 if (!result.success) sync.cancelBrowserLogin(attempt)200 _state.update { it.copy(browserLogin = null, loginMessage = result.message) }201 } finally {202 if (browserCompletionGeneration == generation) _state.update { it.copy(syncInProgress = false) }203 }204 }205 }206207 fun cancelBrowserLogin(attempt: BrowserLoginAttempt? = _state.value.browserLogin?.attempt) {208 if (attempt != null && _state.value.browserLogin?.attempt !== attempt) {209 sync.cancelBrowserLogin(attempt)210 return211 }212 browserCompletionJob?.cancel()213 browserCompletionJob = null214 if (attempt != null) sync.cancelBrowserLogin(attempt)215 _state.update { current ->216 if (attempt == null || current.browserLogin?.attempt === attempt) current.copy(browserLogin = null) else current217 }218 }219220 fun removeCustomServer(url: String) = settings.updateDb { it.copy(customHubServers = it.customHubServers - url) }221222 fun setSyncTriggers(value: DbSyncTriggerPreferences) =223 settings.updateDb { it.copy(features = it.features.copy(syncTriggers = value)) }224225 /** Keeps a server the user typed in (and signed in to) in the dropdown; published ones are listed anyway. */226 private fun rememberServer(server: String) {227 val url = normalizeHubServer(server) ?: return228 if (_state.value.publishedServers.any { it.url == url }) return229 settings.updateDb { if (url in it.customHubServers) it else it.copy(customHubServers = it.customHubServers + url) }230 }231232 fun connectCloud(syncId: Long, providerId: String, accountLabel: String?, accessToken: String) {233 if (_state.value.operationInProgress) return234 runExclusive {235 val result = cloudSync.connect(syncId, providerId, accountLabel, accessToken)236 result.message237 }238 }239240 fun logout(syncId: Long) {241 if (_state.value.operationInProgress) return242 cancelBrowserLogin()243 runExclusive {244 sync.logout(syncId)245 getString(Res.string.sync_logged_out)246 }247 }248249 fun deviceIdCopied() {250 viewModelScope.launch {251 val message = getString(Res.string.sync_device_id_copied)252 _state.update { it.copy(syncMessage = message) }253 }254 }255256 fun syncNow(syncId: Long, settings: DbSettings) = runSync(Res.string.sync_operation_sync) { sync.sync(syncId, settings) }257258 fun uploadOnly(syncId: Long) = runSync(Res.string.sync_operation_upload) { sync.pushChanges(syncId) }259260 fun downloadOnly(syncId: Long) = runSync(Res.string.sync_operation_download) { sync.pullChanges(syncId) }261262 fun uploadCloudBackup(syncId: Long, settings: DbSettings) = runCloud(Res.string.sync_operation_cloud_backup) {263 val result = cloudSync.uploadBackup(syncId, BackupOptions(compressionLevel = settings.backupCompressionLevel ?: 6))264 getString(Res.string.sync_cloud_uploaded, result.itemCount, result.fileName)265 }266267 fun restoreCloudBackup(syncId: Long) = runCloud(Res.string.sync_operation_cloud_restore) {268 val result = cloudSync.restoreLatestBackup(syncId)269 getString(Res.string.sync_cloud_restored, result.preview.itemCount, result.fileName)270 }271272 private fun showLoginMessage(message: StringResource) {273 viewModelScope.launch {274 val text = getString(message)275 _state.update { it.copy(loginMessage = text) }276 }277 }278279 // Run a sync block, refresh, and report the upload/download counts. `label`280 // distinguishes full sync vs the upload-only / download-only flows added from the old app.281 private fun runSync(label: StringResource, block: suspend () -> SyncResult) = runExclusive {282 val name = getString(label)283 catchingNonCancellation { block() }284 .map { result ->285 if (result.errors.isEmpty()) {286 getString(Res.string.sync_operation_counts, name, result.uploadedChanges, result.downloadedChanges)287 } else {288 result.errors.joinToString(" • ")289 }290 }291 .getOrElse { error -> error.message ?: getString(Res.string.sync_operation_label_failed, name) }292 }293294 private fun runCloud(label: StringResource, block: suspend () -> String) = runExclusive {295 val name = getString(label)296 catchingNonCancellation { getString(Res.string.sync_operation_result, name, block()) }297 .getOrElse { error -> error.message ?: getString(Res.string.sync_operation_label_failed, name) }298 }299300 private fun runExclusive(block: suspend () -> String) {301 if (_state.value.operationInProgress) return302 _state.update { it.copy(syncInProgress = true) }303 viewModelScope.launch {304 try {305 val message = block()306 _state.update { it.copy(syncMessage = message) }307 } catch (cancelled: CancellationException) {308 throw cancelled309 } catch (error: Throwable) {310 val message = error.message ?: getString(Res.string.sync_operation_failed)311 _state.update { it.copy(syncMessage = message) }312 } finally {313 _state.update { it.copy(syncInProgress = false) }314 }315 }316 }317318 override fun onCleared() {319 cancelBrowserLogin()320 super.onCleared()321 }322}323