mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
Implement data restoration functionality from Google Sheets, including repository methods to fetch custom foods and updated UI controls in the settings screen.
184 lines
7.4 KiB
Kotlin
184 lines
7.4 KiB
Kotlin
package com.example.util
|
|
|
|
import android.util.Log
|
|
import kotlinx.coroutines.Dispatchers
|
|
import kotlinx.coroutines.withContext
|
|
import okhttp3.Headers
|
|
import okhttp3.MediaType.Companion.toMediaType
|
|
import okhttp3.MultipartBody
|
|
import okhttp3.OkHttpClient
|
|
import okhttp3.Request
|
|
import okhttp3.RequestBody.Companion.asRequestBody
|
|
import okhttp3.RequestBody.Companion.toRequestBody
|
|
import org.json.JSONArray
|
|
import org.json.JSONObject
|
|
import java.io.File
|
|
import java.net.URLEncoder
|
|
import java.util.concurrent.TimeUnit
|
|
|
|
object GoogleDriveService {
|
|
|
|
private const val TAG = "GoogleDriveService"
|
|
const val ROOT_FOLDER_NAME = "Satiéa"
|
|
const val PHOTOS_FOLDER_NAME = "Photos des repas"
|
|
|
|
private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
|
|
private val multipartRelatedMediaType = "multipart/related".toMediaType()
|
|
private val jpegMediaType = "image/jpeg".toMediaType()
|
|
|
|
private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
|
|
.connectTimeout(25, TimeUnit.SECONDS)
|
|
.readTimeout(25, TimeUnit.SECONDS)
|
|
.writeTimeout(25, TimeUnit.SECONDS)
|
|
.build()
|
|
|
|
suspend fun findOrCreateFolder(
|
|
accessToken: String,
|
|
folderName: String,
|
|
parentFolderId: String? = null
|
|
): Result<String> = withContext(Dispatchers.IO) {
|
|
try {
|
|
// 1. Search existing folder
|
|
val parentClause = if (parentFolderId != null) " and '$parentFolderId' in parents" else ""
|
|
val query = "name = '$folderName' and mimeType = 'application/vnd.google-apps.folder' and trashed = false$parentClause"
|
|
val searchUrl = "https://www.googleapis.com/drive/v3/files?q=" +
|
|
URLEncoder.encode(query, "UTF-8") +
|
|
"&fields=" + URLEncoder.encode("files(id, name)", "UTF-8") +
|
|
"&spaces=drive"
|
|
|
|
val searchRequest = Request.Builder()
|
|
.url(searchUrl)
|
|
.header("Authorization", "Bearer $accessToken")
|
|
.get()
|
|
.build()
|
|
|
|
okHttpClient.newCall(searchRequest).execute().use { response ->
|
|
if (response.code == 401) {
|
|
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
|
|
}
|
|
if (response.isSuccessful) {
|
|
val bodyStr = response.body?.string().orEmpty()
|
|
val files = JSONObject(bodyStr).optJSONArray("files")
|
|
if (files != null && files.length() > 0) {
|
|
val folderId = files.getJSONObject(0).getString("id")
|
|
return@withContext Result.success(folderId)
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. Folder does not exist, create it
|
|
val createJson = JSONObject().apply {
|
|
put("name", folderName)
|
|
put("mimeType", "application/vnd.google-apps.folder")
|
|
if (parentFolderId != null) {
|
|
put("parents", JSONArray().put(parentFolderId))
|
|
}
|
|
}
|
|
|
|
val createRequest = Request.Builder()
|
|
.url("https://www.googleapis.com/drive/v3/files?fields=id")
|
|
.header("Authorization", "Bearer $accessToken")
|
|
.post(createJson.toString().toRequestBody(jsonMediaType))
|
|
.build()
|
|
|
|
okHttpClient.newCall(createRequest).execute().use { response ->
|
|
val bodyStr = response.body?.string().orEmpty()
|
|
if (response.code == 401) {
|
|
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
|
|
}
|
|
if (!response.isSuccessful) {
|
|
return@withContext Result.failure(IllegalStateException("Échec création dossier Drive '$folderName': ${response.code}"))
|
|
}
|
|
val id = JSONObject(bodyStr).getString("id")
|
|
Result.success(id)
|
|
}
|
|
} catch (e: Exception) {
|
|
Log.e(TAG, "Error findOrCreateFolder $folderName", e)
|
|
Result.failure(e)
|
|
}
|
|
}
|
|
|
|
suspend fun moveFileToFolder(
|
|
accessToken: String,
|
|
fileId: String,
|
|
targetFolderId: String
|
|
): Result<Unit> = withContext(Dispatchers.IO) {
|
|
try {
|
|
val url = "https://www.googleapis.com/drive/v3/files/$fileId?addParents=$targetFolderId&fields=id,parents"
|
|
val request = Request.Builder()
|
|
.url(url)
|
|
.header("Authorization", "Bearer $accessToken")
|
|
.patch("{}".toRequestBody(jsonMediaType))
|
|
.build()
|
|
|
|
okHttpClient.newCall(request).execute().use { response ->
|
|
if (response.code == 401) {
|
|
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
|
|
}
|
|
if (response.isSuccessful) {
|
|
Result.success(Unit)
|
|
} else {
|
|
Result.failure(IllegalStateException("Échec déplacement vers dossier $targetFolderId"))
|
|
}
|
|
}
|
|
} catch (e: Exception) {
|
|
Log.w(TAG, "Could not move file $fileId to folder: ${e.message}")
|
|
Result.failure(e)
|
|
}
|
|
}
|
|
|
|
suspend fun uploadPhoto(
|
|
accessToken: String,
|
|
photoFile: File,
|
|
parentFolderId: String
|
|
): Result<String> = withContext(Dispatchers.IO) {
|
|
if (!photoFile.exists()) {
|
|
return@withContext Result.failure(IllegalArgumentException("File not found: ${photoFile.path}"))
|
|
}
|
|
|
|
try {
|
|
val metadataJson = JSONObject().apply {
|
|
put("name", photoFile.name)
|
|
put("parents", JSONArray().put(parentFolderId))
|
|
}
|
|
|
|
val multipartBody = MultipartBody.Builder()
|
|
.setType(multipartRelatedMediaType)
|
|
.addPart(
|
|
Headers.headersOf("Content-Type", "application/json; charset=UTF-8"),
|
|
metadataJson.toString().toRequestBody(jsonMediaType)
|
|
)
|
|
.addPart(
|
|
Headers.headersOf("Content-Type", "image/jpeg"),
|
|
photoFile.asRequestBody(jpegMediaType)
|
|
)
|
|
.build()
|
|
|
|
val uploadUrl = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id,webViewLink"
|
|
val request = Request.Builder()
|
|
.url(uploadUrl)
|
|
.header("Authorization", "Bearer $accessToken")
|
|
.post(multipartBody)
|
|
.build()
|
|
|
|
okHttpClient.newCall(request).execute().use { response ->
|
|
val bodyStr = response.body?.string().orEmpty()
|
|
if (response.code == 401) {
|
|
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
|
|
}
|
|
if (!response.isSuccessful) {
|
|
return@withContext Result.failure(IllegalStateException("Échec upload photo: ${response.code}"))
|
|
}
|
|
|
|
val json = JSONObject(bodyStr)
|
|
val id = json.getString("id")
|
|
val link = json.optString("webViewLink", "https://drive.google.com/file/d/$id/view")
|
|
Result.success(link)
|
|
}
|
|
} catch (e: Exception) {
|
|
Log.e(TAG, "Error uploading photo ${photoFile.name}", e)
|
|
Result.failure(e)
|
|
}
|
|
}
|
|
}
|