package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.services.backup.BackupOptions import eu.friedcutlet.yokan.services.backup.RestorePreview import eu.friedcutlet.yokan.util.PlatformLock import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update enum class SyncOperationStage { Syncing, Uploading, Downloading, } enum class SyncOperationOutcome { Succeeded, Failed, Cancelled, } data class SyncOperationState( val activeCount: Int = 0, val stage: SyncOperationStage? = null, val lastOutcome: SyncOperationOutcome? = null, /** 0..1 while a multi-page pull reports how far it got; null when unknown. */ val progress: Float? = null, ) { val isActive: Boolean get() = activeCount > 0 } /** Shared operation tracker used by manual, scheduled, outbox, and live sync paths. */ class SyncOperationMonitor { private val lock = PlatformLock() private val active = linkedMapOf() private var nextId = 0L private val _state = MutableStateFlow(SyncOperationState()) val state: StateFlow = _state.asStateFlow() fun begin(stage: SyncOperationStage): Long = lock.withLock { val id = ++nextId active[id] = stage _state.update { current -> current.copy(activeCount = active.size, stage = stage, progress = null) } id } fun progress(id: Long, fraction: Float) = lock.withLock { if (id !in active) return@withLock _state.update { it.copy(progress = fraction.coerceIn(0f, 1f)) } } fun finish(id: Long, outcome: SyncOperationOutcome) = lock.withLock { if (active.remove(id) == null) return@withLock _state.update { current -> current.copy( activeCount = active.size, stage = active.values.lastOrNull(), lastOutcome = outcome, progress = null, ) } } } private val IdleSyncOperationState = MutableStateFlow(SyncOperationState()) interface SyncService { val operationState: StateFlow get() = IdleSyncOperationState suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? = null suspend fun completeBrowserLogin(attempt: BrowserLoginAttempt, loadedUrl: String): SyncLoginResult? = null fun cancelBrowserLogin(attempt: BrowserLoginAttempt) = Unit suspend fun logout(syncId: Long) suspend fun sync(syncId: Long, settings: DbSettings): SyncResult suspend fun pushChanges(syncId: Long): SyncResult suspend fun pullChanges(syncId: Long): SyncResult fun status(syncId: Long): SyncConnectionStatus fun close() = Unit /** Wait for owned calls and their finalizers before releasing transport resources. */ suspend fun closeAndJoin() { close() } } /** Immutable, service-owned identity for one browser login, including its one-use CSRF state. */ @ConsistentCopyVisibility data class BrowserLoginAttempt internal constructor( val syncId: Long, val server: String, val url: String, val device: String, val state: String, /** Redirect target the browser must intercept rather than load (OAuth loopback); null when the flow ends on a real page. */ val callbackUrl: String? = null, ) interface CloudStorageProvider { val descriptor: CloudProviderDescriptor suspend fun validate(connection: CloudConnection): CloudConnectionStatus suspend fun putObject( connection: CloudConnection, key: String, bytes: ByteArray, contentType: String, ): CloudObject suspend fun listObjects(connection: CloudConnection, prefix: String): List suspend fun getObject(connection: CloudConnection, objectRef: CloudObject): ByteArray } class CloudStorageException(message: String) : RuntimeException(message) interface CloudBackupSyncService : SyncService { fun providers(): List fun isCloudPreference(syncPreference: eu.friedcutlet.yokan.database.DbSyncPreference?): Boolean suspend fun connect(syncId: Long, providerId: String, accountLabel: String?, accessToken: String): SyncLoginResult suspend fun uploadBackup(syncId: Long, options: BackupOptions): CloudBackupResult suspend fun restoreLatestBackup(syncId: Long): CloudBackupRestoreResult } data class SyncResult( val uploadedChanges: Int, val downloadedChanges: Int, val settingsSynced: Boolean, val errors: List = emptyList(), ) data class SyncLoginResult( val success: Boolean, val message: String, ) data class SyncConnectionStatus( val loggedIn: Boolean, val email: String?, val server: String?, val lastSyncMillis: Long?, ) data class CloudProviderDescriptor( val id: String, val displayName: String, val description: String, val authInstructions: String, ) data class CloudConnection( val providerId: String, val accountLabel: String?, val accessToken: String, ) data class CloudConnectionStatus( val connected: Boolean, val accountLabel: String? = null, val message: String = "", ) data class CloudObject( val key: String, val displayName: String, val sizeBytes: Long, val modifiedAtMillis: Long, val providerFileId: String? = null, ) data class CloudBackupResult( val providerId: String, val fileName: String, val itemCount: Int, val bytesUploaded: Long, val remoteObject: CloudObject, ) data class CloudBackupRestoreResult( val providerId: String, val fileName: String, val preview: RestorePreview, )