Yokan / rebuild
Course 1 8624561

GoogleDriveSyncService.kt

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

implementation356 lines
1package eu.friedcutlet.yokan.services.sync23import dev.whyoleg.cryptography.DelicateCryptographyApi4import dev.whyoleg.cryptography.random.CryptographyRandom5import eu.friedcutlet.yokan.database.DbSettings6import eu.friedcutlet.yokan.database.DbSyncPreference7import eu.friedcutlet.yokan.database.SyncServerProvider8import eu.friedcutlet.yokan.database.YokanDatabase9import eu.friedcutlet.yokan.services.backup.BackupFormat10import eu.friedcutlet.yokan.services.backup.BackupOptions11import eu.friedcutlet.yokan.services.backup.BackupService12import eu.friedcutlet.yokan.util.sha25613import eu.friedcutlet.yokan.services.http.HttpRequest14import eu.friedcutlet.yokan.services.http.HttpResponse15import eu.friedcutlet.yokan.services.http.HttpService16import eu.friedcutlet.yokan.services.logging.AppLogger17import eu.friedcutlet.yokan.services.tracking.callbackParameter18import eu.friedcutlet.yokan.util.PlatformLock19import eu.friedcutlet.yokan.util.nowMillis20import io.ktor.http.URLBuilder21import io.ktor.http.formUrlEncode22import kotlin.io.encoding.Base6423import kotlin.time.Instant24import kotlinx.coroutines.NonCancellable25import kotlinx.coroutines.currentCoroutineContext26import kotlinx.coroutines.ensureActive27import kotlinx.coroutines.sync.Mutex28import kotlinx.coroutines.sync.withLock29import kotlinx.coroutines.withContext30import kotlinx.serialization.Serializable31import kotlinx.serialization.json.Json32import kotlinx.serialization.json.JsonArray33import kotlinx.serialization.json.JsonObject34import kotlinx.serialization.json.JsonPrimitive35import kotlinx.serialization.json.buildJsonObject36import kotlinx.serialization.json.contentOrNull37import kotlinx.serialization.json.jsonObject38import kotlinx.serialization.json.put3940/** Loopback redirect of a Google "Desktop app" OAuth client; the browser fails to load it and the user copies the URL. */41internal const val GoogleDriveRedirectUri = "http://127.0.0.1"42internal const val GoogleDriveScope = "https://www.googleapis.com/auth/drive.appdata"4344/** Authorization-code + PKCE (S256) URL for the user's own OAuth client. */45internal fun googleDriveAuthorizationUrl(clientId: String, verifier: String, state: String): String =46    URLBuilder("https://accounts.google.com/o/oauth2/v2/auth").apply {47        parameters.append("client_id", clientId)48        parameters.append("redirect_uri", GoogleDriveRedirectUri)49        parameters.append("response_type", "code")50        parameters.append("scope", GoogleDriveScope)51        parameters.append("access_type", "offline")52        parameters.append("prompt", "consent")53        parameters.append("code_challenge", pkceChallenge(verifier))54        parameters.append("code_challenge_method", "S256")55        parameters.append("state", state)56    }.build().toString()5758internal fun pkceChallenge(verifier: String): String = base64Url(sha256(verifier.encodeToByteArray()))5960private fun base64Url(bytes: ByteArray) = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT).encode(bytes)6162/** Epoch millis of an ISO-8601 instant, or null when [value] is not one. */63internal fun parseInstantMillis(value: String): Long? = runCatching { Instant.parse(value).toEpochMilliseconds() }.getOrNull()6465/** Stored in [DbSyncPreference.authToken]; the client id lives in `server`, the account email in `email`. */66@Serializable67private data class GoogleDriveCredential(val clientSecret: String = "", val refreshToken: String)6869/**70 * Application-state sync through one file in the Drive `appDataFolder` of the user's own OAuth client71 * (independent of the `cloud://google-drive` backup path). A run takes a lock file, merges the sync file72 * when another device wrote it, uploads the merged library, and always releases the lock.73 */74class GoogleDriveSyncService(75    private val database: YokanDatabase,76    private val backup: BackupService,77    private val http: HttpService,78    private val operationMonitor: SyncOperationMonitor = SyncOperationMonitor(),79    private val leases: SyncAccountLeases = SyncAccountLeases.None,80    private val clock: () -> Long = ::nowMillis,81) : SyncService {82    override val operationState = operationMonitor.state83    private val operationMutex = Mutex()84    private val json = Json { ignoreUnknownKeys = true }85    private val authLock = PlatformLock()86    private val pendingAuth = mutableMapOf<Long, PendingAuth>()8788    private class PendingAuth(val clientId: String, val verifier: String, val state: String)8990    private class DriveFile(val id: String, val createdMillis: Long, val modifiedMillis: Long, val properties: Map<String, String>) {91        val deviceId: String? get() = properties["deviceId"]92        val expiresAt: Long get() = properties["expiresAt"]?.toLongOrNull() ?: 0L93    }9495    /** [server] is the user's OAuth client id; the returned URL is opened in the system browser. */96    @OptIn(DelicateCryptographyApi::class)97    override fun beginBrowserLogin(syncId: Long, server: String): BrowserLoginAttempt? {98        val clientId = server.trim().takeIf { it.isNotEmpty() && it.length <= 256 && it.none(Char::isWhitespace) } ?: return null99        if (preference(syncId)?.serverProvider != SyncServerProvider.GoogleDrive) return null100        val verifier = base64Url(CryptographyRandom.Default.nextBytes(32))101        val state = base64Url(CryptographyRandom.Default.nextBytes(24))102        authLock.withLock { pendingAuth[syncId] = PendingAuth(clientId, verifier, state) }103        return BrowserLoginAttempt(syncId, clientId, googleDriveAuthorizationUrl(clientId, verifier, state), device = "", state = state)104    }105106    override fun cancelBrowserLogin(attempt: BrowserLoginAttempt) {107        authLock.withLock { if (pendingAuth[attempt.syncId]?.state == attempt.state) pendingAuth.remove(attempt.syncId) }108    }109110    /**111     * Completes the sign-in begun by [beginBrowserLogin]: [server] is the OAuth client id, [email] its client secret,112     * [password] the pasted loopback URL (or bare code) the browser ended on.113     */114    override suspend fun login(syncId: Long, server: String, email: String, password: String): SyncLoginResult = operationMutex.withLock {115        val clientId = server.trim()116        val pending = authLock.withLock { pendingAuth[syncId]?.takeIf { it.clientId == clientId }?.also { pendingAuth.remove(syncId) } }117            ?: return@withLock SyncLoginResult(false, "Open the Google sign-in page for this client ID first.")118        val prior = preference(syncId)119        if (prior == null || prior.serverProvider != SyncServerProvider.GoogleDrive) return@withLock SyncLoginResult(false, "Google Drive is not the selected sync provider.")120        val pasted = password.trim()121        if (pasted.length > 4096 || "error=" in pasted) return@withLock SyncLoginResult(false, "Google sign-in was not completed.")122        if ("state=" in pasted && callbackParameter(pasted, "state") != pending.state) {123            return@withLock SyncLoginResult(false, "This sign-in address belongs to another attempt; open the sign-in page again.")124        }125        val code = callbackParameter(pasted, "code").takeIf { it.isNotEmpty() && it.length <= 1024 && it.none(Char::isWhitespace) && "://" !in it }126            ?: return@withLock SyncLoginResult(false, "Paste the address the browser opened after sign-in, or its code.")127        val secret = email.trim()128        try {129            val token = tokenRequest(clientId, secret, listOf(130                "code" to code, "redirect_uri" to GoogleDriveRedirectUri,131                "grant_type" to "authorization_code", "code_verifier" to pending.verifier,132            ))133            val refreshToken = token.string("refresh_token")134                ?: throw StateSyncException("Google returned no refresh token; remove Yokan's access in your Google account and sign in again.")135            val accessToken = token.string("access_token") ?: throw StateSyncException("Google returned an invalid token response.")136            val user = driveJson(HttpRequest("$DriveApi/about?fields=user(emailAddress,displayName)", headers = bearer(accessToken)), "account lookup")["user"] as? JsonObject137            val account = user?.string("emailAddress") ?: user?.string("displayName")138            currentCoroutineContext().ensureActive()139            val credential = json.encodeToString(GoogleDriveCredential.serializer(), GoogleDriveCredential(secret, refreshToken))140            val deviceId = prior.deviceId?.takeIf(String::isNotBlank) ?: newDeviceId()141            val next = DbSyncPreference(server = clientId, email = account, authToken = credential, serverProvider = SyncServerProvider.GoogleDrive)142            val failure = leases.commitClaimed(prior, next) {143                database.upsertSyncPreferenceIf(144                    syncId = syncId,145                    accepts = { it == prior },146                    transform = { current ->147                        requireNotNull(current).copy(148                            server = clientId, email = account, authToken = credential, syncOn = true, deviceId = deviceId,149                            lastSyncManga = null, lastSyncHistory = null, lastSyncUpdate = null,150                        )151                    },152                )153            }154            if (failure != null) SyncLoginResult(false, failure)155            else SyncLoginResult(true, "Connected to Google Drive${account?.let { " as $it" }.orEmpty()}.")156        } catch (error: StateSyncException) {157            SyncLoginResult(false, error.message ?: "Google sign-in failed.")158        }159    }160161    override suspend fun logout(syncId: Long) = operationMutex.withLock {162        val pref = preference(syncId) ?: return@withLock163        database.upsertSyncPreferenceIf(syncId, accepts = { it != null }, transform = { requireNotNull(it).copy(authToken = null, syncOn = false) })164        leases.releaseQuietly(pref)165    }166167    override suspend fun sync(syncId: Long, settings: DbSettings) = run(SyncOperationStage.Syncing, syncId, push = true, pull = true)168    override suspend fun pushChanges(syncId: Long) = run(SyncOperationStage.Uploading, syncId, push = true, pull = false)169    override suspend fun pullChanges(syncId: Long) = run(SyncOperationStage.Downloading, syncId, push = false, pull = true)170171    override fun status(syncId: Long): SyncConnectionStatus {172        val pref = preference(syncId)173        return SyncConnectionStatus(!pref?.authToken.isNullOrBlank(), pref?.email, "Google Drive", pref?.lastSyncManga)174    }175176    private suspend fun run(stage: SyncOperationStage, syncId: Long, push: Boolean, pull: Boolean): SyncResult =177        runStateSync(operationMonitor, operationMutex, stage, "Google Drive") { perform(syncId, push, pull) }178179    private suspend fun perform(syncId: Long, push: Boolean, pull: Boolean): SyncResult {180        val captured = preference(syncId) ?: return stateSyncFailure("No sync configuration.")181        if (captured.serverProvider != SyncServerProvider.GoogleDrive) return stateSyncFailure("Google Drive is not the selected sync provider.")182        val clientId = captured.server?.trim()?.takeIf(String::isNotEmpty) ?: return stateSyncFailure("Google OAuth client ID is missing.")183        val credential = captured.authToken?.let { runCatching { json.decodeFromString(GoogleDriveCredential.serializer(), it) }.getOrNull() }184            ?: return stateSyncFailure("Not signed in to Google Drive.")185        val deviceId = captured.deviceId?.takeIf(String::isNotBlank) ?: return stateSyncFailure("Sign in to Google Drive again.")186        leases.claimFailure(captured)?.let { return stateSyncFailure(it) }187        val accessToken = tokenRequest(clientId, credential.clientSecret, listOf("refresh_token" to credential.refreshToken, "grant_type" to "refresh_token"))188            .string("access_token") ?: throw StateSyncException("Google returned an invalid token response.")189        database.checkSyncAccount(captured)190        val lockId = acquireLock(accessToken, deviceId)191        try {192            database.checkSyncAccount(captured)193            val remote = listFiles(accessToken, SyncFileName).maxByOrNull { it.modifiedMillis }194            var downloaded = 0195            // Our own last upload holds nothing new; another device's file is merged in, never replacing local data.196            if (pull && remote != null && remote.deviceId != deviceId) {197                val bytes = drive(HttpRequest("$DriveApi/files/${remote.id}?alt=media", headers = bearer(accessToken)), "download").bodyBytes198                database.checkSyncAccount(captured)199                downloaded = backup.mergeRemoteState(bytes, captured, "Google Drive") ?: 0200            }201            var uploaded = 0202            if (push) {203                val export = backup.exportBackup(204                    BackupOptions(205                        includeHistory = captured.syncHistories,206                        includeUpdates = captured.syncUpdates,207                        includeSettings = captured.syncSettings,208                        compressionLevel = 6,209                        format = BackupFormat.Yokan,210                        includePrivateNotes = false,211                    ),212                )213                database.checkSyncAccount(captured)214                upload(accessToken, remote?.id, deviceId, export.bytes, export.contentType)215                uploaded = export.itemCount216            }217            database.recordStateSync(captured)218            return SyncResult(uploaded, downloaded, settingsSynced = push && captured.syncSettings)219        } finally {220            withContext(NonCancellable) {221                runCatching { deleteFile(accessToken, lockId) }222                    .onFailure { AppLogger.warn("[sync] Google Drive lock release failed; it expires on its own") }223            }224        }225    }226227    /**228     * Takes the `appDataFolder` lock: expired locks are removed, a live lock of another device refuses the run,229     * and when two devices create locks at once (Drive allows duplicate names) the later one backs off.230     */231    private suspend fun acquireLock(accessToken: String, deviceId: String): String {232        val now = clock()233        val (stale, live) = listFiles(accessToken, LockFileName).partition { it.expiresAt <= now }234        stale.forEach { deleteFile(accessToken, it.id) }235        if (live.any { it.deviceId != deviceId }) throw StateSyncException(BusyMessage)236        live.forEach { deleteFile(accessToken, it.id) } // Left behind by an interrupted run on this device.237        val metadata = buildJsonObject {238            put("name", LockFileName)239            put("parents", JsonArray(listOf(JsonPrimitive("appDataFolder"))))240            put("appProperties", buildJsonObject { put("deviceId", deviceId); put("expiresAt", (now + LockTtlMillis).toString()) })241        }242        val created = driveJson(243            HttpRequest("$DriveApi/files?fields=id,createdTime", "POST", bearer(accessToken) + ("Content-Type" to "application/json"), metadata.toString()),244            "lock",245        )246        val lockId = created.string("id") ?: throw StateSyncException("Google Drive returned an invalid lock file.")247        val mine = created.string("createdTime")?.let(::parseInstantMillis) ?: now248        val rival = listFiles(accessToken, LockFileName).any {249            it.id != lockId && it.deviceId != deviceId && it.expiresAt > now &&250                (it.createdMillis < mine || (it.createdMillis == mine && it.id < lockId))251        }252        if (rival) {253            withContext(NonCancellable) { runCatching { deleteFile(accessToken, lockId) } }254            throw StateSyncException(BusyMessage)255        }256        return lockId257    }258259    private suspend fun upload(accessToken: String, fileId: String?, deviceId: String, bytes: ByteArray, contentType: String) {260        val metadata = buildJsonObject {261            if (fileId == null) {262                put("name", SyncFileName)263                put("parents", JsonArray(listOf(JsonPrimitive("appDataFolder"))))264            }265            put("appProperties", buildJsonObject { put("deviceId", deviceId) })266        }267        val boundary = "yokan-sync-${clock()}"268        val url = if (fileId == null) "$DriveUpload/files?uploadType=multipart&fields=id" else "$DriveUpload/files/$fileId?uploadType=multipart&fields=id"269        drive(270            HttpRequest(271                url, if (fileId == null) "POST" else "PATCH",272                bearer(accessToken) + ("Content-Type" to "multipart/related; boundary=$boundary"),273                bodyBytes = multipartRelated(boundary, metadata.toString(), contentType, bytes),274            ),275            "upload",276        )277    }278279    private suspend fun listFiles(accessToken: String, name: String): List<DriveFile> {280        val url = URLBuilder("$DriveApi/files").apply {281            parameters.append("spaces", "appDataFolder")282            parameters.append("q", "name = '$name' and trashed = false")283            parameters.append("fields", "files(id,createdTime,modifiedTime,appProperties)")284        }.build().toString()285        val files = driveJson(HttpRequest(url, headers = bearer(accessToken)), "list")["files"] as? JsonArray ?: return emptyList()286        return files.mapNotNull { element ->287            val file = element as? JsonObject ?: return@mapNotNull null288            val id = file.string("id") ?: return@mapNotNull null289            val properties = (file["appProperties"] as? JsonObject)?.mapNotNull { (key, value) ->290                (value as? JsonPrimitive)?.contentOrNull?.let { key to it }291            }?.toMap().orEmpty()292            DriveFile(id, file.string("createdTime")?.let(::parseInstantMillis) ?: 0L, file.string("modifiedTime")?.let(::parseInstantMillis) ?: 0L, properties)293        }294    }295296    private suspend fun deleteFile(accessToken: String, id: String) {297        val response = http.requestOrNull(HttpRequest("$DriveApi/files/$id", "DELETE", bearer(accessToken)))298            ?: throw StateSyncException("Could not reach Google Drive.")299        if (response.statusCode != 404 && response.statusCode !in 200..299) throw driveFailure(response, "delete")300    }301302    private suspend fun drive(request: HttpRequest, action: String): HttpResponse {303        val response = http.requestOrNull(request) ?: throw StateSyncException("Could not reach Google Drive.")304        if (response.statusCode !in 200..299) throw driveFailure(response, action)305        return response306    }307308    private suspend fun driveJson(request: HttpRequest, action: String): JsonObject {309        val body = drive(request, action).body310        return runCatching { json.parseToJsonElement(body).jsonObject }.getOrNull()311            ?: throw StateSyncException("Google Drive returned an invalid $action response.")312    }313314    private fun driveFailure(response: HttpResponse, action: String) = StateSyncException(315        if (response.statusCode == 401) "Google Drive rejected the sign-in; sign in again."316        else "Google Drive $action failed with HTTP ${response.statusCode}.",317    )318319    /** Token endpoint call (code exchange or refresh); the client secret is sent when the user entered one. */320    private suspend fun tokenRequest(clientId: String, clientSecret: String, form: List<Pair<String, String>>): JsonObject {321        val fields = listOf("client_id" to clientId) + listOfNotNull(clientSecret.takeIf(String::isNotBlank)?.let { "client_secret" to it }) + form322        val response = http.requestOrNull(323            HttpRequest(TokenUrl, "POST", mapOf("Content-Type" to "application/x-www-form-urlencoded", "Accept" to "application/json"), fields.formUrlEncode()),324        ) ?: throw StateSyncException("Could not reach Google.")325        val body = runCatching { json.parseToJsonElement(response.body).jsonObject }.getOrNull()326        if (response.statusCode !in 200..299) throw StateSyncException(327            when (body?.string("error")) {328                "invalid_grant" -> "Google sign-in expired or was revoked; sign in to Google Drive again."329                "invalid_client", "unauthorized_client" -> "Google rejected the OAuth client ID or secret."330                else -> "Google token request failed with HTTP ${response.statusCode}."331            },332        )333        return body ?: throw StateSyncException("Google returned an invalid token response.")334    }335336    private fun bearer(accessToken: String) = mapOf("Authorization" to "Bearer $accessToken", "Accept" to "application/json")337338    private fun preference(id: Long): DbSyncPreference? = database.syncPreferences().firstOrNull { it.syncId == id }339340    @OptIn(DelicateCryptographyApi::class)341    private fun newDeviceId(): String =342        CryptographyRandom.Default.nextBytes(16).toHexString()343344    private fun JsonObject.string(key: String): String? =345        (this[key] as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf(String::isNotEmpty)346347    internal companion object {348        const val SyncFileName = "yokan_sync.json.gz"349        const val LockFileName = "yokan_sync.lock"350        const val LockTtlMillis = 10 * 60 * 1000L351        const val BusyMessage = "Sync is in progress on another device; try again in a few minutes."352        private const val DriveApi = "https://www.googleapis.com/drive/v3"353        private const val DriveUpload = "https://www.googleapis.com/upload/drive/v3"354        const val TokenUrl = "https://oauth2.googleapis.com/token"355    }356}357

Search chapters, reference and source filenames.