package eu.friedcutlet.yokan.services.sync import dev.whyoleg.cryptography.DelicateCryptographyApi import dev.whyoleg.cryptography.random.CryptographyRandom 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.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.HttpResponse import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.tracking.callbackParameter import eu.friedcutlet.yokan.util.PlatformLock import eu.friedcutlet.yokan.util.nowMillis import io.ktor.http.URLBuilder import io.ktor.http.formUrlEncode import kotlin.io.encoding.Base64 import kotlin.time.Instant import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.put /** Loopback redirect of a Google "Desktop app" OAuth client; the browser fails to load it and the user copies the URL. */ internal const val GoogleDriveRedirectUri = "http://127.0.0.1" internal const val GoogleDriveScope = "https://www.googleapis.com/auth/drive.appdata" /** Authorization-code + PKCE (S256) URL for the user's own OAuth client. */ internal fun googleDriveAuthorizationUrl(clientId: String, verifier: String, state: String): String = URLBuilder("https://accounts.google.com/o/oauth2/v2/auth").apply { parameters.append("client_id", clientId) parameters.append("redirect_uri", GoogleDriveRedirectUri) parameters.append("response_type", "code") parameters.append("scope", GoogleDriveScope) parameters.append("access_type", "offline") parameters.append("prompt", "consent") parameters.append("code_challenge", pkceChallenge(verifier)) parameters.append("code_challenge_method", "S256") parameters.append("state", state) }.build().toString() internal fun pkceChallenge(verifier: String): String = base64Url(sha256(verifier.encodeToByteArray())) private fun base64Url(bytes: ByteArray) = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).encode(bytes) /** Epoch millis of an ISO-8601 instant, or null when [value] is not one. */ internal fun parseInstantMillis(value: String): Long? = runCatching { Instant.parse(value).toEpochMilliseconds() }.getOrNull() /** Stored in [DbSyncPreference.authToken]; the client id lives in `server`, the account email in `email`. */ @Serializable private data class GoogleDriveCredential(val clientSecret: String = "", val refreshToken: String) /** * Application-state sync through one file in the Drive `appDataFolder` of the user's own OAuth client * (independent of the `cloud://google-drive` backup path). A run takes a lock file, merges the sync file * when another device wrote it, uploads the merged library, and always releases the lock. */ class GoogleDriveSyncService( private val database: YokanDatabase, private val backup: BackupService, private val http: HttpService, private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(), private val leases: SyncAccountLeases = SyncAccountLeases.None, private val clock: () -> Long = ::nowMillis, ) : SyncService { override val operationState = operationMonitor.state private val operationMutex = Mutex() private val json = Json { ignoreUnknownKeys = true } private val authLock = PlatformLock() private val pendingAuth = mutableMapOf() private class PendingAuth(val clientId: String, val verifier: String, val state: String) private class DriveFile(val id: String, val createdMillis: Long, val modifiedMillis: Long, val properties: Map) { val deviceId: String? get() = properties["deviceId"] val expiresAt: Long get() = properties["expiresAt"]?.toLongOrNull() ?: 0L } /** [server] is the user's OAuth client id; the returned URL is opened in the system browser. */ @OptIn(DelicateCryptographyApi::class) override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? { val clientId = server.trim().takeIf { it.isNotEmpty() && it.length <= 256 && it.none(Char::isWhitespace) } ?: return null if (preference(syncId)?.serverProvider != SyncServerProvider.GoogleDrive) return null val verifier = base64Url(CryptographyRandom.Default.nextBytes(32)) val state = base64Url(CryptographyRandom.Default.nextBytes(24)) authLock.withLock { pendingAuth[syncId] = PendingAuth(clientId, verifier, state) } return BrowserLoginAttempt(syncId, clientId, googleDriveAuthorizationUrl(clientId, verifier, state), device = "", state = state) } override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) { authLock.withLock { if (pendingAuth[attempt.syncId]?.state == attempt.state) pendingAuth.remove(attempt.syncId) } } /** * Completes the sign-in begun by [beginBrowserLogin]: [server] is the OAuth client id, [email] its client secret, * [password] the pasted loopback URL (or bare code) the browser ended on. */ override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = operationMutex.withLock { val clientId = server.trim() val pending = authLock.withLock { pendingAuth[syncId]?.takeIf { it.clientId == clientId }?.also { pendingAuth.remove(syncId) } } ?: return@withLock SyncLoginResult(false, "Open the Google sign-in page for this client ID first.") val prior = preference(syncId) if (prior == null || prior.serverProvider != SyncServerProvider.GoogleDrive) return@withLock SyncLoginResult(false, "Google Drive is not the selected sync provider.") val pasted = password.trim() if (pasted.length > 4096 || "error=" in pasted) return@withLock SyncLoginResult(false, "Google sign-in was not completed.") if ("state=" in pasted && callbackParameter(pasted, "state") != pending.state) { return@withLock SyncLoginResult(false, "This sign-in address belongs to another attempt; open the sign-in page again.") } val code = callbackParameter(pasted, "code").takeIf { it.isNotEmpty() && it.length <= 1024 && it.none(Char::isWhitespace) && "://" !in it } ?: return@withLock SyncLoginResult(false, "Paste the address the browser opened after sign-in, or its code.") val secret = email.trim() try { val token = tokenRequest(clientId, secret, listOf( "code" to code, "redirect_uri" to GoogleDriveRedirectUri, "grant_type" to "authorization_code", "code_verifier" to pending.verifier, )) val refreshToken = token.string("refresh_token") ?: throw StateSyncException("Google returned no refresh token; remove Yokan's access in your Google account and sign in again.") val accessToken = token.string("access_token") ?: throw StateSyncException("Google returned an invalid token response.") val user = driveJson(HttpRequest("$DriveApi/about?fields=user(emailAddress,displayName)", headers = bearer(accessToken)), "account lookup")["user"] as? JsonObject val account = user?.string("emailAddress") ?: user?.string("displayName") currentCoroutineContext().ensureActive() val credential = json.encodeToString(GoogleDriveCredential.serializer(), GoogleDriveCredential(secret, refreshToken)) val deviceId = prior.deviceId?.takeIf(String::isNotBlank) ?: newDeviceId() val next = DbSyncPreference(server = clientId, email = account, authToken = credential, serverProvider = SyncServerProvider.GoogleDrive) val failure = leases.commitClaimed(prior, next) { database.upsertSyncPreferenceIf( syncId = syncId, accepts = { it == prior }, transform = { current -> requireNotNull(current).copy( server = clientId, email = account, authToken = credential, syncOn = true, deviceId = deviceId, lastSyncManga = null, lastSyncHistory = null, lastSyncUpdate = null, ) }, ) } if (failure != null) SyncLoginResult(false, failure) else SyncLoginResult(true, "Connected to Google Drive${account?.let { " as $it" }.orEmpty()}.") } catch (error: StateSyncException) { SyncLoginResult(false, error.message ?: "Google sign-in failed.") } } 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, "Google Drive", pref?.lastSyncManga) } private suspend fun run(stage: SyncOperationStage, syncId: Long, push: Boolean, pull: Boolean): SyncResult = runStateSync(operationMonitor, operationMutex, stage, "Google Drive") { 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.GoogleDrive) return stateSyncFailure("Google Drive is not the selected sync provider.") val clientId = captured.server?.trim()?.takeIf(String::isNotEmpty) ?: return stateSyncFailure("Google OAuth client ID is missing.") val credential = captured.authToken?.let { runCatching { json.decodeFromString(GoogleDriveCredential.serializer(), it) }.getOrNull() } ?: return stateSyncFailure("Not signed in to Google Drive.") val deviceId = captured.deviceId?.takeIf(String::isNotBlank) ?: return stateSyncFailure("Sign in to Google Drive again.") leases.claimFailure(captured)?.let { return stateSyncFailure(it) } val accessToken = tokenRequest(clientId, credential.clientSecret, listOf("refresh_token" to credential.refreshToken, "grant_type" to "refresh_token")) .string("access_token") ?: throw StateSyncException("Google returned an invalid token response.") database.checkSyncAccount(captured) val lockId = acquireLock(accessToken, deviceId) try { database.checkSyncAccount(captured) val remote = listFiles(accessToken, SyncFileName).maxByOrNull { it.modifiedMillis } var downloaded = 0 // Our own last upload holds nothing new; another device's file is merged in, never replacing local data. if (pull && remote != null && remote.deviceId != deviceId) { val bytes = drive(HttpRequest("$DriveApi/files/${remote.id}?alt=media", headers = bearer(accessToken)), "download").bodyBytes database.checkSyncAccount(captured) downloaded = backup.mergeRemoteState(bytes, captured, "Google Drive") ?: 0 } var uploaded = 0 if (push) { val export = backup.exportBackup( BackupOptions( includeHistory = captured.syncHistories, includeUpdates = captured.syncUpdates, includeSettings = captured.syncSettings, compressionLevel = 6, format = BackupFormat.Yokan, includePrivateNotes = false, ), ) database.checkSyncAccount(captured) upload(accessToken, remote?.id, deviceId, export.bytes, export.contentType) uploaded = export.itemCount } database.recordStateSync(captured) return SyncResult(uploaded, downloaded, settingsSynced = push && captured.syncSettings) } finally { withContext(NonCancellable) { runCatching { deleteFile(accessToken, lockId) } .onFailure { AppLogger.warn("[sync] Google Drive lock release failed; it expires on its own") } } } } /** * Takes the `appDataFolder` lock: expired locks are removed, a live lock of another device refuses the run, * and when two devices create locks at once (Drive allows duplicate names) the later one backs off. */ private suspend fun acquireLock(accessToken: String, deviceId: String): String { val now = clock() val (stale, live) = listFiles(accessToken, LockFileName).partition { it.expiresAt <= now } stale.forEach { deleteFile(accessToken, it.id) } if (live.any { it.deviceId != deviceId }) throw StateSyncException(BusyMessage) live.forEach { deleteFile(accessToken, it.id) } // Left behind by an interrupted run on this device. val metadata = buildJsonObject { put("name", LockFileName) put("parents", JsonArray(listOf(JsonPrimitive("appDataFolder")))) put("appProperties", buildJsonObject { put("deviceId", deviceId); put("expiresAt", (now + LockTtlMillis).toString()) }) } val created = driveJson( HttpRequest("$DriveApi/files?fields=id,createdTime", "POST", bearer(accessToken) + ("Content-Type" to "application/json"), metadata.toString()), "lock", ) val lockId = created.string("id") ?: throw StateSyncException("Google Drive returned an invalid lock file.") val mine = created.string("createdTime")?.let(::parseInstantMillis) ?: now val rival = listFiles(accessToken, LockFileName).any { it.id != lockId && it.deviceId != deviceId && it.expiresAt > now && (it.createdMillis < mine || (it.createdMillis == mine && it.id < lockId)) } if (rival) { withContext(NonCancellable) { runCatching { deleteFile(accessToken, lockId) } } throw StateSyncException(BusyMessage) } return lockId } private suspend fun upload(accessToken: String, fileId: String?, deviceId: String, bytes: ByteArray, contentType: String) { val metadata = buildJsonObject { if (fileId == null) { put("name", SyncFileName) put("parents", JsonArray(listOf(JsonPrimitive("appDataFolder")))) } put("appProperties", buildJsonObject { put("deviceId", deviceId) }) } val boundary = "yokan-sync-${clock()}" val url = if (fileId == null) "$DriveUpload/files?uploadType=multipart&fields=id" else "$DriveUpload/files/$fileId?uploadType=multipart&fields=id" drive( HttpRequest( url, if (fileId == null) "POST" else "PATCH", bearer(accessToken) + ("Content-Type" to "multipart/related; boundary=$boundary"), bodyBytes = multipartRelated(boundary, metadata.toString(), contentType, bytes), ), "upload", ) } private suspend fun listFiles(accessToken: String, name: String): List { val url = URLBuilder("$DriveApi/files").apply { parameters.append("spaces", "appDataFolder") parameters.append("q", "name = '$name' and trashed = false") parameters.append("fields", "files(id,createdTime,modifiedTime,appProperties)") }.build().toString() val files = driveJson(HttpRequest(url, headers = bearer(accessToken)), "list")["files"] as? JsonArray ?: return emptyList() return files.mapNotNull { element -> val file = element as? JsonObject ?: return@mapNotNull null val id = file.string("id") ?: return@mapNotNull null val properties = (file["appProperties"] as? JsonObject)?.mapNotNull { (key, value) -> (value as? JsonPrimitive)?.contentOrNull?.let { key to it } }?.toMap().orEmpty() DriveFile(id, file.string("createdTime")?.let(::parseInstantMillis) ?: 0L, file.string("modifiedTime")?.let(::parseInstantMillis) ?: 0L, properties) } } private suspend fun deleteFile(accessToken: String, id: String) { val response = http.requestOrNull(HttpRequest("$DriveApi/files/$id", "DELETE", bearer(accessToken))) ?: throw StateSyncException("Could not reach Google Drive.") if (response.statusCode != 404 && response.statusCode !in 200..299) throw driveFailure(response, "delete") } private suspend fun drive(request: HttpRequest, action: String): HttpResponse { val response = http.requestOrNull(request) ?: throw StateSyncException("Could not reach Google Drive.") if (response.statusCode !in 200..299) throw driveFailure(response, action) return response } private suspend fun driveJson(request: HttpRequest, action: String): JsonObject { val body = drive(request, action).body return runCatching { json.parseToJsonElement(body).jsonObject }.getOrNull() ?: throw StateSyncException("Google Drive returned an invalid $action response.") } private fun driveFailure(response: HttpResponse, action: String) = StateSyncException( if (response.statusCode == 401) "Google Drive rejected the sign-in; sign in again." else "Google Drive $action failed with HTTP ${response.statusCode}.", ) /** Token endpoint call (code exchange or refresh); the client secret is sent when the user entered one. */ private suspend fun tokenRequest(clientId: String, clientSecret: String, form: List>): JsonObject { val fields = listOf("client_id" to clientId) + listOfNotNull(clientSecret.takeIf(String::isNotBlank)?.let { "client_secret" to it }) + form val response = http.requestOrNull( HttpRequest(TokenUrl, "POST", mapOf("Content-Type" to "application/x-www-form-urlencoded", "Accept" to "application/json"), fields.formUrlEncode()), ) ?: throw StateSyncException("Could not reach Google.") val body = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull() if (response.statusCode !in 200..299) throw StateSyncException( when (body?.string("error")) { "invalid_grant" -> "Google sign-in expired or was revoked; sign in to Google Drive again." "invalid_client", "unauthorized_client" -> "Google rejected the OAuth client ID or secret." else -> "Google token request failed with HTTP ${response.statusCode}." }, ) return body ?: throw StateSyncException("Google returned an invalid token response.") } private fun bearer(accessToken: String) = mapOf("Authorization" to "Bearer $accessToken", "Accept" to "application/json") private fun preference(id: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == id } @OptIn(DelicateCryptographyApi::class) private fun newDeviceId(): String = CryptographyRandom.Default.nextBytes(16).toHexString() private fun JsonObject.string(key: String): String? = (this[key] as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf(String::isNotEmpty) internal companion object { const val SyncFileName = "yokan_sync.json.gz" const val LockFileName = "yokan_sync.lock" const val LockTtlMillis = 10 * 60 * 1000L const val BusyMessage = "Sync is in progress on another device; try again in a few minutes." private const val DriveApi = "https://www.googleapis.com/drive/v3" private const val DriveUpload = "https://www.googleapis.com/upload/drive/v3" const val TokenUrl = "https://oauth2.googleapis.com/token" } }