mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
feat: implement meal notification system
Add necessary permissions, services, and receivers to support scheduled meal notifications and boot completion handling. Also includes dependency updates and minor test fixes.
This commit is contained in:
1 parent
f13d46f778
commit
fe69d7621a
31 files changed
+2972
-350
No files matched your search
@@ -0,0 +1,333 @@
|
||||
package com.example.util
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import com.example.data.model.FoodUnit
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealFoodItem
|
||||
import com.example.data.model.MealType
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStream
|
||||
import java.io.InputStreamReader
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Calendar
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import java.util.UUID
|
||||
|
||||
data class CsvImportResult(
|
||||
val importedMeals: List<MealEntry>,
|
||||
val skippedDuplicatesCount: Int,
|
||||
val newFoodItems: List<MealFoodItem>
|
||||
)
|
||||
|
||||
object CsvImporter {
|
||||
|
||||
private val supportedDateFormats = listOf(
|
||||
SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH),
|
||||
SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH),
|
||||
SimpleDateFormat("dd-MM-yyyy", Locale.FRENCH),
|
||||
SimpleDateFormat("d/M/yyyy", Locale.FRENCH)
|
||||
)
|
||||
|
||||
private val supportedTimeFormats = listOf(
|
||||
SimpleDateFormat("HH:mm", Locale.FRENCH),
|
||||
SimpleDateFormat("H:mm", Locale.FRENCH),
|
||||
SimpleDateFormat("HH:mm:ss", Locale.FRENCH)
|
||||
)
|
||||
|
||||
suspend fun importFromUri(
|
||||
context: Context,
|
||||
uri: Uri,
|
||||
existingMeals: List<MealEntry>
|
||||
): Result<CsvImportResult> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
context.contentResolver.openInputStream(uri)?.use { inputStream ->
|
||||
parseCsvStream(inputStream, existingMeals)
|
||||
} ?: Result.failure(IllegalStateException("Impossible d'ouvrir le fichier CSV"))
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
fun parseCsvStream(
|
||||
inputStream: InputStream,
|
||||
existingMeals: List<MealEntry>
|
||||
): Result<CsvImportResult> {
|
||||
return try {
|
||||
val reader = BufferedReader(InputStreamReader(inputStream, Charsets.UTF_8))
|
||||
val lines = parseCsvRecords(reader)
|
||||
if (lines.isEmpty()) {
|
||||
return Result.failure(IllegalArgumentException("Le fichier CSV est vide"))
|
||||
}
|
||||
|
||||
val headerRow = lines[0]
|
||||
val colIndexMap = mapHeaders(headerRow)
|
||||
|
||||
val parsedMeals = mutableListOf<MealEntry>()
|
||||
var skippedDuplicates = 0
|
||||
val discoveredFoodItems = mutableListOf<MealFoodItem>()
|
||||
|
||||
// Index existing meals by (minuteTimestamp, mealType)
|
||||
val existingFingerprints = existingMeals.map { meal ->
|
||||
buildFingerprint(meal.mealTimestamp, meal.mealType)
|
||||
}.toMutableSet()
|
||||
|
||||
for (rowIndex in 1 until lines.size) {
|
||||
val row = lines[rowIndex]
|
||||
if (row.all { it.isBlank() }) continue
|
||||
|
||||
val dateStr = getColValue(row, colIndexMap["date"])
|
||||
val timeStr = getColValue(row, colIndexMap["time"])
|
||||
val mealTypeRaw = getColValue(row, colIndexMap["meal_type"])
|
||||
val hungerRaw = getColValue(row, colIndexMap["hunger"])
|
||||
val satietyRaw = getColValue(row, colIndexMap["satiety"])
|
||||
val foodsRaw = getColValue(row, colIndexMap["foods"])
|
||||
val note = getColValue(row, colIndexMap["note"])
|
||||
|
||||
val timestamp = parseTimestamp(dateStr, timeStr) ?: System.currentTimeMillis()
|
||||
val mealType = parseMealType(mealTypeRaw)
|
||||
val hunger = hungerRaw.toIntOrNull()?.coerceIn(1, 10) ?: 5
|
||||
val satiety = satietyRaw.toIntOrNull()?.coerceIn(1, 10) ?: 7
|
||||
|
||||
val fingerprint = buildFingerprint(timestamp, mealType.name)
|
||||
if (existingFingerprints.contains(fingerprint)) {
|
||||
skippedDuplicates++
|
||||
continue
|
||||
}
|
||||
|
||||
val foodItems = parseFoodItems(foodsRaw)
|
||||
discoveredFoodItems.addAll(foodItems)
|
||||
|
||||
val newMeal = MealEntry(
|
||||
id = "local_imp_${UUID.randomUUID().toString().take(8)}",
|
||||
userId = "",
|
||||
mealType = mealType.name,
|
||||
mealTimestamp = timestamp,
|
||||
hungerBefore = hunger,
|
||||
satietyAfter = satiety,
|
||||
note = note,
|
||||
foodItemsSerialized = foodItems.map { it.serialize() },
|
||||
photosBase64 = emptyList()
|
||||
)
|
||||
|
||||
parsedMeals.add(newMeal)
|
||||
existingFingerprints.add(fingerprint)
|
||||
}
|
||||
|
||||
Result.success(
|
||||
CsvImportResult(
|
||||
importedMeals = parsedMeals,
|
||||
skippedDuplicatesCount = skippedDuplicates,
|
||||
newFoodItems = discoveredFoodItems.distinctBy { it.name.lowercase().trim() }
|
||||
)
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun buildFingerprint(timestamp: Long, mealType: String): String {
|
||||
val minute = timestamp / 60_000
|
||||
return "${mealType.uppercase()}_$minute"
|
||||
}
|
||||
|
||||
private fun mapHeaders(headerRow: List<String>): Map<String, Int> {
|
||||
val map = mutableMapOf<String, Int>()
|
||||
for ((index, rawCol) in headerRow.withIndex()) {
|
||||
val col = java.text.Normalizer.normalize(rawCol.trim().lowercase(Locale.FRENCH), java.text.Normalizer.Form.NFD)
|
||||
.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")
|
||||
|
||||
when {
|
||||
col == "date" -> map["date"] = index
|
||||
col.contains("heure") || col == "time" -> map["time"] = index
|
||||
col.contains("type") -> map["meal_type"] = index
|
||||
col.contains("faim") && !col.contains("ressenti") -> map["hunger"] = index
|
||||
col.contains("satiete") && !col.contains("ressenti") -> map["satiety"] = index
|
||||
col.contains("aliment") || col.contains("plat") -> map["foods"] = index
|
||||
col.contains("note") || col.contains("commentaire") -> map["note"] = index
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
private fun getColValue(row: List<String>, colIndex: Int?): String {
|
||||
return if (colIndex != null && colIndex in row.indices) row[colIndex].trim() else ""
|
||||
}
|
||||
|
||||
private fun parseTimestamp(dateStr: String, timeStr: String): Long? {
|
||||
if (dateStr.isBlank()) return null
|
||||
|
||||
var parsedDate: Date? = null
|
||||
for (df in supportedDateFormats) {
|
||||
try {
|
||||
parsedDate = df.parse(dateStr.trim())
|
||||
if (parsedDate != null) break
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
if (parsedDate == null) return null
|
||||
|
||||
val cal = Calendar.getInstance().apply { time = parsedDate }
|
||||
|
||||
if (timeStr.isNotBlank()) {
|
||||
for (tf in supportedTimeFormats) {
|
||||
try {
|
||||
val parsedTime = tf.parse(timeStr.trim())
|
||||
if (parsedTime != null) {
|
||||
val timeCal = Calendar.getInstance().apply { time = parsedTime }
|
||||
cal.set(Calendar.HOUR_OF_DAY, timeCal.get(Calendar.HOUR_OF_DAY))
|
||||
cal.set(Calendar.MINUTE, timeCal.get(Calendar.MINUTE))
|
||||
cal.set(Calendar.SECOND, 0)
|
||||
cal.set(Calendar.MILLISECOND, 0)
|
||||
break
|
||||
}
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
return cal.timeInMillis
|
||||
}
|
||||
|
||||
private fun parseMealType(raw: String): MealType {
|
||||
val clean = java.text.Normalizer.normalize(raw.trim().lowercase(Locale.FRENCH), java.text.Normalizer.Form.NFD)
|
||||
.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")
|
||||
|
||||
return when {
|
||||
clean.contains("petit") || clean.contains("breakfast") -> MealType.BREAKFAST
|
||||
clean.contains("dej") || clean.contains("lunch") || clean.contains("midi") -> MealType.LUNCH
|
||||
clean.contains("collat") || clean.contains("gout") || clean.contains("snack") -> MealType.SNACK
|
||||
clean.contains("din") || clean.contains("dinner") || clean.contains("soir") || clean.contains("souper") -> MealType.DINNER
|
||||
else -> MealType.LUNCH
|
||||
}
|
||||
}
|
||||
|
||||
fun parseFoodItems(raw: String): List<MealFoodItem> {
|
||||
val trimmed = raw.trim()
|
||||
if (trimmed.isEmpty()) return emptyList()
|
||||
|
||||
// Delimiters between items can be ';' or '|' (or ',' if not surrounded by parenthesis)
|
||||
val tokens = if (trimmed.contains(";")) {
|
||||
trimmed.split(";").map { it.trim() }
|
||||
} else if (trimmed.contains("|") && !trimmed.contains("•")) {
|
||||
// Check if serialized pipe format (name|weight|unit) or multi items
|
||||
if (trimmed.count { it == '|' } in 1..2 && !trimmed.contains("g") && !trimmed.contains("ml")) {
|
||||
listOf(trimmed)
|
||||
} else {
|
||||
trimmed.split("|").map { it.trim() }
|
||||
}
|
||||
} else {
|
||||
listOf(trimmed)
|
||||
}
|
||||
|
||||
val items = mutableListOf<MealFoodItem>()
|
||||
for (token in tokens) {
|
||||
val itemStr = token.trim()
|
||||
if (itemStr.isEmpty()) continue
|
||||
|
||||
// 1. Try serialized format "name|weight|unit"
|
||||
val deserialized = MealFoodItem.deserialize(itemStr)
|
||||
if (deserialized != null && deserialized.name != itemStr) {
|
||||
items.add(deserialized)
|
||||
continue
|
||||
}
|
||||
|
||||
// 2. Parse formatted string like "Saumon grillé (150 g)" or "Riz basmati • 200 g" or "Pomme (1 portion)"
|
||||
val regex = Regex("""^(.*?)(?:\s*(?:\(|\•|-)\s*(\d+(?:[.,]\d+)?)\s*(g|ml|portions?|portion)?\s*\)?)?$""", RegexOption.IGNORE_CASE)
|
||||
val match = regex.find(itemStr)
|
||||
if (match != null) {
|
||||
val name = match.groupValues[1].trim()
|
||||
val weightStr = match.groupValues.getOrNull(2)?.replace(",", ".")?.trim()
|
||||
val weight = weightStr?.toDoubleOrNull()
|
||||
val unitRaw = match.groupValues.getOrNull(3)?.lowercase(Locale.FRENCH)?.trim().orEmpty()
|
||||
val unit = when {
|
||||
unitRaw.startsWith("ml") -> FoodUnit.ML
|
||||
unitRaw.startsWith("portion") -> FoodUnit.PORTION
|
||||
else -> FoodUnit.G
|
||||
}
|
||||
if (name.isNotEmpty()) {
|
||||
items.add(MealFoodItem(name = name, weight = weight, unit = unit))
|
||||
}
|
||||
} else {
|
||||
items.add(MealFoodItem(name = itemStr, weight = null, unit = FoodUnit.G))
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
/**
|
||||
* Robust CSV record splitter supporting quotes, commas, semicolons, and UTF-8 BOM.
|
||||
*/
|
||||
fun parseCsvRecords(reader: BufferedReader): List<List<String>> {
|
||||
val records = mutableListOf<List<String>>()
|
||||
var detectedDelimiter = ','
|
||||
|
||||
var firstLine: String? = reader.readLine() ?: return emptyList()
|
||||
// Strip BOM if present
|
||||
if (firstLine != null && firstLine.startsWith("\uFEFF")) {
|
||||
firstLine = firstLine.substring(1)
|
||||
}
|
||||
|
||||
// Auto-detect delimiter from the first line (count ; vs , outside quotes)
|
||||
val semicolonCount = firstLine?.count { it == ';' } ?: 0
|
||||
val commaCount = firstLine?.count { it == ',' } ?: 0
|
||||
if (semicolonCount > commaCount) {
|
||||
detectedDelimiter = ';'
|
||||
}
|
||||
|
||||
val fullText = StringBuilder()
|
||||
if (firstLine != null) {
|
||||
fullText.append(firstLine).append('\n')
|
||||
}
|
||||
var line: String? = reader.readLine()
|
||||
while (line != null) {
|
||||
fullText.append(line).append('\n')
|
||||
line = reader.readLine()
|
||||
}
|
||||
|
||||
val text = fullText.toString()
|
||||
val currentField = StringBuilder()
|
||||
val currentRecord = mutableListOf<String>()
|
||||
var inQuotes = false
|
||||
var i = 0
|
||||
|
||||
while (i < text.length) {
|
||||
val c = text[i]
|
||||
|
||||
if (c == '"') {
|
||||
if (inQuotes && i + 1 < text.length && text[i + 1] == '"') {
|
||||
// Escaped quote ("")
|
||||
currentField.append('"')
|
||||
i++
|
||||
} else {
|
||||
inQuotes = !inQuotes
|
||||
}
|
||||
} else if (c == detectedDelimiter && !inQuotes) {
|
||||
currentRecord.add(currentField.toString().trim())
|
||||
currentField.clear()
|
||||
} else if ((c == '\r' || c == '\n') && !inQuotes) {
|
||||
if (c == '\r' && i + 1 < text.length && text[i + 1] == '\n') {
|
||||
i++
|
||||
}
|
||||
currentRecord.add(currentField.toString().trim())
|
||||
currentField.clear()
|
||||
if (currentRecord.any { it.isNotEmpty() }) {
|
||||
records.add(currentRecord.toList())
|
||||
}
|
||||
currentRecord.clear()
|
||||
} else {
|
||||
currentField.append(c)
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if (currentField.isNotEmpty() || currentRecord.isNotEmpty()) {
|
||||
currentRecord.add(currentField.toString().trim())
|
||||
if (currentRecord.any { it.isNotEmpty() }) {
|
||||
records.add(currentRecord.toList())
|
||||
}
|
||||
}
|
||||
|
||||
return records
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.example.util
|
||||
|
||||
import android.accounts.Account
|
||||
import android.content.Context
|
||||
import com.example.R
|
||||
import com.google.android.gms.auth.GoogleAuthUtil
|
||||
import com.google.android.gms.auth.UserRecoverableAuthException
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignInClient
|
||||
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
|
||||
import com.google.android.gms.common.api.Scope
|
||||
import com.google.firebase.Firebase
|
||||
import com.google.firebase.auth.auth
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
object GoogleSheetsAuthHelper {
|
||||
|
||||
const val SCOPE_SPREADSHEETS_URL = "https://www.googleapis.com/auth/spreadsheets"
|
||||
const val SCOPE_DRIVE_FILE_URL = "https://www.googleapis.com/auth/drive.file"
|
||||
|
||||
val SCOPE_SPREADSHEETS = Scope(SCOPE_SPREADSHEETS_URL)
|
||||
val SCOPE_DRIVE_FILE = Scope(SCOPE_DRIVE_FILE_URL)
|
||||
|
||||
const val OAUTH_SCOPE_STRING = "oauth2:$SCOPE_SPREADSHEETS_URL $SCOPE_DRIVE_FILE_URL"
|
||||
|
||||
fun getGoogleSignInClient(context: Context): GoogleSignInClient {
|
||||
val serverClientId = try {
|
||||
context.getString(R.string.default_web_client_id)
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
|
||||
val gsoBuilder = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
||||
.requestEmail()
|
||||
.requestScopes(SCOPE_SPREADSHEETS, SCOPE_DRIVE_FILE)
|
||||
|
||||
if (!serverClientId.isNullOrBlank()) {
|
||||
gsoBuilder.requestIdToken(serverClientId)
|
||||
}
|
||||
|
||||
return GoogleSignIn.getClient(context, gsoBuilder.build())
|
||||
}
|
||||
|
||||
suspend fun getAccessToken(context: Context): Result<String> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val email = Firebase.auth.currentUser?.email
|
||||
?: GoogleSignIn.getLastSignedInAccount(context)?.email
|
||||
|
||||
if (email.isNullOrBlank()) {
|
||||
return@withContext Result.failure(
|
||||
IllegalStateException("Aucun compte Google connecté. Veuillez vous connecter pour synchroniser avec Google Sheets.")
|
||||
)
|
||||
}
|
||||
|
||||
val account = Account(email, "com.google")
|
||||
val token = GoogleAuthUtil.getToken(context, account, OAUTH_SCOPE_STRING)
|
||||
Result.success(token)
|
||||
} catch (e: UserRecoverableAuthException) {
|
||||
// Must be handled by prompting user via e.intent
|
||||
Result.failure(e)
|
||||
} catch (e: Exception) {
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.example.util
|
||||
|
||||
import com.example.data.model.HungerSatietyScale
|
||||
import com.example.data.model.MealEntry
|
||||
import com.example.data.model.MealType
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
object GoogleSheetsDataFormatter {
|
||||
|
||||
val HEADERS: List<String> = listOf(
|
||||
"Date",
|
||||
"Heure",
|
||||
"Type de repas",
|
||||
"Faim avant (/10)",
|
||||
"Ressenti faim",
|
||||
"Satiété après (/10)",
|
||||
"Ressenti satiété",
|
||||
"Aliments & Poids",
|
||||
"Note globale",
|
||||
"Photos jointes"
|
||||
)
|
||||
|
||||
fun formatMealsToRows(meals: List<MealEntry>): List<List<Any>> {
|
||||
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH)
|
||||
val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH)
|
||||
|
||||
val rows = mutableListOf<List<Any>>()
|
||||
// Header row
|
||||
rows.add(HEADERS)
|
||||
|
||||
// Sorted by descending timestamp (most recent first)
|
||||
val sortedMeals = meals.sortedByDescending { it.mealTimestamp }
|
||||
|
||||
for (meal in sortedMeals) {
|
||||
val dateObj = Date(meal.mealTimestamp)
|
||||
val dateStr = dateFormat.format(dateObj)
|
||||
val timeStr = timeFormat.format(dateObj)
|
||||
val mealTypeLabel = MealType.fromString(meal.mealType).displayName
|
||||
val hungerLabel = HungerSatietyScale.getHungerLabel(meal.hungerBefore)
|
||||
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.photosBase64.size
|
||||
|
||||
rows.add(
|
||||
listOf(
|
||||
dateStr,
|
||||
timeStr,
|
||||
mealTypeLabel,
|
||||
meal.hungerBefore,
|
||||
hungerLabel,
|
||||
meal.satietyAfter,
|
||||
satietyLabel,
|
||||
foodsFormatted,
|
||||
cleanNote,
|
||||
photosCount
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
return rows
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package com.example.util
|
||||
|
||||
import android.util.Log
|
||||
import com.example.data.model.MealEntry
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import okhttp3.MediaType.Companion.toMediaType
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.URLEncoder
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
data class GoogleSheetsSyncResult(
|
||||
val spreadsheetId: String,
|
||||
val spreadsheetUrl: String,
|
||||
val mealsCount: Int,
|
||||
val timestamp: Long = System.currentTimeMillis()
|
||||
)
|
||||
|
||||
object GoogleSheetsSyncService {
|
||||
|
||||
private const val TAG = "GoogleSheetsSync"
|
||||
const val SPREADSHEET_TITLE = "Satiéa — Journal des Repas"
|
||||
|
||||
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)
|
||||
.build()
|
||||
|
||||
suspend fun getOrCreateSpreadsheet(
|
||||
accessToken: String,
|
||||
cachedSpreadsheetId: String? = null
|
||||
): Result<Pair<String, String>> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
// 1. If we have a cached spreadsheetId, verify it still exists and is accessible
|
||||
if (!cachedSpreadsheetId.isNullOrBlank()) {
|
||||
val checkRequest = Request.Builder()
|
||||
.url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl")
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(checkRequest).execute().use { response ->
|
||||
if (response.isSuccessful) {
|
||||
val bodyStr = response.body?.string().orEmpty()
|
||||
val json = JSONObject(bodyStr)
|
||||
val id = json.optString("spreadsheetId", cachedSpreadsheetId)
|
||||
val url = json.optString(
|
||||
"spreadsheetUrl",
|
||||
"https://docs.google.com/spreadsheets/d/$id/edit"
|
||||
)
|
||||
return@withContext Result.success(Pair(id, url))
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Cached spreadsheet check failed, searching Drive: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Search Drive for existing spreadsheet named "Satiéa — Journal des Repas"
|
||||
val query = "name = '$SPREADSHEET_TITLE' and mimeType = 'application/vnd.google-apps.spreadsheet' and trashed = false"
|
||||
val encodedQuery = URLEncoder.encode(query, "UTF-8")
|
||||
val driveSearchUrl = "https://www.googleapis.com/drive/v3/files?q=$encodedQuery&fields=files(id,name,webViewLink)"
|
||||
|
||||
val searchRequest = Request.Builder()
|
||||
.url(driveSearchUrl)
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.get()
|
||||
.build()
|
||||
|
||||
okHttpClient.newCall(searchRequest).execute().use { searchResponse ->
|
||||
if (searchResponse.isSuccessful) {
|
||||
val body = searchResponse.body?.string().orEmpty()
|
||||
val json = JSONObject(body)
|
||||
val files = json.optJSONArray("files")
|
||||
if (files != null && files.length() > 0) {
|
||||
val firstFile = files.getJSONObject(0)
|
||||
val id = firstFile.getString("id")
|
||||
val link = firstFile.optString("webViewLink", "https://docs.google.com/spreadsheets/d/$id/edit")
|
||||
return@withContext Result.success(Pair(id, link))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Not found, create a new Google Sheet
|
||||
val createPayload = JSONObject().apply {
|
||||
put("properties", JSONObject().apply {
|
||||
put("title", SPREADSHEET_TITLE)
|
||||
})
|
||||
put("sheets", JSONArray().apply {
|
||||
put(JSONObject().apply {
|
||||
put("properties", JSONObject().apply {
|
||||
put("title", "Journal")
|
||||
put("gridProperties", JSONObject().apply {
|
||||
put("frozenRowCount", 1)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
val createRequest = Request.Builder()
|
||||
.url("https://sheets.googleapis.com/v4/spreadsheets")
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.post(createPayload.toString().toRequestBody(jsonMediaType))
|
||||
.build()
|
||||
|
||||
okHttpClient.newCall(createRequest).execute().use { response ->
|
||||
val bodyStr = response.body?.string().orEmpty()
|
||||
if (!response.isSuccessful) {
|
||||
val errorMsg = parseErrorMessage(bodyStr, response.code)
|
||||
return@withContext Result.failure(IllegalStateException("Création du classeur Google Sheets échouée: $errorMsg"))
|
||||
}
|
||||
|
||||
val json = JSONObject(bodyStr)
|
||||
val id = json.getString("spreadsheetId")
|
||||
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
|
||||
Result.success(Pair(id, url))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error in getOrCreateSpreadsheet", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun syncMeals(
|
||||
accessToken: String,
|
||||
spreadsheetId: String,
|
||||
meals: List<MealEntry>
|
||||
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
val rows = GoogleSheetsDataFormatter.formatMealsToRows(meals)
|
||||
|
||||
// 1. Clear previous content to remove stale deleted rows
|
||||
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/A1:Z:clear"
|
||||
val clearRequest = Request.Builder()
|
||||
.url(clearUrl)
|
||||
.header("Authorization", "Bearer $accessToken")
|
||||
.post("{}".toRequestBody(jsonMediaType))
|
||||
.build()
|
||||
|
||||
try {
|
||||
okHttpClient.newCall(clearRequest).execute().close()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Clear range warning: ${e.message}")
|
||||
}
|
||||
|
||||
// 2. Put formatted values starting at A1
|
||||
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", "A1")
|
||||
put("majorDimension", "ROWS")
|
||||
put("values", jsonValuesArray)
|
||||
}
|
||||
|
||||
val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/A1?valueInputOption=USER_ENTERED"
|
||||
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.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
|
||||
)
|
||||
)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error in syncMeals", e)
|
||||
Result.failure(e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseErrorMessage(body: String, statusCode: Int): String {
|
||||
return try {
|
||||
val json = JSONObject(body)
|
||||
val error = json.optJSONObject("error")
|
||||
val message = error?.optString("message")
|
||||
if (!message.isNullOrBlank()) message else "Code HTTP $statusCode"
|
||||
} catch (_: Exception) {
|
||||
"Code HTTP $statusCode"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user