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

@@ -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)
}
}
}