Yokan / rebuild
Course 1 8624561

GoogleDriveCloudStorageProvider.kt

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

implementation162 lines
1package eu.friedcutlet.yokan.services.sync23import eu.friedcutlet.yokan.services.catchingNonCancellation4import eu.friedcutlet.yokan.services.http.HttpRequest5import eu.friedcutlet.yokan.services.http.HttpService6import eu.friedcutlet.yokan.util.nowMillis7import kotlinx.serialization.json.Json8import kotlinx.serialization.json.JsonArray9import kotlinx.serialization.json.JsonObject10import kotlinx.serialization.json.JsonPrimitive11import kotlinx.serialization.json.contentOrNull12import kotlinx.serialization.json.jsonArray13import kotlinx.serialization.json.jsonObject14import kotlinx.serialization.json.jsonPrimitive15import kotlinx.serialization.json.longOrNull1617/** Stores cloud backups in the Drive `appDataFolder` of the connected account. */18class GoogleDriveCloudStorageProvider(19    private val http: HttpService,20) : CloudStorageProvider {21    override val descriptor: CloudProviderDescriptor = CloudProviderDescriptor(22        id = ProviderId,23        displayName = "Google Drive",24        description = "Stores Yokan sync snapshots and backups in the app data folder of the connected Google Drive account.",25        authInstructions = "Use an OAuth access token with the https://www.googleapis.com/auth/drive.appdata scope.",26    )2728    private val json = Json {29        ignoreUnknownKeys = true30        isLenient = true31    }3233    override suspend fun validate(connection: CloudConnection): CloudConnectionStatus =34        catchingNonCancellation {35            listObjects(connection, "__yokan-validation__")36            CloudConnectionStatus(connected = true, accountLabel = connection.accountLabel, message = "Connected")37        }.getOrElse { error ->38            CloudConnectionStatus(connected = false, accountLabel = connection.accountLabel, message = error.message.orEmpty())39        }4041    override suspend fun putObject(42        connection: CloudConnection,43        key: String,44        bytes: ByteArray,45        contentType: String,46    ): CloudObject {47        val boundary = "yokan-${nowMillis()}"48        val metadata = JsonObject(49            mapOf(50                "name" to JsonPrimitive(key),51                "parents" to JsonArray(listOf(JsonPrimitive("appDataFolder"))),52            ),53        ).toString()54        val body = multipartRelated(boundary, metadata, contentType, bytes)55        val response = http.request(56            HttpRequest(57                url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,size,modifiedTime",58                method = "POST",59                headers = authHeaders(connection) + mapOf("Content-Type" to "multipart/related; boundary=$boundary"),60                bodyBytes = body,61            ),62        )63        if (response.statusCode !in 200..299) {64            throw CloudStorageException("Google Drive upload failed with HTTP ${response.statusCode}: ${response.body.take(160)}")65        }66        return parseFile(response.body, fallbackKey = key, fallbackSize = bytes.size.toLong())67    }6869    override suspend fun listObjects(connection: CloudConnection, prefix: String): List<CloudObject> {70        val query = "'appDataFolder' in parents and name contains '${escapeDriveQuery(prefix)}' and trashed=false"71        val url = "https://www.googleapis.com/drive/v3/files" +72            "?spaces=appDataFolder" +73            "&q=${percentEncode(query)}" +74            "&fields=${percentEncode("files(id,name,size,modifiedTime)")}"75        val response = http.request(HttpRequest(url = url, headers = authHeaders(connection)))76        if (response.statusCode !in 200..299) {77            throw CloudStorageException("Google Drive list failed with HTTP ${response.statusCode}: ${response.body.take(160)}")78        }79        val files = json.parseToJsonElement(response.body).jsonObject["files"]?.jsonArray ?: JsonArray(emptyList())80        return files.mapNotNull { element ->81            runCatching { parseFile(element.jsonObject, fallbackKey = prefix, fallbackSize = 0L) }.getOrNull()82        }83    }8485    override suspend fun getObject(connection: CloudConnection, objectRef: CloudObject): ByteArray {86        val fileId = objectRef.providerFileId ?: throw CloudStorageException("Google Drive file id is missing.")87        val response = http.request(88            HttpRequest(89                url = "https://www.googleapis.com/drive/v3/files/${percentEncode(fileId)}?alt=media",90                headers = authHeaders(connection),91            ),92        )93        if (response.statusCode !in 200..299) {94            throw CloudStorageException("Google Drive download failed with HTTP ${response.statusCode}: ${response.body.take(160)}")95        }96        return response.bodyBytes97    }9899    private fun parseFile(body: String, fallbackKey: String, fallbackSize: Long): CloudObject =100        parseFile(json.parseToJsonElement(body).jsonObject, fallbackKey, fallbackSize)101102    private fun parseFile(file: JsonObject, fallbackKey: String, fallbackSize: Long): CloudObject {103        val id = file.string("id")104        val name = file.string("name") ?: fallbackKey105        val size = file["size"]?.jsonPrimitive?.longOrNull106            ?: file.string("size")?.toLongOrNull()107            ?: fallbackSize108        val modified = file.string("modifiedTime")?.let(::parseInstantMillis) ?: nowMillis()109        return CloudObject(110            key = name,111            displayName = name,112            sizeBytes = size,113            modifiedAtMillis = modified,114            providerFileId = id,115        )116    }117118    private fun authHeaders(connection: CloudConnection): Map<String, String> =119        mapOf(120            "Authorization" to "Bearer ${connection.accessToken}",121            "Accept" to "application/json",122        )123124    private fun JsonObject.string(key: String): String? =125        this[key]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }126127    private fun escapeDriveQuery(value: String): String =128        value.replace("\\", "\\\\").replace("'", "\\'")129130    private fun percentEncode(value: String): String {131        val allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"132        return buildString {133            value.encodeToByteArray().forEach { byte ->134                val int = byte.toInt() and 0xff135                val char = int.toChar()136                if (char in allowed) {137                    append(char)138                } else {139                    append('%')140                    append(int.toString(16).uppercase().padStart(2, '0'))141                }142            }143        }144    }145146    companion object {147        const val ProviderId = "google-drive"148    }149}150151/** Drive `uploadType=multipart` body: JSON metadata part, then the media part. */152internal fun multipartRelated(boundary: String, metadata: String, contentType: String, bytes: ByteArray): ByteArray {153    val prefix = buildString {154        append("--").append(boundary).append("\r\n")155        append("Content-Type: application/json; charset=UTF-8\r\n\r\n")156        append(metadata).append("\r\n")157        append("--").append(boundary).append("\r\n")158        append("Content-Type: ").append(contentType).append("\r\n\r\n")159    }.encodeToByteArray()160    val suffix = "\r\n--$boundary--\r\n".encodeToByteArray()161    return prefix + bytes + suffix162}163

Search chapters, reference and source filenames.