mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
feat: support meal photo URIs and improve UI events
- Add `photoUris` field to `MealEntry` and update Firestore rules. - Implement `UiEvent` handling in `MainActivity` for navigation/links. - Remove sensitive email data from error logs and clean up manifest.
This commit is contained in:
1 parent
f0487453c9
commit
87bbb448c2
34 files changed
+2026
-1170
No files matched your search
@@ -10,21 +10,24 @@ import com.example.data.model.MealType
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.time.Instant
|
||||
import java.time.LocalDate
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
|
||||
object CsvExporter {
|
||||
|
||||
private val fileDateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.FRENCH)
|
||||
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH)
|
||||
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
|
||||
|
||||
fun buildDefaultFileName(): String {
|
||||
val dateStr = SimpleDateFormat("yyyy-MM-dd", Locale.FRENCH).format(Date())
|
||||
val dateStr = fileDateFormatter.format(LocalDate.now())
|
||||
return "satiea_repas_$dateStr.csv"
|
||||
}
|
||||
|
||||
fun generateCsvContent(meals: List<MealEntry>): String {
|
||||
val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.FRENCH)
|
||||
val timeFormat = SimpleDateFormat("HH:mm", Locale.FRENCH)
|
||||
|
||||
fun generateCsvContent(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): String {
|
||||
val sb = StringBuilder()
|
||||
// UTF-8 BOM for proper French accent display in Excel / LibreOffice / Google Sheets
|
||||
sb.append('\uFEFF')
|
||||
@@ -32,15 +35,15 @@ object CsvExporter {
|
||||
|
||||
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 zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)
|
||||
val dateStr = dateFormatter.format(zonedDateTime)
|
||||
val timeStr = timeFormatter.format(zonedDateTime)
|
||||
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 = escapeCsvField(meal.note)
|
||||
val photoCount = meal.photosBase64.size
|
||||
val photoCount = meal.displayPhotoUris.size
|
||||
|
||||
sb.append(escapeCsvField(dateStr)).append(',')
|
||||
sb.append(escapeCsvField(timeStr)).append(',')
|
||||
|
||||
@@ -11,9 +11,11 @@ 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.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
import java.util.UUID
|
||||
|
||||
@@ -25,17 +27,18 @@ data class CsvImportResult(
|
||||
|
||||
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 supportedDatePatterns = listOf(
|
||||
"dd/MM/yyyy",
|
||||
"yyyy-MM-dd",
|
||||
"dd-MM-yyyy",
|
||||
"d/M/yyyy"
|
||||
)
|
||||
|
||||
private val supportedTimeFormats = listOf(
|
||||
SimpleDateFormat("HH:mm", Locale.FRENCH),
|
||||
SimpleDateFormat("H:mm", Locale.FRENCH),
|
||||
SimpleDateFormat("HH:mm:ss", Locale.FRENCH)
|
||||
private val supportedTimePatterns = listOf(
|
||||
"HH:mm",
|
||||
"H:mm",
|
||||
"HH:mm:ss",
|
||||
"H:mm:ss"
|
||||
)
|
||||
|
||||
suspend fun importFromUri(
|
||||
@@ -157,36 +160,32 @@ object CsvImporter {
|
||||
return if (colIndex != null && colIndex in row.indices) row[colIndex].trim() else ""
|
||||
}
|
||||
|
||||
private fun parseTimestamp(dateStr: String, timeStr: String): Long? {
|
||||
private fun parseTimestamp(dateStr: String, timeStr: String, zoneId: ZoneId = ZoneId.systemDefault()): Long? {
|
||||
if (dateStr.isBlank()) return null
|
||||
|
||||
var parsedDate: Date? = null
|
||||
for (df in supportedDateFormats) {
|
||||
var parsedLocalDate: LocalDate? = null
|
||||
for (pattern in supportedDatePatterns) {
|
||||
try {
|
||||
parsedDate = df.parse(dateStr.trim())
|
||||
if (parsedDate != null) break
|
||||
parsedLocalDate = LocalDate.parse(dateStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH))
|
||||
if (parsedLocalDate != null) break
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
if (parsedDate == null) return null
|
||||
|
||||
val cal = Calendar.getInstance().apply { time = parsedDate }
|
||||
if (parsedLocalDate == null) return null
|
||||
|
||||
var parsedLocalTime = LocalTime.NOON
|
||||
if (timeStr.isNotBlank()) {
|
||||
for (tf in supportedTimeFormats) {
|
||||
for (pattern in supportedTimePatterns) {
|
||||
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
|
||||
}
|
||||
parsedLocalTime = LocalTime.parse(timeStr.trim(), DateTimeFormatter.ofPattern(pattern, Locale.FRENCH))
|
||||
break
|
||||
} catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
return cal.timeInMillis
|
||||
|
||||
return LocalDateTime.of(parsedLocalDate, parsedLocalTime)
|
||||
.atZone(zoneId)
|
||||
.toInstant()
|
||||
.toEpochMilli()
|
||||
}
|
||||
|
||||
private fun parseMealType(raw: String): MealType {
|
||||
|
||||
@@ -3,8 +3,9 @@ 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.time.Instant
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Locale
|
||||
|
||||
object GoogleSheetsDataFormatter {
|
||||
@@ -22,10 +23,10 @@ object GoogleSheetsDataFormatter {
|
||||
"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)
|
||||
private val dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy", Locale.FRENCH)
|
||||
private val timeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.FRENCH)
|
||||
|
||||
fun formatMealsToRows(meals: List<MealEntry>, zoneId: ZoneId = ZoneId.systemDefault()): List<List<Any>> {
|
||||
val rows = mutableListOf<List<Any>>()
|
||||
// Header row
|
||||
rows.add(HEADERS)
|
||||
@@ -34,15 +35,15 @@ object GoogleSheetsDataFormatter {
|
||||
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 zonedDateTime = Instant.ofEpochMilli(meal.mealTimestamp).atZone(zoneId)
|
||||
val dateStr = dateFormatter.format(zonedDateTime)
|
||||
val timeStr = timeFormatter.format(zonedDateTime)
|
||||
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
|
||||
val photosCount = meal.displayPhotoUris.size
|
||||
|
||||
rows.add(
|
||||
listOf(
|
||||
|
||||
@@ -5,72 +5,120 @@ import android.graphics.Bitmap
|
||||
import android.graphics.BitmapFactory
|
||||
import android.net.Uri
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.InputStream
|
||||
import java.util.UUID
|
||||
|
||||
object ImageUtils {
|
||||
|
||||
suspend fun uriToBase64(context: Context, uri: Uri, maxWidth: Int = 480, maxHeight: Int = 480): String? =
|
||||
withContext(Dispatchers.IO) {
|
||||
try {
|
||||
var inputStream: InputStream? = context.contentResolver.openInputStream(uri) ?: return@withContext null
|
||||
private const val TAG = "ImageUtils"
|
||||
private const val PHOTOS_DIR_NAME = "meal_photos"
|
||||
private const val MAX_DIMENSION = 960
|
||||
private const val JPEG_QUALITY = 80
|
||||
|
||||
// Decode bounds first
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
inputStream?.close()
|
||||
|
||||
// Calculate inSampleSize
|
||||
var inSampleSize = 1
|
||||
if (options.outHeight > maxHeight || options.outWidth > maxWidth) {
|
||||
val halfHeight = options.outHeight / 2
|
||||
val halfWidth = options.outWidth / 2
|
||||
while (halfHeight / inSampleSize >= maxHeight && halfWidth / inSampleSize >= maxWidth) {
|
||||
inSampleSize *= 2
|
||||
}
|
||||
}
|
||||
|
||||
// Decode actual bitmap
|
||||
val decodeOptions = BitmapFactory.Options().apply {
|
||||
this.inSampleSize = inSampleSize
|
||||
}
|
||||
inputStream = context.contentResolver.openInputStream(uri)
|
||||
val originalBitmap = BitmapFactory.decodeStream(inputStream, null, decodeOptions)
|
||||
inputStream?.close()
|
||||
|
||||
if (originalBitmap == null) return@withContext null
|
||||
|
||||
// Scale to exact target bounds
|
||||
val scaledBitmap = if (originalBitmap.width > maxWidth || originalBitmap.height > maxHeight) {
|
||||
val ratio = minOf(
|
||||
maxWidth.toFloat() / originalBitmap.width,
|
||||
maxHeight.toFloat() / originalBitmap.height
|
||||
)
|
||||
val targetW = (originalBitmap.width * ratio).toInt().coerceAtLeast(1)
|
||||
val targetH = (originalBitmap.height * ratio).toInt().coerceAtLeast(1)
|
||||
Bitmap.createScaledBitmap(originalBitmap, targetW, targetH, true)
|
||||
} else {
|
||||
originalBitmap
|
||||
}
|
||||
|
||||
val outputStream = ByteArrayOutputStream()
|
||||
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, outputStream)
|
||||
val bytes = outputStream.toByteArray()
|
||||
Base64.encodeToString(bytes, Base64.NO_WRAP)
|
||||
} catch (e: Exception) {
|
||||
null
|
||||
fun getPhotosDirectory(context: Context): File {
|
||||
return File(context.applicationContext.filesDir, PHOTOS_DIR_NAME).apply {
|
||||
if (!exists()) {
|
||||
mkdirs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveImageToPrivateStorage(
|
||||
context: Context,
|
||||
sourceUri: Uri
|
||||
): String? = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
var inputStream: InputStream? = context.contentResolver.openInputStream(sourceUri)
|
||||
?: return@withContext null
|
||||
|
||||
// 1. Decode bounds
|
||||
val options = BitmapFactory.Options().apply {
|
||||
inJustDecodeBounds = true
|
||||
}
|
||||
BitmapFactory.decodeStream(inputStream, null, options)
|
||||
inputStream?.close()
|
||||
|
||||
// 2. Calculate inSampleSize for memory safety
|
||||
var inSampleSize = 1
|
||||
if (options.outHeight > MAX_DIMENSION || options.outWidth > MAX_DIMENSION) {
|
||||
val halfHeight = options.outHeight / 2
|
||||
val halfWidth = options.outWidth / 2
|
||||
while (halfHeight / inSampleSize >= MAX_DIMENSION && halfWidth / inSampleSize >= MAX_DIMENSION) {
|
||||
inSampleSize *= 2
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Decode actual bitmap
|
||||
val decodeOptions = BitmapFactory.Options().apply {
|
||||
this.inSampleSize = inSampleSize
|
||||
}
|
||||
inputStream = context.contentResolver.openInputStream(sourceUri)
|
||||
val decodedBitmap = BitmapFactory.decodeStream(inputStream, null, decodeOptions)
|
||||
inputStream?.close()
|
||||
|
||||
if (decodedBitmap == null) return@withContext null
|
||||
|
||||
// 4. Scale to max dimension while preserving aspect ratio
|
||||
val scaledBitmap = if (decodedBitmap.width > MAX_DIMENSION || decodedBitmap.height > MAX_DIMENSION) {
|
||||
val ratio = minOf(
|
||||
MAX_DIMENSION.toFloat() / decodedBitmap.width,
|
||||
MAX_DIMENSION.toFloat() / decodedBitmap.height
|
||||
)
|
||||
val targetW = (decodedBitmap.width * ratio).toInt().coerceAtLeast(1)
|
||||
val targetH = (decodedBitmap.height * ratio).toInt().coerceAtLeast(1)
|
||||
Bitmap.createScaledBitmap(decodedBitmap, targetW, targetH, true).also {
|
||||
if (it != decodedBitmap) decodedBitmap.recycle()
|
||||
}
|
||||
} else {
|
||||
decodedBitmap
|
||||
}
|
||||
|
||||
// 5. Write directly to private JPEG file
|
||||
val targetDir = getPhotosDirectory(context)
|
||||
val uniqueFileName = "meal_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}.jpg"
|
||||
val targetFile = File(targetDir, uniqueFileName)
|
||||
|
||||
FileOutputStream(targetFile).use { outStream ->
|
||||
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, outStream)
|
||||
outStream.flush()
|
||||
}
|
||||
scaledBitmap.recycle()
|
||||
|
||||
Uri.fromFile(targetFile).toString()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error saving image to private storage: ${e.message}", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
fun deletePhotoFile(photoUriStr: String?): Boolean {
|
||||
if (photoUriStr.isNullOrBlank()) return false
|
||||
return try {
|
||||
val uri = Uri.parse(photoUriStr)
|
||||
val path = uri.path
|
||||
if (path != null) {
|
||||
val file = File(path)
|
||||
if (file.exists()) {
|
||||
file.delete()
|
||||
} else false
|
||||
} else false
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Could not delete photo file: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// Retained for backward-compatibility if old Base64 entries need temporary conversion
|
||||
fun base64ToBitmap(base64Str: String): Bitmap? {
|
||||
return try {
|
||||
val bytes = Base64.decode(base64Str, Base64.DEFAULT)
|
||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
||||
} catch (e: Exception) {
|
||||
} catch (_: Exception) {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user