Yokan / rebuild
Course 1 8624561

SyncYomiSyncService.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/sync/SyncYomiSyncService.kt

implementation170 lines
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.database.DbSettings4import eu.friedcutlet.yokan.database.DbSyncPreference5import eu.friedcutlet.yokan.database.SyncServerProvider6import eu.friedcutlet.yokan.database.YokanDatabase7import eu.friedcutlet.yokan.database.sync.normalizeMangayomiServer8import eu.friedcutlet.yokan.services.backup.BackupFormat9import eu.friedcutlet.yokan.services.backup.BackupOptions10import eu.friedcutlet.yokan.services.backup.BackupService11import eu.friedcutlet.yokan.util.sha25612import eu.friedcutlet.yokan.services.http.HttpRequest13import eu.friedcutlet.yokan.services.http.HttpService14import eu.friedcutlet.yokan.services.http.header15import eu.friedcutlet.yokan.services.http.normalizeHubServer16import eu.friedcutlet.yokan.services.logging.AppLogger17import io.ktor.http.Url18import kotlinx.coroutines.currentCoroutineContext19import kotlinx.coroutines.ensureActive20import kotlinx.coroutines.sync.Mutex21import kotlinx.coroutines.sync.withLock2223/** `https://` assumed, lowercase scheme/host, no trailing slash; null unless a plain http(s) origin/path. */24internal fun normalizeSyncYomiHost(value: String): String? {25    val raw = normalizeHubServer(value)?.let(::normalizeMangayomiServer) ?: return null26    val url = runCatching { Url(raw) }.getOrNull() ?: return null27    if (url.protocol.name !in setOf("http", "https") || url.host.isBlank() || url.user != null || '?' in raw || '#' in raw) return null28    return raw29}3031/** Lease-key label for an API key: a short SHA-256 digest, so the key itself never leaves the preference. */32internal fun syncYomiKeyLabel(apiKey: String?): String =33    apiKey?.takeIf(String::isNotBlank)?.let { key ->34        sha256(key.encodeToByteArray()).copyOf(8).toHexString()35    }.orEmpty()3637/**38 * SyncYomi (`/api/sync/content`): one Tachiyomi-protobuf backup per API key. A run downloads it, merges it into the39 * library, and uploads the merged library under `If-Match`; a concurrent upload (412) restarts the run a bounded40 * number of times. Local data is only merged into, never replaced.41 */42class SyncYomiSyncService(43    private val database: YokanDatabase,44    private val backup: BackupService,45    private val http: HttpService,46    private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(),47    private val leases: SyncAccountLeases = SyncAccountLeases.None,48) : SyncService {49    override val operationState = operationMonitor.state50    private val operationMutex = Mutex()5152    /** [server] is the SyncYomi host, [password] the API key; [email] is unused. */53    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = operationMutex.withLock {54        val prior = preference(syncId)55        if (prior?.serverProvider != SyncServerProvider.SyncYomi) return@withLock SyncLoginResult(false, "SyncYomi is not the selected sync provider.")56        val host = normalizeSyncYomiHost(server) ?: return@withLock SyncLoginResult(false, "Enter a valid SyncYomi server URL.")57        val apiKey = password.trim().takeIf(String::isNotEmpty) ?: return@withLock SyncLoginResult(false, "API key is required.")58        val response = http.requestOrNull(HttpRequest(contentUrl(host), headers = mapOf(TokenHeader to apiKey)))59            ?: return@withLock SyncLoginResult(false, "Could not reach the SyncYomi server.")60        when (response.statusCode) {61            in 200..299, 404 -> Unit62            401, 403 -> return@withLock SyncLoginResult(false, "SyncYomi rejected the API key.")63            else -> return@withLock SyncLoginResult(false, "SyncYomi server returned HTTP ${response.statusCode}.")64        }65        currentCoroutineContext().ensureActive()66        val next = DbSyncPreference(server = host, authToken = apiKey, serverProvider = SyncServerProvider.SyncYomi)67        val failure = leases.commitClaimed(prior, next) {68            database.upsertSyncPreferenceIf(69                syncId = syncId,70                accepts = { it == prior },71                transform = { current ->72                    requireNotNull(current).copy(73                        server = host, email = null, authToken = apiKey, syncOn = true,74                        lastSyncManga = null, lastSyncHistory = null, lastSyncUpdate = null,75                    )76                },77            )78        }79        if (failure != null) SyncLoginResult(false, failure) else SyncLoginResult(true, "Connected to SyncYomi server.")80    }8182    override suspend fun logout(syncId: Long) = operationMutex.withLock {83        val pref = preference(syncId) ?: return@withLock84        database.upsertSyncPreferenceIf(syncId, accepts = { it != null }, transform = { requireNotNull(it).copy(authToken = null, syncOn = false) })85        leases.releaseQuietly(pref)86    }8788    override suspend fun sync(syncId: Long, settings: DbSettings) = run(SyncOperationStage.Syncing, syncId, push = true, pull = true)89    override suspend fun pushChanges(syncId: Long) = run(SyncOperationStage.Uploading, syncId, push = true, pull = false)90    override suspend fun pullChanges(syncId: Long) = run(SyncOperationStage.Downloading, syncId, push = false, pull = true)9192    override fun status(syncId: Long): SyncConnectionStatus {93        val pref = preference(syncId)94        return SyncConnectionStatus(!pref?.authToken.isNullOrBlank(), pref?.email, pref?.server, pref?.lastSyncManga)95    }9697    private suspend fun run(stage: SyncOperationStage, syncId: Long, push: Boolean, pull: Boolean): SyncResult =98        runStateSync(operationMonitor, operationMutex, stage, "SyncYomi") { perform(syncId, push, pull) }99100    private suspend fun perform(syncId: Long, push: Boolean, pull: Boolean): SyncResult {101        val captured = preference(syncId) ?: return stateSyncFailure("No sync configuration.")102        if (captured.serverProvider != SyncServerProvider.SyncYomi) return stateSyncFailure("SyncYomi is not the selected sync provider.")103        val host = captured.server?.let(::normalizeSyncYomiHost) ?: return stateSyncFailure("Invalid SyncYomi server URL.")104        val apiKey = captured.authToken?.takeIf(String::isNotBlank) ?: return stateSyncFailure("Not logged in.")105        leases.claimFailure(captured)?.let { return stateSyncFailure(it) }106        var downloaded = 0107        repeat(MaxAttempts) {108            database.checkSyncAccount(captured)109            // Always a full GET: the ETag it returns is the If-Match precondition of this run's upload.110            val remote = http.requestOrNull(HttpRequest(contentUrl(host), headers = mapOf(TokenHeader to apiKey)))111                ?: throw StateSyncException("Could not reach the SyncYomi server.")112            database.checkSyncAccount(captured)113            val etag = when (remote.statusCode) {114                404 -> null115                in 200..299 -> remote.headers.header("ETag") ?: throw StateSyncException("SyncYomi server response is missing its ETag.")116                else -> throw httpFailure(remote.statusCode)117            }118            if (pull && etag != null) {119                // Unreadable remote content is overwritten below, as upstream SyncYomi clients do.120                downloaded += backup.mergeRemoteState(remote.bodyBytes, captured, "SyncYomi") ?: 0121            }122            if (!push) {123                database.recordStateSync(captured)124                return SyncResult(0, downloaded, settingsSynced = false)125            }126            val export = backup.exportBackup(127                BackupOptions(128                    includeHistory = captured.syncHistories,129                    includeUpdates = captured.syncUpdates,130                    includeSettings = false,131                    compressionLevel = 0,132                    format = BackupFormat.Tachiyomi,133                    includePrivateNotes = false,134                ),135            )136            if (export.bytes.isEmpty()) throw StateSyncException("Nothing to upload to SyncYomi.")137            database.checkSyncAccount(captured)138            val headers = buildMap {139                put(TokenHeader, apiKey)140                put("Content-Type", "application/octet-stream")141                etag?.let { put("If-Match", it) }142            }143            val upload = http.requestOrNull(HttpRequest(contentUrl(host), "PUT", headers, bodyBytes = export.bytes))144                ?: throw StateSyncException("Could not reach the SyncYomi server.")145            when (upload.statusCode) {146                in 200..299 -> {147                    database.recordStateSync(captured)148                    return SyncResult(export.itemCount, downloaded, settingsSynced = false)149                }150                412 -> AppLogger.info("[sync] SyncYomi data changed during upload; restarting sync")151                else -> throw httpFailure(upload.statusCode)152            }153        }154        return stateSyncFailure("SyncYomi data kept changing on the server during sync; try again later.")155    }156157    private fun httpFailure(status: Int) = StateSyncException(158        if (status == 401 || status == 403) "SyncYomi rejected the API key; sign in again." else "SyncYomi server returned HTTP $status.",159    )160161    private fun preference(id: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == id }162163    private companion object {164        const val TokenHeader = "X-API-Token"165        /** Full pull/merge/push passes before a persistent 412 is reported as a conflict. */166        const val MaxAttempts = 3167168        fun contentUrl(host: String) = "$host/api/sync/content"169    }170}171

Search chapters, reference and source filenames.