package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.database.DbSettings 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.backup.BackupFormat import eu.friedcutlet.yokan.services.backup.BackupOptions import eu.friedcutlet.yokan.services.backup.BackupService import eu.friedcutlet.yokan.util.sha256 import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.header import eu.friedcutlet.yokan.services.http.normalizeHubServer import eu.friedcutlet.yokan.services.logging.AppLogger import io.ktor.http.Url import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock /** `https://` assumed, lowercase scheme/host, no trailing slash; null unless a plain http(s) origin/path. */ internal fun normalizeSyncYomiHost(value: String): String? { val raw = normalizeHubServer(value)?.let(::normalizeMangayomiServer) ?: return null val url = runCatching { Url(raw) }.getOrNull() ?: return null if (url.protocol.name !in setOf("http", "https") || url.host.isBlank() || url.user != null || '?' in raw || '#' in raw) return null return raw } /** Lease-key label for an API key: a short SHA-256 digest, so the key itself never leaves the preference. */ internal fun syncYomiKeyLabel(apiKey: String?): String = apiKey?.takeIf(String::isNotBlank)?.let { key -> sha256(key.encodeToByteArray()).copyOf(8).toHexString() }.orEmpty() /** * SyncYomi (`/api/sync/content`): one Tachiyomi-protobuf backup per API key. A run downloads it, merges it into the * library, and uploads the merged library under `If-Match`; a concurrent upload (412) restarts the run a bounded * number of times. Local data is only merged into, never replaced. */ class SyncYomiSyncService( private val database: YokanDatabase, private val backup: BackupService, private val http: HttpService, private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(), private val leases: SyncAccountLeases = SyncAccountLeases.None, ) : SyncService { override val operationState = operationMonitor.state private val operationMutex = Mutex() /** [server] is the SyncYomi host, [password] the API key; [email] is unused. */ override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = operationMutex.withLock { val prior = preference(syncId) if (prior?.serverProvider != SyncServerProvider.SyncYomi) return@withLock SyncLoginResult(false, "SyncYomi is not the selected sync provider.") val host = normalizeSyncYomiHost(server) ?: return@withLock SyncLoginResult(false, "Enter a valid SyncYomi server URL.") val apiKey = password.trim().takeIf(String::isNotEmpty) ?: return@withLock SyncLoginResult(false, "API key is required.") val response = http.requestOrNull(HttpRequest(contentUrl(host), headers = mapOf(TokenHeader to apiKey))) ?: return@withLock SyncLoginResult(false, "Could not reach the SyncYomi server.") when (response.statusCode) { in 200..299, 404 -> Unit 401, 403 -> return@withLock SyncLoginResult(false, "SyncYomi rejected the API key.") else -> return@withLock SyncLoginResult(false, "SyncYomi server returned HTTP ${response.statusCode}.") } currentCoroutineContext().ensureActive() val next = DbSyncPreference(server = host, authToken = apiKey, serverProvider = SyncServerProvider.SyncYomi) val failure = leases.commitClaimed(prior, next) { database.upsertSyncPreferenceIf( syncId = syncId, accepts = { it == prior }, transform = { current -> requireNotNull(current).copy( server = host, email = null, authToken = apiKey, syncOn = true, lastSyncManga = null, lastSyncHistory = null, lastSyncUpdate = null, ) }, ) } if (failure != null) SyncLoginResult(false, failure) else SyncLoginResult(true, "Connected to SyncYomi server.") } override suspend fun logout(syncId: Long) = operationMutex.withLock { val pref = preference(syncId) ?: return@withLock database.upsertSyncPreferenceIf(syncId, accepts = { it != null }, transform = { requireNotNull(it).copy(authToken = null, syncOn = false) }) leases.releaseQuietly(pref) } override suspend fun sync(syncId: Long, settings: DbSettings) = run(SyncOperationStage.Syncing, syncId, push = true, pull = true) override suspend fun pushChanges(syncId: Long) = run(SyncOperationStage.Uploading, syncId, push = true, pull = false) override suspend fun pullChanges(syncId: Long) = run(SyncOperationStage.Downloading, syncId, push = false, pull = true) override fun status(syncId: Long): SyncConnectionStatus { val pref = preference(syncId) return SyncConnectionStatus(!pref?.authToken.isNullOrBlank(), pref?.email, pref?.server, pref?.lastSyncManga) } private suspend fun run(stage: SyncOperationStage, syncId: Long, push: Boolean, pull: Boolean): SyncResult = runStateSync(operationMonitor, operationMutex, stage, "SyncYomi") { perform(syncId, push, pull) } private suspend fun perform(syncId: Long, push: Boolean, pull: Boolean): SyncResult { val captured = preference(syncId) ?: return stateSyncFailure("No sync configuration.") if (captured.serverProvider != SyncServerProvider.SyncYomi) return stateSyncFailure("SyncYomi is not the selected sync provider.") val host = captured.server?.let(::normalizeSyncYomiHost) ?: return stateSyncFailure("Invalid SyncYomi server URL.") val apiKey = captured.authToken?.takeIf(String::isNotBlank) ?: return stateSyncFailure("Not logged in.") leases.claimFailure(captured)?.let { return stateSyncFailure(it) } var downloaded = 0 repeat(MaxAttempts) { database.checkSyncAccount(captured) // Always a full GET: the ETag it returns is the If-Match precondition of this run's upload. val remote = http.requestOrNull(HttpRequest(contentUrl(host), headers = mapOf(TokenHeader to apiKey))) ?: throw StateSyncException("Could not reach the SyncYomi server.") database.checkSyncAccount(captured) val etag = when (remote.statusCode) { 404 -> null in 200..299 -> remote.headers.header("ETag") ?: throw StateSyncException("SyncYomi server response is missing its ETag.") else -> throw httpFailure(remote.statusCode) } if (pull && etag != null) { // Unreadable remote content is overwritten below, as upstream SyncYomi clients do. downloaded += backup.mergeRemoteState(remote.bodyBytes, captured, "SyncYomi") ?: 0 } if (!push) { database.recordStateSync(captured) return SyncResult(0, downloaded, settingsSynced = false) } val export = backup.exportBackup( BackupOptions( includeHistory = captured.syncHistories, includeUpdates = captured.syncUpdates, includeSettings = false, compressionLevel = 0, format = BackupFormat.Tachiyomi, includePrivateNotes = false, ), ) if (export.bytes.isEmpty()) throw StateSyncException("Nothing to upload to SyncYomi.") database.checkSyncAccount(captured) val headers = buildMap { put(TokenHeader, apiKey) put("Content-Type", "application/octet-stream") etag?.let { put("If-Match", it) } } val upload = http.requestOrNull(HttpRequest(contentUrl(host), "PUT", headers, bodyBytes = export.bytes)) ?: throw StateSyncException("Could not reach the SyncYomi server.") when (upload.statusCode) { in 200..299 -> { database.recordStateSync(captured) return SyncResult(export.itemCount, downloaded, settingsSynced = false) } 412 -> AppLogger.info("[sync] SyncYomi data changed during upload; restarting sync") else -> throw httpFailure(upload.statusCode) } } return stateSyncFailure("SyncYomi data kept changing on the server during sync; try again later.") } private fun httpFailure(status: Int) = StateSyncException( if (status == 401 || status == 403) "SyncYomi rejected the API key; sign in again." else "SyncYomi server returned HTTP $status.", ) private fun preference(id: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == id } private companion object { const val TokenHeader = "X-API-Token" /** Full pull/merge/push passes before a persistent 412 is reported as a conflict. */ const val MaxAttempts = 3 fun contentUrl(host: String) = "$host/api/sync/content" } }