com.gabrielittner.github.diff.services.GoogleCloudStorage.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of github-diff Show documentation
Show all versions of github-diff Show documentation
Diff apks and post results to Github
package com.gabrielittner.github.diff.services
import com.gabrielittner.github.diff.Apk
import com.gabrielittner.github.diff.Storage
import com.google.auth.oauth2.GoogleCredentials
import com.google.cloud.storage.Blob
import com.google.cloud.storage.BlobId
import com.google.cloud.storage.BlobInfo
import com.google.cloud.storage.Storage as CloudStorage
import com.google.cloud.storage.StorageOptions
import com.google.gson.JsonParser
import okio.ByteString
import okio.ByteString.Companion.encodeUtf8
import okio.ByteString.Companion.toByteString
import okio.buffer
import okio.gzip
import okio.sink
import java.io.ByteArrayOutputStream
class GoogleCloudStorage(credentials: String) : Storage {
private val projectId = JsonParser().parse(credentials).asJsonObject.get("project_id").asString
private val googleCredentials = GoogleCredentials.fromStream(credentials.byteInputStream())
private val storage = StorageOptions.newBuilder()
.setProjectId(projectId)
.setCredentials(googleCredentials)
.build()
.service
override fun store(name: String, content: String): String {
val bucketName = bucketName(BUCKET_DIFF)
val id = BlobId.of(bucketName, name)
val blob = storage.save(id, content.encodeUtf8(), "text/plain")
return blob.url
}
override fun saveApk(commit: String, apk: Apk): String {
val bucketName = bucketName(BUCKET_APK)
val id = apkBlobId(bucketName, commit, apk.name)
val blob = storage.save(id, apk.bytes, "application/vnd.android.package-archive")
return blob.url
}
override fun loadApk(name: String, commit: String?): Apk? {
if (commit != null) {
val bucketName = bucketName(BUCKET_APK)
val apkId = apkBlobId(bucketName, commit, name)
val blob = storage.get(apkId)
if (blob != null) {
val bytes = blob.getContent().toByteString()
val url = blob.url
return Apk.from(name, commit, bytes, url)
}
}
return null
}
private fun bucketName(type: String): String {
return "$projectId-$type"
}
private fun apkBlobId(bucketName: String, commit: String, name: String): BlobId {
return BlobId.of(bucketName, "$name-$commit.apk")
}
private val Blob.url get() = "https://storage.cloud.google.com/$bucket/$name"
private fun CloudStorage.save(blobId: BlobId, value: ByteString, contentType: String): Blob {
val blobInfo = BlobInfo.newBuilder(blobId)
.setContentType(contentType)
.setContentEncoding("gzip")
.build()
val content = ByteArrayOutputStream().let { stream ->
stream.sink().gzip().buffer().use { it.write(value) }
stream.toByteArray()
}
return create(blobInfo, content)
}
companion object {
const val BUCKET_APK = "apk"
const val BUCKET_DIFF = "diff"
}
}