package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbSyncPreference import eu.friedcutlet.yokan.database.SyncServerProvider import eu.friedcutlet.yokan.database.YokanDatabase import eu.friedcutlet.yokan.database.sync.normalizeMangayomiServer import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.http.normalizeHubServer import eu.friedcutlet.yokan.services.logging.AppLogger import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Device-wide ownership of remote sync accounts, so two profiles never sync into one library. * [claim] throws with a user-facing message when another profile holds [key]. */ interface SyncAccountLeases { suspend fun claim(key: String) suspend fun release(key: String) companion object { /** Single-profile hosts and tests: every claim succeeds. */ val None = object : SyncAccountLeases { override suspend fun claim(key: String) = Unit override suspend fun release(key: String) = Unit } } } /** * Lease key of a configured account (signed in or not). Account names are trimmed and lowercased, so one * account is one key as far as the stored name allows (Mangayomi password logins store the typed email, * OAuth the server username: the same account reached both ways yields two keys). A blank account name * still leases the server, so only one profile may use an unnamed account there. */ internal fun syncLeaseKey(preference: DbSyncPreference?): String? { val server = preference?.server ?: return null val account = preference.email.orEmpty().trim() val key = when { // SyncYomi has no account name: the API key selects the account, so lease by its digest, never the raw key. preference.serverProvider == SyncServerProvider.SyncYomi -> "syncyomi|${normalizeSyncYomiHost(server) ?: return null}|${syncYomiKeyLabel(preference.authToken)}" // Google Drive state sync keeps the user's OAuth client id in `server`. preference.serverProvider == SyncServerProvider.GoogleDrive -> "gdrive|${server.trim().takeIf(String::isNotEmpty) ?: return null}|$account" server.startsWith(CloudServerPrefix) -> "cloud|${providerIdFromServer(server) ?: return null}|$account" preference.serverProvider == SyncServerProvider.Mangayomi -> "mangayomi|${normalizeMangayomiServer(server) ?: return null}|$account" else -> "hub|${normalizeHubServer(server) ?: return null}|$account" } return key.lowercase() } private fun DbSyncPreference?.signedIn() = !this?.authToken.isNullOrBlank() && syncLeaseKey(this) != null /** Claims [preference]'s account if signed in; the failure message, or null when this profile may use it. */ internal suspend fun SyncAccountLeases.claimFailure(preference: DbSyncPreference?): String? { if (!preference.signedIn()) return null val key = syncLeaseKey(preference) ?: return null return try { claim(key); null } catch (cancelled: CancellationException) { throw cancelled } catch (error: Exception) { error.message ?: "Could not reserve this sync account for this profile." } } /** * Adopts the account a profile already uses (e.g. Default's pre-lease login) as soon as it opens. A conflict * is only logged; every sync operation re-checks the lease and reports it as its error. */ internal fun adoptConfiguredSyncAccount(leases: SyncAccountLeases, database: YokanDatabase, scope: CoroutineScope) { scope.launch { catchingNonCancellation { leases.claimFailure(database.syncPreferences().firstOrNull()) } .getOrNull()?.let { AppLogger.warn("[sync] $it") } } } /** Best effort: a failed release only keeps the account reserved for this profile until its next logout/delete. */ internal suspend fun SyncAccountLeases.releaseQuietly(preference: DbSyncPreference?) { val key = syncLeaseKey(preference) ?: return try { withContext(NonCancellable) { release(key) } } catch (_: Exception) { } } /** * Claims [next]'s account right before the guarded credential [commit]. A rejected commit hands the lease * back to [previous]'s account (or releases it). Returns null once committed, else the message to show. */ internal suspend fun SyncAccountLeases.commitClaimed( previous: DbSyncPreference?, next: DbSyncPreference, commit: suspend () -> Boolean, ): String? { claimFailure(next)?.let { return it } var committed = false try { committed = commit() } finally { if (!committed) withContext(NonCancellable) { if (!previous.signedIn() || claimFailure(previous) != null) releaseQuietly(next) } } return if (committed) null else "Sync configuration changed during login; try again." }