cocos_android/app/src/com/jc/jcfw/util/DriveUtils.kt
2023-11-09 16:33:34 +08:00

96 lines
2.8 KiB
Kotlin

package com.jc.jcfw.util
import android.util.Log
import com.google.api.client.extensions.android.http.AndroidHttp
import com.google.api.client.extensions.android.json.AndroidJsonFactory
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential
import com.google.api.client.http.FileContent
import com.google.api.services.drive.Drive
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.io.OutputStream
object DriveUtils {
private val TAG = DriveUtils::class.java.simpleName
fun generateService(credential: GoogleAccountCredential?, appName: String?): Drive {
return Drive.Builder(
AndroidHttp.newCompatibleTransport(),
AndroidJsonFactory.getDefaultInstance(),
credential
)
.setApplicationName(appName)
.build()
}
/**
* query app file by filename
*
* @param service
* @param fileName
* @throws IOException
*/
fun queryOneAppFile(service: Drive, fileName: String): String {
var querySuccess = false
var fileId = ""
while (!querySuccess) {
try {
val files = service.files().list()
.setSpaces("appDataFolder")
.setFields("nextPageToken, files(id, name)")
.setPageSize(100)
.execute()
querySuccess = true
for (file in files.files) {
Log.i(TAG, String.format("Found file: %s (%s)\n", file.name, file.id))
if (file.name == fileName) {
fileId = file.id
break
}
}
} catch (e: IOException) {
Log.i(TAG, "error query file from drive")
}
}
return fileId
}
/**
* download one file from drive
*
* @param service
* @param fileId
* @throws IOException
*/
@Throws(IOException::class)
fun downloadFile(service: Drive, fileId: String?): String {
val outputStream: OutputStream = ByteArrayOutputStream()
service.files()[fileId].executeMediaAndDownloadTo(outputStream)
// convert outputStream to JSON string
// String json = outputStream.toString();
return outputStream.toString()
}
/**
* upload one file to Drive
*
* @param service
* @param filePath file absolute path
* @param fileType application/json
* @throws IOException
*/
@Throws(IOException::class)
fun uploadAppFile(service: Drive, filePath: File, fileType: String?): String {
val fileName = filePath.name
val fileMetadata = com.google.api.services.drive.model.File()
fileMetadata.name = fileName
fileMetadata.parents = listOf("appDataFolder")
// "application/json"
val mediaContent = FileContent(fileType, filePath)
val file = service.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute()
Log.i(TAG, String.format("%s upload success, File ID: %s", fileName, file.id))
return file.id
}
}