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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user