package eu.friedcutlet.yokan.services.sync import eu.friedcutlet.yokan.services.catchingNonCancellation import eu.friedcutlet.yokan.services.http.HttpRequest import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.util.nowMillis import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull /** Stores cloud backups in the Drive `appDataFolder` of the connected account. */ class GoogleDriveCloudStorageProvider( private val http: HttpService, ) : CloudStorageProvider { override val descriptor: CloudProviderDescriptor = CloudProviderDescriptor( id = ProviderId, displayName = "Google Drive", description = "Stores Yokan sync snapshots and backups in the app data folder of the connected Google Drive account.", authInstructions = "Use an OAuth access token with the https://www.googleapis.com/auth/drive.appdata scope.", ) private val json = Json { ignoreUnknownKeys = true isLenient = true } override suspend fun validate(connection: CloudConnection): CloudConnectionStatus = catchingNonCancellation { listObjects(connection, "__yokan-validation__") CloudConnectionStatus(connected = true, accountLabel = connection.accountLabel, message = "Connected") }.getOrElse { error -> CloudConnectionStatus(connected = false, accountLabel = connection.accountLabel, message = error.message.orEmpty()) } override suspend fun putObject( connection: CloudConnection, key: String, bytes: ByteArray, contentType: String, ): CloudObject { val boundary = "yokan-${nowMillis()}" val metadata = JsonObject( mapOf( "name" to JsonPrimitive(key), "parents" to JsonArray(listOf(JsonPrimitive("appDataFolder"))), ), ).toString() val body = multipartRelated(boundary, metadata, contentType, bytes) val response = http.request( HttpRequest( url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,name,size,modifiedTime", method = "POST", headers = authHeaders(connection) + mapOf("Content-Type" to "multipart/related; boundary=$boundary"), bodyBytes = body, ), ) if (response.statusCode !in 200..299) { throw CloudStorageException("Google Drive upload failed with HTTP ${response.statusCode}: ${response.body.take(160)}") } return parseFile(response.body, fallbackKey = key, fallbackSize = bytes.size.toLong()) } override suspend fun listObjects(connection: CloudConnection, prefix: String): List { val query = "'appDataFolder' in parents and name contains '${escapeDriveQuery(prefix)}' and trashed=false" val url = "https://www.googleapis.com/drive/v3/files" + "?spaces=appDataFolder" + "&q=${percentEncode(query)}" + "&fields=${percentEncode("files(id,name,size,modifiedTime)")}" val response = http.request(HttpRequest(url = url, headers = authHeaders(connection))) if (response.statusCode !in 200..299) { throw CloudStorageException("Google Drive list failed with HTTP ${response.statusCode}: ${response.body.take(160)}") } val files = json.parseToJsonElement(response.body).jsonObject["files"]?.jsonArray ?: JsonArray(emptyList()) return files.mapNotNull { element -> runCatching { parseFile(element.jsonObject, fallbackKey = prefix, fallbackSize = 0L) }.getOrNull() } } override suspend fun getObject(connection: CloudConnection, objectRef: CloudObject): ByteArray { val fileId = objectRef.providerFileId ?: throw CloudStorageException("Google Drive file id is missing.") val response = http.request( HttpRequest( url = "https://www.googleapis.com/drive/v3/files/${percentEncode(fileId)}?alt=media", headers = authHeaders(connection), ), ) if (response.statusCode !in 200..299) { throw CloudStorageException("Google Drive download failed with HTTP ${response.statusCode}: ${response.body.take(160)}") } return response.bodyBytes } private fun parseFile(body: String, fallbackKey: String, fallbackSize: Long): CloudObject = parseFile(json.parseToJsonElement(body).jsonObject, fallbackKey, fallbackSize) private fun parseFile(file: JsonObject, fallbackKey: String, fallbackSize: Long): CloudObject { val id = file.string("id") val name = file.string("name") ?: fallbackKey val size = file["size"]?.jsonPrimitive?.longOrNull ?: file.string("size")?.toLongOrNull() ?: fallbackSize val modified = file.string("modifiedTime")?.let(::parseInstantMillis) ?: nowMillis() return CloudObject( key = name, displayName = name, sizeBytes = size, modifiedAtMillis = modified, providerFileId = id, ) } private fun authHeaders(connection: CloudConnection): Map = mapOf( "Authorization" to "Bearer ${connection.accessToken}", "Accept" to "application/json", ) private fun JsonObject.string(key: String): String? = this[key]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() } private fun escapeDriveQuery(value: String): String = value.replace("\\", "\\\\").replace("'", "\\'") private fun percentEncode(value: String): String { val allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~" return buildString { value.encodeToByteArray().forEach { byte -> val int = byte.toInt() and 0xff val char = int.toChar() if (char in allowed) { append(char) } else { append('%') append(int.toString(16).uppercase().padStart(2, '0')) } } } } companion object { const val ProviderId = "google-drive" } } /** Drive `uploadType=multipart` body: JSON metadata part, then the media part. */ internal fun multipartRelated(boundary: String, metadata: String, contentType: String, bytes: ByteArray): ByteArray { val prefix = buildString { append("--").append(boundary).append("\r\n") append("Content-Type: application/json; charset=UTF-8\r\n\r\n") append(metadata).append("\r\n") append("--").append(boundary).append("\r\n") append("Content-Type: ").append(contentType).append("\r\n\r\n") }.encodeToByteArray() val suffix = "\r\n--$boundary--\r\n".encodeToByteArray() return prefix + bytes + suffix }