Files
satiea/app/src/main/java/com/example/domain/GoogleSheetsSyncUseCase.kt
T
bleackstorm 3397fc1c60 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.
2026-11-08 20:38:08 +01:00

272 lines
12 KiB
Kotlin

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
import com.google.android.gms.auth.UserRecoverableAuthException
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 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,
private val sheetsPrefs: GoogleSheetsPreferencesManager
) {
private val syncMutex = Mutex()
suspend fun execute(): SheetsSyncResult = syncMutex.withLock {
withContext(Dispatchers.IO) {
executeInternal(retryOnAuthFailure = true)
}
}
private suspend fun executeInternal(retryOnAuthFailure: Boolean): SheetsSyncResult {
val tokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
if (tokenResult.isFailure) {
val exception = tokenResult.exceptionOrNull()
return if (exception is UserRecoverableAuthException) {
SheetsSyncResult.RecoverableAuth(
message = "Autorisation requise pour Google Sheets & Drive",
intent = exception.intent
)
} else {
SheetsSyncResult.Failure(exception?.localizedMessage ?: "Impossible d'obtenir l'autorisation Google")
}
}
var token = tokenResult.getOrThrow()
// 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) {
GoogleSheetsAuthHelper.invalidateToken(context, token)
val refreshedTokenResult = GoogleSheetsAuthHelper.getAccessToken(context)
if (refreshedTokenResult.isSuccess) {
token = refreshedTokenResult.getOrThrow()
spreadsheetResult = GoogleSheetsSyncService.getOrCreateSpreadsheet(
token,
sheetsPrefs.spreadsheetId,
parentFolderId = rootFolderId
)
}
}
if (spreadsheetResult.isFailure) {
val err = spreadsheetResult.exceptionOrNull()?.localizedMessage ?: "Erreur de création du classeur"
return SheetsSyncResult.Failure(err)
}
val (id, url) = spreadsheetResult.getOrThrow()
sheetsPrefs.spreadsheetId = id
sheetsPrefs.spreadsheetUrl = url
// 3. Upload missing meal photos to Google Drive Photos folder
val currentMeals = repository.getAllMealsSnapshot()
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.syncMealsAndFoods(
accessToken = token,
spreadsheetId = id,
meals = currentMeals,
foods = currentFoods,
photoLinkProvider = { sheetsPrefs.getPhotoDriveUrl(it) }
)
}
}
return if (syncResult.isSuccess) {
val res = syncResult.getOrThrow()
sheetsPrefs.lastSyncTimestamp = res.timestamp
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé avec succès"
SheetsSyncResult.Success(res.spreadsheetUrl, res.mealsCount, res.foodsCount, res.timestamp)
} else {
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
return try {
syncMutex.withLock {
withContext(Dispatchers.IO) {
val token = GoogleSheetsAuthHelper.getAccessToken(context).getOrNull() ?: return@withContext null
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 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
sheetsPrefs.lastSyncCount = res.mealsCount
sheetsPrefs.lastSyncStatus = "Synchronisé automatiquement"
res
} else null
}
}
} catch (_: Exception) {
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)
}
}
}