feat: add Google Sheets data restoration

Implement data restoration functionality from Google Sheets, including repository methods to fetch custom foods and updated UI controls in the settings screen.
This commit is contained in:
bleackstorm committed 2026-11-08 20:38:08 +01:00
1 parent 79e04f64d8
commit 3397fc1c60
12 files changed
+1076 -99

No files matched your search

@@ -292,6 +292,21 @@ fun AppRoot(
}
}
val triggerGoogleSheetsRestore = {
val email = Firebase.auth.currentUser?.email
?: GoogleSignIn.getLastSignedInAccount(context)?.email
if (email.isNullOrBlank()) {
val client = GoogleSheetsAuthHelper.getGoogleSignInClient(context)
sheetsAuthConsentLauncher.launch(client.signInIntent)
} else {
viewModel.restoreFromGoogleSheets(
onAuthConsentNeeded = { intent ->
sheetsAuthConsentLauncher.launch(intent)
}
)
}
}
val openGoogleSheets = { url: String ->
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
@@ -419,6 +434,7 @@ fun AppRoot(
onSyncSheetsClick = { triggerGoogleSheetsSync() },
onAutoSyncSheetsChange = { enabled -> viewModel.setAutoSyncSheets(enabled) },
onOpenSheetsClick = { url -> openGoogleSheets(url) },
onRestoreSheetsClick = { triggerGoogleSheetsRestore() },
onSignInClick = { showAuthSheet = true },
onSignOut = {
viewModel.signOut(context) {
@@ -50,6 +50,28 @@ class GoogleSheetsPreferencesManager private constructor(context: Context) {
prefs.edit().putString(KEY_LAST_SYNC_ERROR, value).apply()
}
var rootFolderId: String?
get() = prefs.getString(KEY_ROOT_FOLDER_ID, null)
set(value) {
prefs.edit().putString(KEY_ROOT_FOLDER_ID, value).apply()
}
var photosFolderId: String?
get() = prefs.getString(KEY_PHOTOS_FOLDER_ID, null)
set(value) {
prefs.edit().putString(KEY_PHOTOS_FOLDER_ID, value).apply()
}
fun getPhotoDriveUrl(localUri: String): String? {
val key = "photo_url_" + localUri.hashCode()
return prefs.getString(key, null)
}
fun savePhotoDriveUrl(localUri: String, driveUrl: String) {
val key = "photo_url_" + localUri.hashCode()
prefs.edit().putString(key, driveUrl).apply()
}
fun clear() {
prefs.edit().clear().apply()
}
@@ -58,6 +80,8 @@ class GoogleSheetsPreferencesManager private constructor(context: Context) {
private const val PREFS_NAME = "satiea_google_sheets_prefs"
private const val KEY_SPREADSHEET_ID = "spreadsheet_id"
private const val KEY_SPREADSHEET_URL = "spreadsheet_url"
private const val KEY_ROOT_FOLDER_ID = "root_folder_id"
private const val KEY_PHOTOS_FOLDER_ID = "photos_folder_id"
private const val KEY_AUTO_SYNC = "auto_sync_enabled"
private const val KEY_LAST_SYNC_TIMESTAMP = "last_sync_timestamp"
private const val KEY_LAST_SYNC_COUNT = "last_sync_count"
@@ -47,7 +47,11 @@ class MealRepository(
context.applicationContext.getString(R.string.firestore_database_id)
)
} catch (_: Exception) {
null
try {
FirebaseFirestore.getInstance()
} catch (_: Exception) {
null
}
},
context = context.applicationContext
)
@@ -312,6 +316,30 @@ class MealRepository(
}
}
suspend fun getAllCustomFoodsSnapshot(): List<LocalCustomFoodEntity> {
if (localMealDao != null) {
return localMealDao.getAllCustomFoodsOnce()
}
val uid = getUserIdOrNull() ?: return emptyList()
val firestore = db ?: return emptyList()
return try {
firestore.collection("users").document(uid).collection("custom_foods")
.orderBy("name", Query.Direction.ASCENDING)
.get()
.await()
.toObjects(CustomFoodEntry::class.java)
.map {
LocalCustomFoodEntity(
slugId = it.id,
name = it.name,
defaultUnit = it.defaultUnit
)
}
} catch (_: Exception) {
emptyList()
}
}
suspend fun importMealsFromCsv(context: Context, uri: Uri): Result<CsvImportResult> {
return try {
val existingMeals = localMealDao?.getAllMealsOnce()?.map { it.toMealEntry() } ?: emptyList()
@@ -413,4 +441,94 @@ class MealRepository(
Result.failure(e)
}
}
suspend fun insertRestoredMealsAndFoods(
meals: List<MealEntry>,
foods: List<LocalCustomFoodEntity>
): Pair<Int, Int> {
var newMealsCount = 0
var newFoodsCount = 0
if (localMealDao != null) {
val existing = localMealDao.getAllMealsOnce()
val existingFingerprints = existing.map { "${it.mealType.uppercase()}_${it.mealTimestamp / 60_000}" }.toSet()
val toInsertMeals = mutableListOf<LocalMealEntity>()
for (m in meals) {
val fp = "${m.mealType.uppercase()}_${m.mealTimestamp / 60_000}"
if (fp !in existingFingerprints) {
toInsertMeals.add(LocalMealEntity.fromMealEntry(m))
newMealsCount++
}
}
if (toInsertMeals.isNotEmpty()) {
localMealDao.insertMeals(toInsertMeals)
}
val existingFoods = localMealDao.getAllCustomFoodsOnce().map { it.name.lowercase().trim() }.toSet()
val toInsertFoods = mutableListOf<LocalCustomFoodEntity>()
for (f in foods) {
if (f.name.lowercase().trim() !in existingFoods) {
toInsertFoods.add(f)
newFoodsCount++
}
}
if (toInsertFoods.isNotEmpty()) {
localMealDao.insertCustomFoods(toInsertFoods)
}
}
return Pair(newMealsCount, newFoodsCount)
}
suspend fun syncLocalToCloud(): Result<Int> {
val uid = getUserIdOrNull() ?: return Result.failure(IllegalStateException("No Google account signed in"))
val firestore = db ?: return Result.failure(IllegalStateException("Firestore is not available"))
return try {
val remoteMealsSnapshot = firestore.collection("users").document(uid).collection("meals").get().await()
val remoteMealIds = remoteMealsSnapshot.documents.map { it.id }.toSet()
val localMeals = localMealDao?.getAllMealsOnce()?.map { it.toMealEntry() } ?: emptyList()
var uploadedCount = 0
for (meal in localMeals) {
if (!remoteMealIds.contains(meal.id)) {
val payload = mapOf(
"userId" to uid,
"mealType" to meal.mealType,
"mealTimestamp" to meal.mealTimestamp,
"hungerBefore" to meal.hungerBefore,
"satietyAfter" to meal.satietyAfter,
"note" to meal.note,
"foodItemsSerialized" to meal.foodItemsSerialized,
"photoUris" to meal.photoUris,
"photosBase64" to meal.photosBase64,
"createdAt" to FieldValue.serverTimestamp(),
"updatedAt" to FieldValue.serverTimestamp()
)
firestore.collection("users").document(uid).collection("meals").document(meal.id).set(payload).await()
uploadedCount++
}
}
val remoteFoodsSnapshot = firestore.collection("users").document(uid).collection("custom_foods").get().await()
val remoteFoodIds = remoteFoodsSnapshot.documents.map { it.id }.toSet()
val localFoods = localMealDao?.getAllCustomFoodsOnce() ?: emptyList()
for (food in localFoods) {
if (!remoteFoodIds.contains(food.slugId)) {
val payload = mapOf(
"userId" to uid,
"name" to food.name,
"defaultUnit" to food.defaultUnit,
"createdAt" to FieldValue.serverTimestamp(),
"updatedAt" to FieldValue.serverTimestamp()
)
firestore.collection("users").document(uid).collection("custom_foods").document(food.slugId).set(payload).await()
}
}
Result.success(uploadedCount)
} catch (e: Exception) {
if (e is CancellationException) throw e
Result.failure(e)
}
}
}
@@ -2,9 +2,12 @@ package com.example.domain
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.repository.MealRepository
import com.example.util.AuthExpiredException
import com.example.util.GoogleDriveService
import com.example.util.GoogleSheetsAuthHelper
import com.example.util.GoogleSheetsSyncResult
import com.example.util.GoogleSheetsSyncService
@@ -13,13 +16,20 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import java.io.File
sealed interface SheetsSyncResult {
data class Success(val url: String, val count: Int, val timestamp: Long) : SheetsSyncResult
data class Success(val url: String, val count: Int, val foodsCount: Int, val timestamp: Long) : SheetsSyncResult
data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsSyncResult
data class Failure(val message: String) : SheetsSyncResult
}
sealed interface SheetsRestoreResult {
data class Success(val mealsCount: Int, val foodsCount: Int) : SheetsRestoreResult
data class RecoverableAuth(val message: String, val intent: Intent?) : SheetsRestoreResult
data class Failure(val message: String) : SheetsRestoreResult
}
class GoogleSheetsSyncUseCase(
private val context: Context,
private val repository: MealRepository,
@@ -50,15 +60,45 @@ class GoogleSheetsSyncUseCase(
var token = tokenResult.getOrThrow()
// 1. Get or create spreadsheet
var spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
// 1. Ensure Satiéa root folder and Photos subfolder on Drive
var rootFolderId = sheetsPrefs.rootFolderId
if (rootFolderId.isNullOrBlank()) {
val folderRes = GoogleDriveService.findOrCreateFolder(token, GoogleDriveService.ROOT_FOLDER_NAME)
if (folderRes.isSuccess) {
rootFolderId = folderRes.getOrThrow()
sheetsPrefs.rootFolderId = rootFolderId
}
}
var photosFolderId = sheetsPrefs.photosFolderId
if (photosFolderId.isNullOrBlank() && !rootFolderId.isNullOrBlank()) {
val photosFolderRes = GoogleDriveService.findOrCreateFolder(
token,
GoogleDriveService.PHOTOS_FOLDER_NAME,
rootFolderId
)
if (photosFolderRes.isSuccess) {
photosFolderId = photosFolderRes.getOrThrow()
sheetsPrefs.photosFolderId = photosFolderId
}
}
// 2. Get or create spreadsheet
var spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(
token,
sheetsPrefs.spreadsheetId,
parentFolderId = rootFolderId
)
if (spreadsheetResult.isFailure && spreadsheetResult.exceptionOrNull() is AuthExpiredException && retryOnAuthFailure) {
// Token expired, invalidate and retry once
GoogleSheetsAuthHelper.invalidateToken(context, token)
val refreshedTokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
if (refreshedTokenResult.isSuccess) {
token = refreshedTokenResult.getOrThrow()
spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId)
spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(
token,
sheetsPrefs.spreadsheetId,
parentFolderId = rootFolderId
)
}
}
@@ -71,15 +111,34 @@ class GoogleSheetsSyncUseCase(
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
// 2. Sync meals
// 3. Upload missing meal photos to Google Drive Photos folder
val currentMeals = repository.getAllMealsSnapshot()
var syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
if (!photosFolderId.isNullOrBlank()) {
uploadMealPhotosQuietly(token, photosFolderId, currentMeals)
}
// 4. Sync meals and custom foods to the 2 spreadsheet tabs
val currentFoods = repository.getAllCustomFoodsSnapshot()
var syncResult = GoogleSheetsSyncService.syncMealsAndFoods(
accessToken = token,
spreadsheetId = id,
meals = currentMeals,
foods = currentFoods,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
)
if (syncResult.isFailure && syncResult.exceptionOrNull() is AuthExpiredException && retryOnAuthFailure) {
GoogleSheetsAuthHelper.invalidateToken(context, token)
val refreshedTokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
if (refreshedTokenResult.isSuccess) {
token = refreshedTokenResult.getOrThrow()
syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
syncResult = GoogleSheetsSyncService.syncMealsAndFoods(
accessToken = token,
spreadsheetId = id,
meals = currentMeals,
foods = currentFoods,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
)
}
}
@@ -88,28 +147,60 @@ class GoogleSheetsSyncUseCase(
sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé avec succès"
SheetsSyncResult.Success(res.spreadsheetUrl, res.mealsCount, res.timestamp)
SheetsSyncResult.Success(res.spreadsheetUrl, res.mealsCount, res.foodsCount, res.timestamp)
} else {
val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation des repas"
val err = syncResult.exceptionOrNull()?.localizedMessage ?: "Erreur lors de la synchronisation"
SheetsSyncResult.Failure(err)
}
}
private suspend fun uploadMealPhotosQuietly(
accessToken: String,
photosFolderId: String,
meals: List<com.example.data.model.MealEntry>
) {
for (meal in meals) {
for (photoUriStr in meal.displayPhotoUris) {
if (sheetsPrefs.getPhotoDriveUrl(photoUriStr) != null) continue
try {
val uri = Uri.parse(photoUriStr)
val path = uri.path ?: continue
val file = File(path)
if (file.exists() && file.isFile) {
val uploadResult = GoogleDriveService.uploadPhoto(accessToken, file, photosFolderId)
if (uploadResult.isSuccess) {
sheetsPrefs.savePhotoDriveUrl(photoUriStr, uploadResult.getOrThrow())
}
}
} catch (e: Exception) {
Log.w("GoogleSheetsSync", "Photo upload skipped for $photoUriStr: ${e.message}")
}
}
}
}
suspend fun executeAutoSyncQuietly(): GoogleSheetsSyncResult? {
if (!sheetsPrefs.isAutoSyncEnabled) return null
if (syncMutex.isLocked) return null // Drop redundant concurrent background trigger
if (syncMutex.isLocked) return null
return try {
syncMutex.withLock {
withContext(Dispatchers.IO) {
val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null
val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId).getOrNull()
val (id, url) = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, sheetsPrefs.spreadsheetId, sheetsPrefs.rootFolderId).getOrNull()
?: return@withContext null
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
val currentMeals = repository.getAllMealsSnapshot()
val syncResult = GoogleSheetsSyncService.syncMeals(token, id, currentMeals)
val currentFoods = repository.getAllCustomFoodsSnapshot()
val syncResult = GoogleSheetsSyncService.syncMealsAndFoods(
accessToken = token,
spreadsheetId = id,
meals = currentMeals,
foods = currentFoods,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
)
if (syncResult.isSuccess) {
val res = syncResult.getOrThrow()
sheetsPrefs.lastSyncTimestamp = res.timestamp
@@ -123,4 +214,58 @@ class GoogleSheetsSyncUseCase(
null
}
}
suspend fun restoreFromSheets(): SheetsRestoreResult = syncMutex.withLock {
withContext(Dispatchers.IO) {
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
if (tokenResult.isFailure) {
val exception = tokenResult.exceptionOrNull()
return@withContext if (exception is UserRecoverableAuthException) {
SheetsRestoreResult.RecoverableAuth(
message = "Autorisation requise pour restaurer les données",
intent = exception.intent
)
} else {
SheetsRestoreResult.Failure(exception?.localizedMessage ?: "Échec d'authentification Google")
}
}
var token = tokenResult.getOrThrow()
val spreadsheetId = sheetsPrefs.spreadsheetId
if (spreadsheetId.isNullOrBlank()) {
// Try finding it on Drive
val findResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(token, null, sheetsPrefs.rootFolderId)
if (findResult.isFailure) {
return@withContext SheetsRestoreResult.Failure("Aucun classeur Satiéa trouvé sur Google Drive")
}
sheetsPrefs.spreadsheetId = findResult.getOrThrow().first
sheetsPrefs.spreadsheetUrl = findResult.getOrThrow().second
}
val targetId = sheetsPrefs.spreadsheetId ?: return@withContext SheetsRestoreResult.Failure("Classeur introuvable")
var readResult = GoogleSheetsSyncService.readSpreadsheetData(token, targetId)
if (readResult.isFailure && readResult.exceptionOrNull() is AuthExpiredException) {
GoogleSheetsAuthHelper.invalidateToken(context, token)
val refreshed = GoogleSheetsAuthHelper.getAccessToken(context)
if (refreshed.isSuccess) {
token = refreshed.getOrThrow()
readResult = GoogleSheetsSyncService.readSpreadsheetData(token, targetId)
}
}
if (readResult.isFailure) {
return@withContext SheetsRestoreResult.Failure(readResult.exceptionOrNull()?.localizedMessage ?: "Erreur de lecture du classeur")
}
val data = readResult.getOrThrow()
val (restoredMeals, restoredFoods) = repository.insertRestoredMealsAndFoods(data.meals, data.foods)
// If user is logged in to Firestore, align remote database too
try {
repository.syncLocalToCloud()
} catch (_: Exception) {}
SheetsRestoreResult.Success(mealsCount = restoredMeals, foodsCount = restoredFoods)
}
}
}
@@ -15,6 +15,7 @@ import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.repository.MealRepository
import com.example.domain.CsvExportUseCase
import com.example.domain.GoogleSheetsSyncUseCase
import com.example.domain.SheetsRestoreResult
import com.example.domain.SheetsSyncResult
import com.example.notification.MealNotificationManager
import com.example.ui.common.UiEvent
@@ -305,7 +306,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
is SheetsSyncResult.Success -> {
_spreadsheetUrl.value = result.url
_sheetsUiState.value = GoogleSheetsUiState.Success(result.url, result.count, result.timestamp)
emitEvent(UiEvent.ShowSnackbar("Synchronisé avec succès vers Google Sheets (${result.count} repas) 📊"))
val foodsInfo = if (result.foodsCount > 0) " et ${result.foodsCount} aliments" else ""
emitEvent(UiEvent.ShowSnackbar("Synchronisé vers Google Sheets (${result.count} repas$foodsInfo) 📊"))
}
is SheetsSyncResult.RecoverableAuth -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
@@ -325,6 +327,42 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
fun restoreFromGoogleSheets(
onAuthConsentNeeded: ((Intent) -> Unit)? = null
) {
viewModelScope.launch {
_sheetsUiState.value = GoogleSheetsUiState.Syncing
when (val result = sheetsSyncUseCase.restoreFromSheets()) {
is SheetsRestoreResult.Success -> {
_sheetsUiState.value = GoogleSheetsUiState.Idle
val msg = buildString {
append("Restauration réussie ✨ : ")
append("${result.mealsCount} repas")
if (result.foodsCount > 0) {
append(" et ${result.foodsCount} aliments")
}
append(" restaurés")
}
emitEvent(UiEvent.ShowSnackbar(msg))
}
is SheetsRestoreResult.RecoverableAuth -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message, result.intent)
if (result.intent != null && onAuthConsentNeeded != null) {
onAuthConsentNeeded(result.intent)
} else if (result.intent != null) {
emitEvent(UiEvent.StartActivity(result.intent))
} else {
emitEvent(UiEvent.ShowSnackbar(result.message))
}
}
is SheetsRestoreResult.Failure -> {
_sheetsUiState.value = GoogleSheetsUiState.Error(result.message)
emitEvent(UiEvent.ShowSnackbar(result.message))
}
}
}
}
fun exportCsvToUri(
targetUri: Uri,
meals: List<MealEntry>
@@ -373,6 +411,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
result.fold(
onSuccess = { count ->
emitEvent(UiEvent.ShowSnackbar("Compte lié ($count repas Cloud synchronisés) ☁️"))
// Trigger uploading any local meals that were created offline
syncLocalToCloud()
},
onFailure = { err ->
val msg = err.localizedMessage ?: "Erreur lors de la synchronisation"
@@ -382,6 +422,12 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
fun syncLocalToCloud() {
viewModelScope.launch {
repository.syncLocalToCloud()
}
}
fun shareCsv(meals: List<MealEntry>) {
viewModelScope.launch {
val result = csvExportUseCase.createShareIntent(meals)
@@ -43,6 +43,7 @@ fun SettingsScreen(
onSyncSheetsClick: () -> Unit,
onAutoSyncSheetsChange: (Boolean) -> Unit,
onOpenSheetsClick: (String) -> Unit,
onRestoreSheetsClick: () -> Unit = {},
onSignInClick: () -> Unit,
onSignOut: () -> Unit,
modifier: Modifier = Modifier
@@ -94,7 +95,8 @@ fun SettingsScreen(
spreadsheetUrl = spreadsheetUrl,
onSyncSheetsClick = onSyncSheetsClick,
onAutoSyncSheetsChange = onAutoSyncSheetsChange,
onOpenSheetsClick = onOpenSheetsClick
onOpenSheetsClick = onOpenSheetsClick,
onRestoreSheetsClick = onRestoreSheetsClick
)
}
@@ -16,9 +16,11 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.OpenInNew
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.CloudDownload
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material.icons.filled.TableChart
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
@@ -31,7 +33,12 @@ import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
@@ -53,8 +60,10 @@ fun GoogleSheetsIntegrationSection(
onSyncSheetsClick: () -> Unit,
onAutoSyncSheetsChange: (Boolean) -> Unit,
onOpenSheetsClick: (String) -> Unit,
onRestoreSheetsClick: () -> Unit = {},
modifier: Modifier = Modifier
) {
var showRestoreConfirmDialog by remember { mutableStateOf(false) }
Card(
modifier = modifier
.fillMaxWidth()
@@ -320,6 +329,25 @@ fun GoogleSheetsIntegrationSection(
}
}
Spacer(modifier = Modifier.height(10.dp))
OutlinedButton(
onClick = { showRestoreConfirmDialog = true },
enabled = spreadsheetUrl != null && sheetsUiState !is GoogleSheetsUiState.Syncing,
modifier = Modifier
.fillMaxWidth()
.testTag("restore_sheets_button"),
shape = RoundedCornerShape(12.dp)
) {
Icon(
imageVector = Icons.Default.CloudDownload,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Restaurer mes données depuis Google Drive & Sheets")
}
Spacer(modifier = Modifier.height(12.dp))
Text(
@@ -329,4 +357,41 @@ fun GoogleSheetsIntegrationSection(
)
}
}
if (showRestoreConfirmDialog) {
AlertDialog(
onDismissRequest = { showRestoreConfirmDialog = false },
title = {
Text(
text = "Restaurer depuis Google Drive & Sheets",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
},
text = {
Text(
text = "Voulez-vous restaurer vos repas et plats personnalisés depuis votre classeur Google Sheets ?\n\nVos ajouts locaux récents seront conservés et fusionnés sans doublon.",
style = MaterialTheme.typography.bodyMedium
)
},
confirmButton = {
Button(
onClick = {
showRestoreConfirmDialog = false
onRestoreSheetsClick()
},
colors = ButtonDefaults.buttonColors(
containerColor = Color(0xFF0F9D58)
)
) {
Text("Restaurer")
}
},
dismissButton = {
TextButton(onClick = { showRestoreConfirmDialog = false }) {
Text("Annuler")
}
}
)
}
}
@@ -0,0 +1,183 @@
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)
}
}
}
@@ -1,16 +1,20 @@
package com.example.util
import com.example.data.local.LocalCustomFoodEntity
import com.example.data.model.FoodUnit
import com.example.data.model.HungerSatietyScale
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
object GoogleSheetsDataFormatter {
val HEADERS: List<String> = listOf(
val HEADERS_MEALS: List<String> = listOf(
"Date",
"Heure",
"Type de repas",
@@ -23,15 +27,27 @@ object GoogleSheetsDataFormatter {
"Photos jointes"
)
val HEADERS_CUSTOM_FOODS: List<String> = listOf(
"Nom de l'aliment / Plat",
"Unité par défaut",
"Date d'ajout"
)
// Backward-compatibility alias
val HEADERS = HEADERS_MEALS
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH)
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
private val dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm", Locale.FRENCH)
fun formatMealsToRows(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): List<List<Any>> {
fun formatMealsToRows(
meals: List<MealEntry>,
zoneId: ZoneId = ZoneId.systemDefault(),
photoLinkProvider: (String) -> String? = { null }
): List<List<Any>> {
val rows = mutableListOf<List<Any>>()
// Header row
rows.add(HEADERS)
rows.add(HEADERS_MEALS)
// Sorted by descending timestamp (most recent first)
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
for (meal in sortedMeals) {
@@ -43,7 +59,14 @@ object GoogleSheetsDataFormatter {
val satietyLabel = HungerSatietyScale.getSatietyLabel(meal.satietyAfter)
val foodsFormatted = meal.parsedFoodItems().joinToString(" ; ") { it.displayCsv() }
val cleanNote = meal.note.replace("\r\n", " ").replace("\n", " ").trim()
val photosCount = meal.displayPhotoUris.size
// Collect Drive URLs or photo count
val driveLinks = meal.displayPhotoUris.mapNotNull { photoLinkProvider(it) }
val photoCell: Any = if (driveLinks.isNotEmpty()) {
driveLinks.joinToString(" ; ")
} else {
meal.displayPhotoUris.size
}
rows.add(
listOf(
@@ -56,11 +79,109 @@ object GoogleSheetsDataFormatter {
satietyLabel,
foodsFormatted,
cleanNote,
photosCount
photoCell
)
)
}
return rows
}
fun formatCustomFoodsToRows(
foods: List<LocalCustomFoodEntity>,
zoneId: ZoneId = ZoneId.systemDefault()
): List<List<Any>> {
val rows = mutableListOf<List<Any>>()
rows.add(HEADERS_CUSTOM_FOODS)
val sortedFoods = foods.sortedBy { it.name.lowercase(Locale.FRENCH) }
for (food in sortedFoods) {
val dateStr = try {
val zdt = Instant.ofEpochMilli(food.updatedAt).atZone(zoneId)
dateTimeFormatter.format(zdt)
} catch (_: Exception) {
""
}
rows.add(
listOf(
food.name,
food.defaultUnit,
dateStr
)
)
}
return rows
}
fun parseRowsToMeals(rows: List<List<Any>>, zoneId: ZoneId = ZoneId.systemDefault()): List<MealEntry> {
if (rows.size <= 1) return emptyList()
val meals = mutableListOf<MealEntry>()
// Skip header row
for (i in 1 until rows.size) {
val row = rows[i]
if (row.isEmpty()) continue
try {
val dateStr = row.getOrNull(0)?.toString()?.trim().orEmpty()
val timeStr = row.getOrNull(1)?.toString()?.trim().orEmpty()
val typeLabel = row.getOrNull(2)?.toString()?.trim().orEmpty()
val hungerVal = row.getOrNull(3)?.toString()?.toIntOrNull() ?: 5
val satietyVal = row.getOrNull(5)?.toString()?.toIntOrNull() ?: 7
val foodsRaw = row.getOrNull(7)?.toString()?.trim().orEmpty()
val note = row.getOrNull(8)?.toString()?.trim().orEmpty()
val photoCell = row.getOrNull(9)?.toString()?.trim().orEmpty()
val timestamp = try {
val ldt = LocalDateTime.parse("$dateStr $timeStr", dateTimeFormatter)
ldt.atZone(zoneId).toInstant().toEpochMilli()
} catch (_: Exception) {
System.currentTimeMillis()
}
val mealType = MealType.fromString(typeLabel)
val foodItems = CsvImporter.parseFoodItems(foodsRaw).map { it.serialize() }
val photoUris = if (photoCell.contains("http")) {
photoCell.split(";").map { it.trim() }.filter { it.startsWith("http") }
} else {
emptyList()
}
val mealId = "restored_${timestamp}_${mealType.name.lowercase()}"
meals.add(
MealEntry(
id = mealId,
mealType = mealType.name,
mealTimestamp = timestamp,
hungerBefore = hungerVal.coerceIn(1, 10),
satietyAfter = satietyVal.coerceIn(1, 10),
note = note,
foodItemsSerialized = foodItems,
photoUris = photoUris,
photosBase64 = emptyList()
)
)
} catch (_: Exception) {
// Ignore malformed individual rows
}
}
return meals
}
fun parseRowsToCustomFoods(rows: List<List<Any>>): List<LocalCustomFoodEntity> {
if (rows.size <= 1) return emptyList()
val foods = mutableListOf<LocalCustomFoodEntity>()
for (i in 1 until rows.size) {
val row = rows[i]
if (row.isEmpty()) continue
val name = row.getOrNull(0)?.toString()?.trim().orEmpty()
if (name.isBlank()) continue
val unitStr = row.getOrNull(1)?.toString()?.trim() ?: "g"
val unit = FoodUnit.fromCode(unitStr)
foods.add(LocalCustomFoodEntity.create(name, unit))
}
return foods
}
}
@@ -1,6 +1,7 @@
package com.example.util
import android.util.Log
import com.example.data.local.LocalCustomFoodEntity
import com.example.data.model.MealEntry
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
@@ -17,34 +18,45 @@ data class GoogleSheetsSyncResult(
val spreadsheetId: String,
val spreadsheetUrl: String,
val mealsCount: Int,
val foodsCount: Int = 0,
val timestamp: Long = System.currentTimeMillis()
)
data class SpreadsheetRestoreData(
val meals: List<MealEntry>,
val foods: List<LocalCustomFoodEntity>
)
class AuthExpiredException(message: String) : IllegalStateException(message)
object GoogleSheetsSyncService {
private const val TAG = "GoogleSheetsSync"
const val SPREADSHEET_TITLE = "Satiéa — Journal des Repas"
const val SHEET_TAB_TITLE = "Journal des repas"
const val SHEET_TAB_MEALS = "Journal des repas"
const val SHEET_TAB_FOODS = "Mes plats et aliments"
// Backward compatibility
const val SHEET_TAB_TITLE = SHEET_TAB_MEALS
private val jsonMediaType = "application/json; charset=utf-8".toMediaType()
private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.connectTimeout(25, TimeUnit.SECONDS)
.readTimeout(25, TimeUnit.SECONDS)
.writeTimeout(25, TimeUnit.SECONDS)
.build()
suspend fun getOrCreateSpreadsheet(
accessToken: String,
cachedSpreadsheetId: String? = null
cachedSpreadsheetId: String? = null,
parentFolderId: String? = null
): Result<Pair<String, String>> = withContext(Dispatchers.IO) {
try {
// 1. If we have a cached spreadsheetId, verify it still exists
// 1. If we have a cached spreadsheetId, verify it still exists and ensure 2 tabs
if (!cachedSpreadsheetId.isNullOrBlank()) {
val checkRequest = Request.Builder()
.url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl")
.url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl,sheets.properties.title")
.header("Authorization", "Bearer $accessToken")
.get()
.build()
@@ -58,6 +70,10 @@ object GoogleSheetsSyncService {
val json = JSONObject(body)
val id = json.getString("spreadsheetId")
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
ensureCustomFoodsTabExists(accessToken, id, json)
if (parentFolderId != null) {
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
}
return@withContext Result.success(Pair(id, url))
}
}
@@ -67,7 +83,7 @@ object GoogleSheetsSyncService {
val query = "name = '$SPREADSHEET_TITLE' and mimeType = 'application/vnd.google-apps.spreadsheet' and trashed = false"
val searchUrl = "https://www.googleapis.com/drive/v3/files?q=" +
URLEncoder.encode(query, "UTF-8") +
"&fields=" + URLEncoder.encode("files(id, name, webViewLink)", "UTF-8") +
"&fields=" + URLEncoder.encode("files(id, name, webViewLink, parents)", "UTF-8") +
"&spaces=drive"
val searchRequest = Request.Builder()
@@ -88,12 +104,16 @@ object GoogleSheetsSyncService {
val firstFile = files.getJSONObject(0)
val id = firstFile.getString("id")
val link = firstFile.optString("webViewLink", "https://docs.google.com/spreadsheets/d/$id/edit")
ensureCustomFoodsTabExists(accessToken, id, null)
if (parentFolderId != null) {
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
}
return@withContext Result.success(Pair(id, link))
}
}
}
// 3. Not found, create a new Google Sheet with dedicated named tab
// 3. Not found: create a new Google Sheet with BOTH tabs (Meals + Custom Foods)
val createPayload = JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SPREADSHEET_TITLE)
@@ -101,7 +121,15 @@ object GoogleSheetsSyncService {
put("sheets", JSONArray().apply {
put(JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SHEET_TAB_TITLE)
put("title", SHEET_TAB_MEALS)
put("gridProperties", JSONObject().apply {
put("frozenRowCount", 1)
})
})
})
put(JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SHEET_TAB_FOODS)
put("gridProperties", JSONObject().apply {
put("frozenRowCount", 1)
})
@@ -129,6 +157,12 @@ object GoogleSheetsSyncService {
val json = JSONObject(bodyStr)
val id = json.getString("spreadsheetId")
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
// Move new sheet into Satiéa Drive folder
if (parentFolderId != null) {
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
}
Result.success(Pair(id, url))
}
} catch (e: Exception) {
@@ -137,79 +171,232 @@ object GoogleSheetsSyncService {
}
}
private suspend fun ensureCustomFoodsTabExists(
accessToken: String,
spreadsheetId: String,
spreadsheetJson: JSONObject?
) = withContext(Dispatchers.IO) {
try {
val json = spreadsheetJson ?: run {
val req = Request.Builder()
.url("https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId?fields=sheets.properties.title")
.header("Authorization", "Bearer $accessToken")
.get()
.build()
okHttpClient.newCall(req).execute().use { resp ->
if (resp.isSuccessful) JSONObject(resp.body?.string().orEmpty()) else null
}
} ?: return@withContext
val sheets = json.optJSONArray("sheets") ?: return@withContext
var hasFoodsTab = false
for (i in 0 until sheets.length()) {
val title = sheets.getJSONObject(i).optJSONObject("properties")?.optString("title")
if (title == SHEET_TAB_FOODS) {
hasFoodsTab = true
break
}
}
if (!hasFoodsTab) {
val addSheetPayload = JSONObject().apply {
put("requests", JSONArray().apply {
put(JSONObject().apply {
put("addSheet", JSONObject().apply {
put("properties", JSONObject().apply {
put("title", SHEET_TAB_FOODS)
put("gridProperties", JSONObject().apply {
put("frozenRowCount", 1)
})
})
})
})
})
}
val addSheetReq = Request.Builder()
.url("https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId:batchUpdate")
.header("Authorization", "Bearer $accessToken")
.post(addSheetPayload.toString().toRequestBody(jsonMediaType))
.build()
okHttpClient.newCall(addSheetReq).execute().use { resp ->
if (!resp.isSuccessful) {
Log.w(TAG, "Could not add sheet tab $SHEET_TAB_FOODS: ${resp.code}")
}
}
}
} catch (e: Exception) {
Log.w(TAG, "Error checking/adding $SHEET_TAB_FOODS tab: ${e.message}")
}
}
suspend fun syncMealsAndFoods(
accessToken: String,
spreadsheetId: String,
meals: List<MealEntry>,
foods: List<LocalCustomFoodEntity>,
photoLinkProvider: (String) -> String? = { null }
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
try {
// 1. Sync Meals on SHEET_TAB_MEALS
val mealRows = GoogleSheetsDataFormatter.formatMealsToRows(meals = meals, photoLinkProvider = photoLinkProvider)
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_MEALS, "A:Z", "A1", mealRows)
// 2. Sync Custom Foods on SHEET_TAB_FOODS
val foodRows = GoogleSheetsDataFormatter.formatCustomFoodsToRows(foods)
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_FOODS, "A:C", "A1", foodRows)
val spreadsheetUrl = "https://docs.google.com/spreadsheets/d/$spreadsheetId/edit"
Result.success(
GoogleSheetsSyncResult(
spreadsheetId = spreadsheetId,
spreadsheetUrl = spreadsheetUrl,
mealsCount = meals.size,
foodsCount = foods.size
)
)
} catch (e: Exception) {
Log.e(TAG, "Error in syncMealsAndFoods", e)
Result.failure(e)
}
}
// Backward-compatibility overload
suspend fun syncMeals(
accessToken: String,
spreadsheetId: String,
meals: List<MealEntry>
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
): Result<GoogleSheetsSyncResult> {
return syncMealsAndFoods(accessToken, spreadsheetId, meals, emptyList())
}
private suspend fun writeRowsToSheet(
accessToken: String,
spreadsheetId: String,
sheetTitle: String,
clearRangeColumns: String,
startCell: String,
rows: List<List<Any>>
) = withContext(Dispatchers.IO) {
// Clear previous range
val clearRange = URLEncoder.encode("'$sheetTitle'!$clearRangeColumns", "UTF-8")
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear"
val clearRequest = Request.Builder()
.url(clearUrl)
.header("Authorization", "Bearer $accessToken")
.post("{}".toRequestBody(jsonMediaType))
.build()
try {
val rows = GoogleSheetsDataFormatter.formatMealsToRows(meals)
// 1. Clear previous content with explicit sheet range to remove stale deleted rows
val clearRange = URLEncoder.encode("'$SHEET_TAB_TITLE'!A:Z", "UTF-8")
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear"
val clearRequest = Request.Builder()
.url(clearUrl)
.header("Authorization", "Bearer $accessToken")
.post("{}".toRequestBody(jsonMediaType))
.build()
try {
okHttpClient.newCall(clearRequest).execute().use { clearResp ->
if (clearResp.code == 401) {
return@withContext Result.failure(AuthExpiredException("Token Google expiré (401)"))
}
}
} catch (e: Exception) {
if (e is AuthExpiredException) throw e
Log.w(TAG, "Clear range warning: ${e.message}")
}
// 2. Put formatted values starting at A1 using RAW input (neutralizes CWE-1236 Formula Injection)
val jsonValuesArray = JSONArray()
for (row in rows) {
val rowArray = JSONArray()
for (item in row) {
rowArray.put(item)
}
jsonValuesArray.put(rowArray)
}
val writePayload = JSONObject().apply {
put("range", "'$SHEET_TAB_TITLE'!A1")
put("majorDimension", "ROWS")
put("values", jsonValuesArray)
}
val writeRange = URLEncoder.encode("'$SHEET_TAB_TITLE'!A1", "UTF-8")
val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$writeRange?valueInputOption=RAW"
val writeRequest = Request.Builder()
.url(writeUrl)
.header("Authorization", "Bearer $accessToken")
.put(writePayload.toString().toRequestBody(jsonMediaType))
.build()
okHttpClient.newCall(writeRequest).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) {
val errorMsg = parseErrorMessage(bodyStr, response.code)
return@withContext Result.failure(IllegalStateException("Mise à jour de la feuille Google Sheets échouée: $errorMsg"))
}
val spreadsheetUrl = "https://docs.google.com/spreadsheets/d/$spreadsheetId/edit"
Result.success(
GoogleSheetsSyncResult(
spreadsheetId = spreadsheetId,
spreadsheetUrl = spreadsheetUrl,
mealsCount = meals.size
)
)
okHttpClient.newCall(clearRequest).execute().use { resp ->
if (resp.code == 401) throw AuthExpiredException("Token Google expiré (401)")
}
} catch (e: Exception) {
Log.e(TAG, "Error in syncMeals", e)
if (e is AuthExpiredException) throw e
Log.w(TAG, "Clear range '$sheetTitle' warning: ${e.message}")
}
// Put values in RAW mode (neutralizes formula injection)
val jsonValuesArray = JSONArray()
for (row in rows) {
val rowArray = JSONArray()
for (item in row) {
rowArray.put(item)
}
jsonValuesArray.put(rowArray)
}
val writePayload = JSONObject().apply {
put("range", "'$sheetTitle'!$startCell")
put("majorDimension", "ROWS")
put("values", jsonValuesArray)
}
val writeRange = URLEncoder.encode("'$sheetTitle'!$startCell", "UTF-8")
val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$writeRange?valueInputOption=RAW"
val writeRequest = Request.Builder()
.url(writeUrl)
.header("Authorization", "Bearer $accessToken")
.put(writePayload.toString().toRequestBody(jsonMediaType))
.build()
okHttpClient.newCall(writeRequest).execute().use { response ->
val bodyStr = response.body?.string().orEmpty()
if (response.code == 401) throw AuthExpiredException("Token Google expiré (401)")
if (!response.isSuccessful) {
val errorMsg = parseErrorMessage(bodyStr, response.code)
throw IllegalStateException("Mise à jour de la feuille '$sheetTitle' échouée: $errorMsg")
}
}
}
suspend fun readSpreadsheetData(
accessToken: String,
spreadsheetId: String
): Result<SpreadsheetRestoreData> = withContext(Dispatchers.IO) {
try {
// 1. Read Meals
val mealsRange = URLEncoder.encode("'$SHEET_TAB_MEALS'!A1:Z", "UTF-8")
val mealsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$mealsRange"
val mealsReq = Request.Builder()
.url(mealsUrl)
.header("Authorization", "Bearer $accessToken")
.get()
.build()
val mealRows = mutableListOf<List<Any>>()
okHttpClient.newCall(mealsReq).execute().use { resp ->
if (resp.code == 401) return@withContext Result.failure(AuthExpiredException("Token expiré"))
if (resp.isSuccessful) {
val body = resp.body?.string().orEmpty()
val values = JSONObject(body).optJSONArray("values")
if (values != null) {
for (i in 0 until values.length()) {
val r = values.getJSONArray(i)
val rowList = mutableListOf<Any>()
for (j in 0 until r.length()) {
rowList.add(r.get(j))
}
mealRows.add(rowList)
}
}
}
}
// 2. Read Custom Foods
val foodsRange = URLEncoder.encode("'$SHEET_TAB_FOODS'!A1:C", "UTF-8")
val foodsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$foodsRange"
val foodsReq = Request.Builder()
.url(foodsUrl)
.header("Authorization", "Bearer $accessToken")
.get()
.build()
val foodRows = mutableListOf<List<Any>>()
okHttpClient.newCall(foodsReq).execute().use { resp ->
if (resp.isSuccessful) {
val body = resp.body?.string().orEmpty()
val values = JSONObject(body).optJSONArray("values")
if (values != null) {
for (i in 0 until values.length()) {
val r = values.getJSONArray(i)
val rowList = mutableListOf<Any>()
for (j in 0 until r.length()) {
rowList.add(r.get(j))
}
foodRows.add(rowList)
}
}
}
}
val parsedMeals = GoogleSheetsDataFormatter.parseRowsToMeals(mealRows)
val parsedFoods = GoogleSheetsDataFormatter.parseRowsToCustomFoods(foodRows)
Result.success(SpreadsheetRestoreData(meals = parsedMeals, foods = parsedFoods))
} catch (e: Exception) {
Log.e(TAG, "Error in readSpreadsheetData", e)
Result.failure(e)
}
}