feat(recipes): add AI recipe importer from URL, photo, text, and Android share sheet

This commit is contained in:
bleack committed 2026-11-29 16:28:41 +01:00
1 parent 0af8021bf2
commit 9b44e488fc
8 files changed
+1303 -2

No files matched your search

+12
View File
@@ -37,6 +37,18 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
</activity>
<receiver
+71 -2
View File
@@ -58,6 +58,7 @@ import com.example.data.model.MealEntry
import com.example.data.model.MealType
import com.example.data.model.RecipeEntry
import com.example.data.preferences.ReminderPreferencesManager
import com.example.domain.RecipeImportUiState
import com.example.notification.MealNotificationManager
import com.example.ui.auth.AuthScreen
import com.example.ui.common.UiEvent
@@ -69,6 +70,7 @@ import com.example.ui.planning.BarcodeScannerScreen
import com.example.ui.planning.PlanningScreen
import com.example.ui.planning.PlanningViewModel
import com.example.ui.planning.StockDeductionDialog
import com.example.ui.recipes.ImportRecipeSheet
import com.example.ui.recipes.RecipeDetailSheet
import com.example.ui.recipes.RecipeEditorSheet
import com.example.ui.recipes.RecipesScreen
@@ -100,6 +102,7 @@ class MainActivity : ComponentActivity() {
private val viewModel: MealViewModel by viewModels()
private val planningViewModel: PlanningViewModel by viewModels()
private val openPlanningRequest = mutableStateOf(false)
private val openRecipeImportRequest = mutableStateOf(false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -122,7 +125,9 @@ class MainActivity : ComponentActivity() {
viewModel = viewModel,
planningViewModel = planningViewModel,
openPlanningRequested = openPlanningRequest.value,
onConsumeOpenPlanningRequest = { openPlanningRequest.value = false }
onConsumeOpenPlanningRequest = { openPlanningRequest.value = false },
openRecipeImportRequested = openRecipeImportRequest.value,
onConsumeOpenRecipeImportRequest = { openRecipeImportRequest.value = false }
)
}
}
@@ -145,6 +150,30 @@ class MainActivity : ComponentActivity() {
MealNotificationManager.ACTION_OPEN_PLANNING_EXPIRING -> {
openPlanningRequest.value = true
}
Intent.ACTION_SEND -> {
val mimeType = intent.type.orEmpty()
when {
mimeType.startsWith("text/") -> {
val sharedText = intent.getStringExtra(Intent.EXTRA_TEXT).orEmpty().trim()
if (sharedText.isNotBlank()) {
openRecipeImportRequest.value = true
viewModel.importRecipeFromUrlOrText(sharedText)
}
}
mimeType.startsWith("image/") -> {
@Suppress("DEPRECATION")
val sharedUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java)
} else {
intent.getParcelableExtra(Intent.EXTRA_STREAM)
}
if (sharedUri != null) {
openRecipeImportRequest.value = true
viewModel.importRecipeFromImageUri(sharedUri)
}
}
}
}
}
}
}
@@ -155,7 +184,9 @@ fun AppRoot(
viewModel: MealViewModel,
planningViewModel: PlanningViewModel,
openPlanningRequested: Boolean = false,
onConsumeOpenPlanningRequest: () -> Unit = {}
onConsumeOpenPlanningRequest: () -> Unit = {},
openRecipeImportRequested: Boolean = false,
onConsumeOpenRecipeImportRequest: () -> Unit = {}
) {
val context = LocalContext.current
var googleAccount by remember { mutableStateOf(GoogleSheetsAuthHelper.getSignedInAccount(context)) }
@@ -211,6 +242,7 @@ fun AppRoot(
var selectedRecipeId by remember { mutableStateOf<String?>(null) }
var showRecipeEditor by remember { mutableStateOf(false) }
var editingRecipe by remember { mutableStateOf<RecipeEntry?>(null) }
var showImportRecipeSheet by rememberSaveable { mutableStateOf(false) }
var showBarcodeScanner by rememberSaveable { mutableStateOf(false) }
LaunchedEffect(openPlanningRequested) {
@@ -220,6 +252,14 @@ fun AppRoot(
}
}
LaunchedEffect(openRecipeImportRequested) {
if (openRecipeImportRequested) {
currentTab = MainTab.RECIPES
showImportRecipeSheet = true
onConsumeOpenRecipeImportRequest()
}
}
// React to quick log meal requests from Widget or Notification
val quickLogMealType by viewModel.quickLogMealRequest.collectAsStateWithLifecycle()
LaunchedEffect(quickLogMealType) {
@@ -304,7 +344,17 @@ fun AppRoot(
val selectedIdeaMealType by viewModel.selectedIdeaMealType.collectAsStateWithLifecycle()
val dailyBenchmarkGap by viewModel.dailyBenchmarkGap.collectAsStateWithLifecycle()
val suggestionUiState by viewModel.suggestionUiState.collectAsStateWithLifecycle()
val recipeImportState by viewModel.recipeImportState.collectAsStateWithLifecycle()
val savedSuggestionIds by viewModel.savedSuggestionIds.collectAsStateWithLifecycle()
LaunchedEffect(recipeImportState) {
val ready = recipeImportState as? RecipeImportUiState.Ready ?: return@LaunchedEffect
showImportRecipeSheet = false
currentTab = MainTab.RECIPES
editingRecipe = ready.recipe
showRecipeEditor = true
viewModel.consumeImportedRecipe()
}
val themeMode by viewModel.themeMode.collectAsStateWithLifecycle()
val sheetsUiState by viewModel.sheetsUiState.collectAsStateWithLifecycle()
val isAutoSyncSheets by viewModel.isAutoSyncSheets.collectAsStateWithLifecycle()
@@ -555,6 +605,10 @@ fun AppRoot(
editingRecipe = null
showRecipeEditor = true
},
onImportRecipeClick = {
viewModel.dismissRecipeImport()
showImportRecipeSheet = true
},
onRecipeClick = { recipe ->
selectedRecipeId = recipe.id
},
@@ -860,6 +914,21 @@ fun AppRoot(
)
}
// AI Recipe Import Sheet (URL / Photo / Text)
if (showImportRecipeSheet || recipeImportState !is RecipeImportUiState.Idle) {
ImportRecipeSheet(
importState = recipeImportState,
onImportFromUrlOrText = { input -> viewModel.importRecipeFromUrlOrText(input) },
onImportFromImageUri = { uri -> viewModel.importRecipeFromImageUri(uri) },
onResetError = { viewModel.dismissRecipeImport() },
onShowMessage = { msg -> viewModel.emitEvent(UiEvent.ShowSnackbar(msg)) },
onDismiss = {
showImportRecipeSheet = false
viewModel.dismissRecipeImport()
}
)
}
if (showAuthSheet) {
ModalBottomSheet(
onDismissRequest = { showAuthSheet = false }
@@ -0,0 +1,480 @@
package com.example.domain
import android.graphics.Bitmap
import android.util.Log
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.MealFoodItem
import com.example.data.model.RecipeCategoryTag
import com.example.data.model.RecipeEntry
import com.google.firebase.Firebase
import com.google.firebase.ai.ai
import com.google.firebase.ai.type.Schema
import com.google.firebase.ai.type.content
import com.google.firebase.ai.type.generationConfig
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import org.json.JSONObject
import java.util.Locale
import java.util.concurrent.TimeUnit
sealed interface RecipeImportUiState {
data object Idle : RecipeImportUiState
data class Loading(val statusMessage: String) : RecipeImportUiState
data class Ready(val recipe: RecipeEntry) : RecipeImportUiState
data class Error(val message: String) : RecipeImportUiState
}
/**
* Imports recipes from web URLs (JSON-LD / HTML), pasted text (WhatsApp/SMS/notes),
* or photos/screenshots using Firebase AI Logic (gemini-3.8-flash with strict JSON Schema).
*/
class RecipeImporterAnalyzer(
private val httpClient: OkHttpClient = defaultHttpClient()
) {
private val allowedCategoryCodes = FoodCategory.entries.map { it.code }
private val allowedUnitCodes = listOf("g", "ml", "portion")
private val allowedRecipeTags = RecipeCategoryTag.entries.map { it.name }
private val responseSchema by lazy {
val ingredientSchema = Schema.obj(
properties = mapOf(
"name" to Schema.string(description = "Nom français simple et propre de l'ingrédient (ex: 'Poulet', 'Courgette', 'Crème fraîche')"),
"weight" to Schema.double(
description = "Quantité numérique pour le nombre de portions de la recette (ex: 400 pour 400 g, 250 pour 250 ml, 2 pour 2 œufs)",
nullable = true
),
"unit" to Schema.enumeration(
values = allowedUnitCodes,
description = "Unité canonique : g (grammes), ml (millilitres) ou portion (pièces/unités/cuillères)"
),
"category" to Schema.enumeration(
values = allowedCategoryCodes,
description = "Code exact de catégorie alimentaire"
)
)
)
Schema.obj(
properties = mapOf(
"isRecipe" to Schema.boolean(description = "true si le contenu contient bien une recette de cuisine, false sinon"),
"title" to Schema.string(description = "Titre court, clair et appétissant de la recette en français"),
"categoryTag" to Schema.enumeration(
values = allowedRecipeTags,
description = "Type de plat : MAIN, BREAKFAST, SNACK, DESSERT ou SIDE"
),
"prepTimeMinutes" to Schema.integer(description = "Temps total estimé (préparation + cuisson) en minutes"),
"servings" to Schema.integer(description = "Nombre de portions / personnes (au moins 1)"),
"ingredients" to Schema.array(
items = ingredientSchema,
description = "Liste complète et structurée des ingrédients"
),
"steps" to Schema.array(
items = Schema.string(description = "Étape de préparation concise et claire en français"),
description = "Étapes ordonnées de préparation"
),
"notes" to Schema.string(
description = "Astuce ou note utile courte (ou chaîne vide)",
nullable = true
)
)
)
}
private val model by lazy {
val config = generationConfig {
responseMimeType = "application/json"
responseSchema = this@RecipeImporterAnalyzer.responseSchema
temperature = 0.2f
}
Firebase.ai.generativeModel(
modelName = "gemini-3.8-flash",
generationConfig = config
)
}
suspend fun importFromUrlOrText(
rawInput: String,
downloadPhoto: suspend (String) -> String? = { null }
): Result<RecipeEntry> {
val trimmed = rawInput.trim()
if (trimmed.isBlank()) {
return Result.failure(IllegalArgumentException("Collez un lien ou le texte d'une recette."))
}
val extractedUrl = extractFirstUrl(trimmed)
val remainingWithoutUrl = if (extractedUrl != null) {
trimmed.replace(extractedUrl, "").trim()
} else {
trimmed
}
// If the input is primarily a URL (e.g. shared from Chrome or pasted link), fetch the webpage
return if (extractedUrl != null && remainingWithoutUrl.length < 120) {
importFromUrl(extractedUrl, downloadPhoto)
} else {
importFromText(trimmed, sourceUrl = extractedUrl)
}
}
suspend fun importFromUrl(
url: String,
downloadPhoto: suspend (String) -> String? = { null }
): Result<RecipeEntry> {
val cleanUrl = extractFirstUrl(url)
?: return Result.failure(IllegalArgumentException("Lien invalide. Utilisez une adresse commençant par http:// ou https://"))
val htmlResult = fetchHtml(cleanUrl)
val html = htmlResult.getOrElse { error ->
return Result.failure(
IllegalStateException(
"Impossible d'ouvrir cette page (${error.message ?: "accès refusé"}). Essayez de copier-coller le texte de la recette ou d'importer une capture d'écran."
)
)
}
val jsonLd = extractJsonLdRecipe(html)
val imageUrl = extractImageUrlFromHtml(html, jsonLd)
val extractedPayload = if (!jsonLd.isNullOrBlank()) {
"DONNÉES STRUCTURÉES JSON-LD DE LA PAGE :\n${jsonLd.take(12_000)}"
} else {
"TEXTE DE LA PAGE WEB :\n${stripHtmlToText(html).take(12_000)}"
}
val recipeResult = analyzeTextContent(extractedPayload, sourceUrl = cleanUrl)
return recipeResult.map { recipe ->
val localPhotoUri = if (!imageUrl.isNullOrBlank()) {
runCatching { downloadPhoto(imageUrl) }.getOrNull()
} else {
null
}
recipe.copy(photoUri = localPhotoUri)
}
}
suspend fun importFromText(
rawText: String,
sourceUrl: String? = null
): Result<RecipeEntry> {
val trimmed = rawText.trim()
if (trimmed.length < 15) {
return Result.failure(IllegalArgumentException("Le texte est trop court pour extraire une recette."))
}
return analyzeTextContent(trimmed.take(12_000), sourceUrl = sourceUrl)
}
suspend fun importFromBitmap(bitmap: Bitmap): Result<RecipeEntry> {
val prompt = buildBaseInstructions(
sourceDescription = "cette photo ou capture d'écran de recette (livre de cuisine, site web, réseau social)"
)
return try {
val response = withTimeout(60_000L) {
model.generateContent(
content {
image(bitmap)
text(prompt)
}
)
}
val jsonText = response.text
if (jsonText.isNullOrBlank()) {
Result.failure(IllegalStateException("Aucune recette n'a pu être lue sur cette image."))
} else {
parseRecipeJson(jsonText, sourceUrl = null)?.let { Result.success(it) }
?: Result.failure(IllegalStateException("Aucune recette reconnue sur cette image. Essayez une photo plus nette."))
}
} catch (e: TimeoutCancellationException) {
Result.failure(IllegalStateException("L'analyse a dépassé le délai (60 s). Vérifiez votre connexion et réessayez."))
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e(TAG, "Recipe image import failed", e)
Result.failure(IllegalStateException(e.localizedMessage ?: "Impossible d'analyser cette image."))
}
}
private suspend fun analyzeTextContent(
extractedText: String,
sourceUrl: String?
): Result<RecipeEntry> {
val prompt = buildBaseInstructions(
sourceDescription = "le contenu suivant"
) + "\n\nCONTENU :\n$extractedText"
return try {
val response = withTimeout(60_000L) {
model.generateContent(prompt)
}
val jsonText = response.text
if (jsonText.isNullOrBlank()) {
Result.failure(IllegalStateException("L'IA n'a renvoyé aucune donnée. Réessayez."))
} else {
parseRecipeJson(jsonText, sourceUrl = sourceUrl)?.let { Result.success(it) }
?: Result.failure(IllegalStateException("Aucune recette n'a été trouvée dans ce contenu."))
}
} catch (e: TimeoutCancellationException) {
Result.failure(IllegalStateException("L'import a dépassé le délai (60 s). Vérifiez votre connexion et réessayez."))
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.e(TAG, "Recipe text/url import failed", e)
Result.failure(IllegalStateException(e.localizedMessage ?: "Impossible d'importer cette recette."))
}
}
private fun buildBaseInstructions(sourceDescription: String): String {
val categoriesHelp = FoodCategory.entries.joinToString("\n") { "- ${it.code}: ${it.displayName}" }
return """
Extrais la recette de cuisine complète depuis $sourceDescription et traduis-la proprement en français si besoin.
RÈGLES STRICTES :
1. Si le contenu ne contient pas de recette de cuisine, renvoie isRecipe = false.
2. Convertis toujours chaque ingrédient dans l'une de ces 3 unités exactes :
- "g" pour les solides pesés (convertis les kg en g : 0,5 kg -> 500 g)
- "ml" pour les liquides (convertis L et cL en ml : 20 cL -> 200 ml, 1 L -> 1000 ml)
- "portion" pour les pièces, œufs, gousses, cuillères, pincées, tranches (ex: 2 œufs -> weight=2, unit="portion")
3. Choisis la catégorie la plus juste pour chaque ingrédient :
$categoriesHelp
4. Garde des noms d'ingrédients simples et utilisables pour une liste de courses (ex: "Blanc de poulet", "Crème fraîche", "Ail").
5. Rédige des étapes claires, numérotées implicitement dans le tableau `steps` (sans préfixe "1." dans le texte).
""".trimIndent()
}
private suspend fun fetchHtml(url: String): Result<String> = withContext(Dispatchers.IO) {
val request = Request.Builder()
.url(url)
.header(
"User-Agent",
"Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Mobile Safari/537.36"
)
.header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.header("Accept-Language", "fr-FR,fr;q=0.9,en;q=0.7")
.get()
.build()
try {
httpClient.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
return@withContext Result.failure(IllegalStateException("HTTP ${response.code}"))
}
val body = response.body?.string().orEmpty()
if (body.isBlank()) {
return@withContext Result.failure(IllegalStateException("Page vide"))
}
Result.success(body)
}
} catch (e: Exception) {
Log.w(TAG, "Failed to fetch recipe URL $url", e)
Result.failure(e)
}
}
companion object {
private const val TAG = "RecipeImporterAnalyzer"
private fun defaultHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(12, TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.build()
}
fun extractFirstUrl(text: String): String? {
val regex = Regex("""https?://[^\s<>"']+""", RegexOption.IGNORE_CASE)
return regex.find(text)?.value?.trimEnd('.', ',', ';', ')', ']', '!')
}
/**
* Extracts the first Schema.org JSON-LD block describing a Recipe (direct object or inside @graph).
*/
fun extractJsonLdRecipe(html: String): String? {
val scriptRegex = Regex(
"""<script[^>]*type=["']application/ld\+json["'][^>]*>(.*?)</script>""",
setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)
)
scriptRegex.findAll(html).forEach { match ->
val raw = match.groupValues[1].trim()
if (raw.isBlank()) return@forEach
findRecipeObjectInJsonLd(raw)?.let { return it.toString() }
}
return null
}
private fun findRecipeObjectInJsonLd(rawJson: String): JSONObject? {
val trimmed = rawJson.trim()
return try {
when {
trimmed.startsWith("[") -> {
val arr = JSONArray(trimmed)
for (i in 0 until arr.length()) {
val item = arr.optJSONObject(i) ?: continue
findRecipeInJsonObject(item)?.let { return it }
}
null
}
trimmed.startsWith("{") -> {
findRecipeInJsonObject(JSONObject(trimmed))
}
else -> null
}
} catch (_: Exception) {
null
}
}
private fun findRecipeInJsonObject(obj: JSONObject): JSONObject? {
if (hasRecipeType(obj)) return obj
val graph = obj.optJSONArray("@graph")
if (graph != null) {
for (i in 0 until graph.length()) {
val node = graph.optJSONObject(i) ?: continue
if (hasRecipeType(node)) return node
}
}
return null
}
private fun hasRecipeType(obj: JSONObject): Boolean {
val typeVal = obj.opt("@type") ?: return false
return when (typeVal) {
is String -> typeVal.equals("Recipe", ignoreCase = true) || typeVal.endsWith("/Recipe", ignoreCase = true)
is JSONArray -> (0 until typeVal.length()).any { idx ->
val s = typeVal.optString(idx, "")
s.equals("Recipe", ignoreCase = true) || s.endsWith("/Recipe", ignoreCase = true)
}
else -> false
}
}
fun extractImageUrlFromHtml(html: String, jsonLdRecipe: String? = null): String? {
// 1. Prefer JSON-LD Recipe image when available
if (!jsonLdRecipe.isNullOrBlank()) {
runCatching {
val obj = JSONObject(jsonLdRecipe)
extractImageUrlFromJsonField(obj.opt("image"))
}.getOrNull()?.let { return it }
}
// 2. Fallback to Open Graph / Twitter image meta tags
val ogPatterns = listOf(
Regex("""<meta[^>]*property=["']og:image["'][^>]*content=["']([^"']+)["']""", RegexOption.IGNORE_CASE),
Regex("""<meta[^>]*content=["']([^"']+)["'][^>]*property=["']og:image["']""", RegexOption.IGNORE_CASE),
Regex("""<meta[^>]*name=["']twitter:image["'][^>]*content=["']([^"']+)["']""", RegexOption.IGNORE_CASE)
)
ogPatterns.forEach { regex ->
val found = regex.find(html)?.groupValues?.getOrNull(1)?.trim()
if (!found.isNullOrBlank() && (found.startsWith("http://") || found.startsWith("https://"))) {
return found
}
}
return null
}
private fun extractImageUrlFromJsonField(imageField: Any?): String? {
return when (imageField) {
is String -> imageField.trim().takeIf { it.startsWith("http://") || it.startsWith("https://") }
is JSONObject -> imageField.optString("url", "").trim()
.takeIf { it.startsWith("http://") || it.startsWith("https://") }
is JSONArray -> {
for (i in 0 until imageField.length()) {
extractImageUrlFromJsonField(imageField.opt(i))?.let { return it }
}
null
}
else -> null
}
}
fun stripHtmlToText(html: String): String {
return html
.replace(Regex("""<script[^>]*>.*?</script>""", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)), " ")
.replace(Regex("""<style[^>]*>.*?</style>""", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)), " ")
.replace(Regex("""<[^>]+>"""), " ")
.replace("&nbsp;", " ")
.replace("&amp;", "&")
.replace("&quot;", "\"")
.replace("&#39;", "'")
.replace(Regex("""\s+"""), " ")
.trim()
}
fun parseRecipeJson(
jsonString: String,
sourceUrl: String? = null
): RecipeEntry? {
val root = runCatching { JSONObject(jsonString) }.getOrNull() ?: return null
if (!root.optBoolean("isRecipe", true)) return null
val title = root.optString("title", "").trim()
if (title.isBlank()) return null
val categoryTag = RecipeCategoryTag.fromString(root.optString("categoryTag", "MAIN")).name
val prepTime = root.optInt("prepTimeMinutes", 20).coerceIn(0, 600)
val servings = root.optInt("servings", 2).coerceIn(1, 30)
val ingredientsArr = root.optJSONArray("ingredients")
val ingredients = mutableListOf<MealFoodItem>()
if (ingredientsArr != null) {
for (i in 0 until ingredientsArr.length()) {
val obj = ingredientsArr.optJSONObject(i) ?: continue
val name = obj.optString("name", "").trim()
if (name.isBlank()) continue
val rawWeight = if (obj.has("weight") && !obj.isNull("weight")) {
obj.optDouble("weight", Double.NaN).takeIf { !it.isNaN() && it > 0.0 }
} else {
null
}
val unit = FoodUnit.fromCode(obj.optString("unit", "portion"))
val category = FoodCategory.fromCode(obj.optString("category"))
?: FoodCategory.inferFromName(name)
ingredients.add(
MealFoodItem(
name = name,
weight = rawWeight,
unit = unit,
categories = listOf(category)
)
)
}
}
val stepsArr = root.optJSONArray("steps")
val steps = mutableListOf<String>()
if (stepsArr != null) {
for (i in 0 until stepsArr.length()) {
val step = stepsArr.optString(i, "").trim()
if (step.isNotBlank()) steps.add(step)
}
}
val rawNotes = root.optString("notes", "").trim()
val combinedNotes = buildList {
if (rawNotes.isNotBlank()) add(rawNotes)
if (!sourceUrl.isNullOrBlank() && !rawNotes.contains(sourceUrl, ignoreCase = true)) {
add("Source : $sourceUrl")
}
}.joinToString("\n")
return RecipeEntry(
id = "",
title = title,
categoryTag = categoryTag,
prepTimeMinutes = prepTime,
servings = servings,
ingredientsSerialized = ingredients.map { it.serialize() },
steps = steps,
notes = combinedNotes,
photoUri = null
)
}
}
}
@@ -26,6 +26,8 @@ import com.example.domain.CulinaryIdeasGenerator
import com.example.domain.DailyBenchmarkAnalyzer
import com.example.domain.DailyBenchmarkGap
import com.example.domain.GoogleSheetsSyncUseCase
import com.example.domain.RecipeImportUiState
import com.example.domain.RecipeImporterAnalyzer
import com.example.domain.SheetsRestoreResult
import com.example.domain.SheetsSyncResult
import com.example.domain.WeeklyStatsCalculator
@@ -33,6 +35,7 @@ import com.example.notification.MealNotificationManager
import com.example.ui.common.UiEvent
import com.example.ui.theme.AppThemeMode
import com.example.util.GoogleSheetsAuthHelper
import com.example.util.ImageUtils
import com.example.widget.SatieaAppWidgetProvider
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
@@ -107,6 +110,8 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs)
private val csvExportUseCase = CsvExportUseCase(context)
private val culinaryIdeasGenerator by lazy { CulinaryIdeasGenerator() }
private val recipeImporter by lazy { RecipeImporterAnalyzer() }
private var recipeImportJob: kotlinx.coroutines.Job? = null
// UDF Event Channel
private val _uiEventChannel = Channel<UiEvent>(Channel.BUFFERED)
@@ -193,6 +198,9 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
private val _suggestionUiState = MutableStateFlow<SuggestionUiState>(SuggestionUiState.Idle)
val suggestionUiState: StateFlow<SuggestionUiState> = _suggestionUiState.asStateFlow()
private val _recipeImportState = MutableStateFlow<RecipeImportUiState>(RecipeImportUiState.Idle)
val recipeImportState: StateFlow<RecipeImportUiState> = _recipeImportState.asStateFlow()
private val _savedSuggestionIds = MutableStateFlow<Set<String>>(emptySet())
val savedSuggestionIds: StateFlow<Set<String>> = _savedSuggestionIds.asStateFlow()
@@ -416,6 +424,74 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
fun importRecipeFromUrlOrText(rawInput: String) {
recipeImportJob?.cancel()
recipeImportJob = viewModelScope.launch {
val hasUrl = RecipeImporterAnalyzer.extractFirstUrl(rawInput) != null
_recipeImportState.value = RecipeImportUiState.Loading(
if (hasUrl) "Lecture de la page web..." else "Analyse de la recette..."
)
val appContext = getApplication<Application>()
val result = recipeImporter.importFromUrlOrText(
rawInput = rawInput,
downloadPhoto = { imageUrl ->
ImageUtils.downloadAndSaveImageToPrivateStorage(appContext, imageUrl)
}
)
result.fold(
onSuccess = { recipe ->
_recipeImportState.value = RecipeImportUiState.Ready(recipe)
},
onFailure = { error ->
_recipeImportState.value = RecipeImportUiState.Error(
error.message ?: "Impossible d'importer cette recette."
)
}
)
}
}
fun importRecipeFromImageUri(uri: Uri) {
recipeImportJob?.cancel()
recipeImportJob = viewModelScope.launch {
_recipeImportState.value = RecipeImportUiState.Loading("Lecture de la photo...")
val bitmap = ImageUtils.loadResizedBitmapForAi(getApplication(), uri, maxDimension = 1440)
if (bitmap == null) {
_recipeImportState.value = RecipeImportUiState.Error(
"Impossible de lire cette image. Réessayez avec une photo plus nette."
)
return@launch
}
try {
val result = recipeImporter.importFromBitmap(bitmap)
result.fold(
onSuccess = { recipe ->
_recipeImportState.value = RecipeImportUiState.Ready(recipe)
},
onFailure = { error ->
_recipeImportState.value = RecipeImportUiState.Error(
error.message ?: "Impossible d'extraire une recette de cette image."
)
}
)
} finally {
if (!bitmap.isRecycled) {
bitmap.recycle()
}
}
}
}
fun consumeImportedRecipe() {
_recipeImportState.value = RecipeImportUiState.Idle
}
fun dismissRecipeImport() {
recipeImportJob?.cancel()
recipeImportJob = null
_recipeImportState.value = RecipeImportUiState.Idle
}
// ------------------------------------------------------------------------
// Food Preferences & AI Culinary Ideas
// ------------------------------------------------------------------------
@@ -0,0 +1,442 @@
package com.example.ui.recipes
import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.net.Uri
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.ContentPaste
import androidx.compose.material.icons.filled.Description
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.Link
import androidx.compose.material.icons.filled.PhotoLibrary
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import com.example.domain.RecipeImportUiState
import com.example.util.ImageUtils
import kotlinx.coroutines.launch
private enum class RecipeImportSourceTab(val label: String) {
LINK("Lien"),
PHOTO("Photo"),
TEXT("Texte")
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImportRecipeSheet(
importState: RecipeImportUiState,
onImportFromUrlOrText: (String) -> Unit,
onImportFromImageUri: (Uri) -> Unit,
onResetError: () -> Unit,
onShowMessage: (String) -> Unit,
onDismiss: () -> Unit
) {
val context = LocalContext.current
val clipboard = LocalClipboardManager.current
val coroutineScope = rememberCoroutineScope()
val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
var selectedTab by rememberSaveable { mutableStateOf(RecipeImportSourceTab.LINK) }
var urlInput by rememberSaveable { mutableStateOf("") }
var textInput by rememberSaveable { mutableStateOf("") }
var pendingCaptureUriString by rememberSaveable { mutableStateOf<String?>(null) }
val pickGalleryLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.PickVisualMedia()
) { uri ->
if (uri != null) {
onImportFromImageUri(uri)
}
}
val takePhotoLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
val expectedUri = pendingCaptureUriString?.let(Uri::parse)
pendingCaptureUriString = null
if (result.resultCode == Activity.RESULT_OK) {
val data = result.data
coroutineScope.launch {
val resolved = ImageUtils.resolveCapturedReceiptUri(
context = context,
expectedUri = expectedUri,
resultData = data
)
if (resolved != null) {
onImportFromImageUri(resolved)
} else {
onShowMessage("Impossible de récupérer la photo. Essayez depuis la galerie.")
}
}
}
}
val launchCamera = {
try {
val uri = ImageUtils.createReceiptCaptureUri(context)
pendingCaptureUriString = uri.toString()
val intent = ImageUtils.buildCameraCaptureIntent(context, uri)
takePhotoLauncher.launch(intent)
} catch (e: Exception) {
pendingCaptureUriString = null
Log.e("ImportRecipeSheet", "Failed to launch camera", e)
onShowMessage("Impossible d'ouvrir l'appareil photo")
}
}
val cameraPermissionLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
launchCamera()
} else {
onShowMessage("Autorisation caméra refusée — choisissez une image depuis la galerie")
}
}
val triggerCamera = {
val hasPerm = ContextCompat.checkSelfPermission(
context,
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED
if (hasPerm) {
launchCamera()
} else {
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
ModalBottomSheet(
onDismissRequest = {
if (importState !is RecipeImportUiState.Loading) {
onDismiss()
}
},
sheetState = sheetState,
shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.navigationBarsPadding()
.imePadding()
.verticalScroll(rememberScrollState())
.padding(horizontal = 20.dp, vertical = 8.dp)
.testTag("import_recipe_sheet"),
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
when (importState) {
is RecipeImportUiState.Loading -> {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 32.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(14.dp)
) {
CircularProgressIndicator()
Text(
text = importState.statusMessage,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center
)
Text(
text = "Extraction du titre, des ingrédients, des quantités et des étapes...",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
}
}
is RecipeImportUiState.Error -> {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 16.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Icon(
imageVector = Icons.Default.ErrorOutline,
contentDescription = null,
tint = MaterialTheme.colorScheme.error,
modifier = Modifier.size(40.dp)
)
Text(
text = "Import impossible",
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold
)
Text(
text = importState.message,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
textAlign = TextAlign.Center
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
OutlinedButton(
onClick = onDismiss,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.weight(1f)
) {
Text("Fermer")
}
Button(
onClick = onResetError,
shape = RoundedCornerShape(12.dp),
modifier = Modifier.weight(1f)
) {
Text("Réessayer")
}
}
}
}
RecipeImportUiState.Idle, is RecipeImportUiState.Ready -> {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
Column {
Text(
text = "Importer une recette",
style = MaterialTheme.typography.titleLarge,
fontWeight = FontWeight.Bold
)
Text(
text = "Depuis un site web, une photo ou un texte copié",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
RecipeImportSourceTab.entries.forEachIndexed { index, tab ->
SegmentedButton(
selected = selectedTab == tab,
onClick = { selectedTab = tab },
shape = SegmentedButtonDefaults.itemShape(
index = index,
count = RecipeImportSourceTab.entries.size
),
icon = {
Icon(
imageVector = when (tab) {
RecipeImportSourceTab.LINK -> Icons.Default.Link
RecipeImportSourceTab.PHOTO -> Icons.Default.CameraAlt
RecipeImportSourceTab.TEXT -> Icons.Default.Description
},
contentDescription = null,
modifier = Modifier.size(16.dp)
)
}
) {
Text(tab.label, maxLines = 1)
}
}
}
when (selectedTab) {
RecipeImportSourceTab.LINK -> {
OutlinedTextField(
value = urlInput,
onValueChange = { urlInput = it },
label = { Text("Lien de la recette") },
placeholder = { Text("https://www.marmiton.org/...") },
singleLine = true,
trailingIcon = {
IconButton(
onClick = {
clipboard.getText()?.text?.trim()?.takeIf { it.isNotBlank() }?.let {
urlInput = it
}
}
) {
Icon(
imageVector = Icons.Default.ContentPaste,
contentDescription = "Coller le lien"
)
}
},
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("import_recipe_url_input")
)
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = "Astuce : vous pouvez aussi utiliser « Partager → Satiea » directement depuis Chrome ou votre navigateur.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(12.dp)
)
}
Button(
onClick = { onImportFromUrlOrText(urlInput) },
enabled = urlInput.isNotBlank(),
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.height(48.dp)
.testTag("import_recipe_url_submit")
) {
Icon(Icons.Default.AutoAwesome, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(8.dp))
Text("Importer depuis ce lien")
}
}
RecipeImportSourceTab.PHOTO -> {
Text(
text = "Photographiez une page de livre de cuisine ou choisissez une capture d'écran (Instagram, blog, note).",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Button(
onClick = triggerCamera,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.height(48.dp)
.testTag("import_recipe_camera_button")
) {
Icon(Icons.Default.CameraAlt, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(8.dp))
Text("Prendre une photo")
}
OutlinedButton(
onClick = {
pickGalleryLauncher.launch(
PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
)
},
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.height(48.dp)
.testTag("import_recipe_gallery_button")
) {
Icon(Icons.Default.PhotoLibrary, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(8.dp))
Text("Choisir depuis la galerie")
}
}
RecipeImportSourceTab.TEXT -> {
OutlinedTextField(
value = textInput,
onValueChange = { textInput = it },
label = { Text("Texte de la recette") },
placeholder = { Text("Collez ici les ingrédients et les étapes (ex. depuis WhatsApp, SMS ou une note)...") },
minLines = 5,
maxLines = 10,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("import_recipe_text_input")
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedButton(
onClick = {
clipboard.getText()?.text?.trim()?.takeIf { it.isNotBlank() }?.let {
textInput = it
}
},
shape = RoundedCornerShape(14.dp)
) {
Icon(Icons.Default.ContentPaste, contentDescription = null, modifier = Modifier.size(16.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("Coller")
}
Button(
onClick = { onImportFromUrlOrText(textInput) },
enabled = textInput.trim().length >= 15,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.weight(1f)
.testTag("import_recipe_text_submit")
) {
Icon(Icons.Default.AutoAwesome, contentDescription = null, modifier = Modifier.size(18.dp))
Spacer(modifier = Modifier.width(6.dp))
Text("Extraire la recette")
}
}
}
}
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
}
@@ -27,11 +27,13 @@ import androidx.compose.material.icons.automirrored.filled.MenuBook
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Download
import androidx.compose.material.icons.filled.People
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.FloatingActionButton
@@ -90,6 +92,7 @@ fun RecipesScreen(
suggestionUiState: SuggestionUiState,
savedSuggestionIds: Set<String>,
onAddRecipeClick: () -> Unit,
onImportRecipeClick: () -> Unit = {},
onRecipeClick: (RecipeEntry) -> Unit,
onSavePreference: (name: String, status: FoodPreferenceStatus, category: FoodCategory?) -> Unit,
onRemovePreference: (slugId: String) -> Unit,
@@ -252,6 +255,30 @@ fun RecipesScreen(
onLikeRecipeIngredients = onLikeSuggestedRecipeIngredients
)
} else {
// Quick Import Recipe banner (URL / Photo / Text)
item {
FilledTonalButton(
onClick = onImportRecipeClick,
shape = RoundedCornerShape(14.dp),
modifier = Modifier
.fillMaxWidth()
.testTag("import_recipe_button")
) {
Icon(
imageVector = Icons.Default.Download,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Importer une recette (Lien, Photo ou Texte)",
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}
// Search bar & Category filter chips
if (recipes.isNotEmpty()) {
item {
@@ -16,10 +16,13 @@ import androidx.core.content.FileProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.util.UUID
import java.util.concurrent.TimeUnit
object ImageUtils {
@@ -104,6 +107,89 @@ object ImageUtils {
}
}
/**
* Downloads an image from an HTTP(S) URL (e.g. recipe og:image) and saves a resized
* JPEG copy into private app storage. Returns null silently if the remote host blocks or fails.
*/
suspend fun downloadAndSaveImageToPrivateStorage(
context: Context,
imageUrl: String
): String? = withContext(Dispatchers.IO) {
if (!imageUrl.startsWith("http://") && !imageUrl.startsWith("https://")) {
return@withContext null
}
try {
val client = OkHttpClient.Builder()
.connectTimeout(8, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.followRedirects(true)
.build()
val request = Request.Builder()
.url(imageUrl)
.header(
"User-Agent",
"Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Mobile Safari/537.36"
)
.get()
.build()
val bytes = client.newCall(request).execute().use { response ->
if (!response.isSuccessful) return@withContext null
val bodyBytes = response.body?.bytes() ?: return@withContext null
if (bodyBytes.isEmpty() || bodyBytes.size > 12 * 1024 * 1024) return@withContext null
bodyBytes
}
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
if (bounds.outWidth <= 0 || bounds.outHeight <= 0) return@withContext null
var inSampleSize = 1
if (bounds.outHeight > MAX_DIMENSION || bounds.outWidth > MAX_DIMENSION) {
val halfH = bounds.outHeight / 2
val halfW = bounds.outWidth / 2
while (halfH / inSampleSize >= MAX_DIMENSION && halfW / inSampleSize >= MAX_DIMENSION) {
inSampleSize *= 2
}
}
val decoded = BitmapFactory.decodeByteArray(
bytes,
0,
bytes.size,
BitmapFactory.Options().apply { this.inSampleSize = inSampleSize }
) ?: return@withContext null
val scaled = if (decoded.width > MAX_DIMENSION || decoded.height > MAX_DIMENSION) {
val ratio = minOf(
MAX_DIMENSION.toFloat() / decoded.width,
MAX_DIMENSION.toFloat() / decoded.height
)
val targetW = (decoded.width * ratio).toInt().coerceAtLeast(1)
val targetH = (decoded.height * ratio).toInt().coerceAtLeast(1)
Bitmap.createScaledBitmap(decoded, targetW, targetH, true).also {
if (it != decoded) decoded.recycle()
}
} else {
decoded
}
val targetDir = getPhotosDirectory(context)
val uniqueFileName = "recipe_${System.currentTimeMillis()}_${UUID.randomUUID().toString().take(6)}.jpg"
val targetFile = File(targetDir, uniqueFileName)
FileOutputStream(targetFile).use { out ->
scaled.compress(Bitmap.CompressFormat.JPEG, JPEG_QUALITY, out)
out.flush()
}
scaled.recycle()
Uri.fromFile(targetFile).toString()
} catch (e: Exception) {
Log.w(TAG, "Could not download recipe image from $imageUrl: ${e.message}")
null
}
}
fun deletePhotoFile(context: Context, photoUriStr: String?): Boolean {
if (photoUriStr.isNullOrBlank()) return false
return try {
@@ -0,0 +1,109 @@
package com.example
import com.example.data.model.FoodCategory
import com.example.data.model.FoodUnit
import com.example.data.model.RecipeCategoryTag
import com.example.domain.RecipeImporterAnalyzer
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class RecipeImporterAnalyzerTest {
@Test
fun extractFirstUrl_handlesChromeSharedTitleAndLink() {
val shared = "Gratin de courgettes facile - Marmiton https://www.marmiton.org/recettes/recette_gratin.aspx!"
assertEquals(
"https://www.marmiton.org/recettes/recette_gratin.aspx",
RecipeImporterAnalyzer.extractFirstUrl(shared)
)
}
@Test
fun extractJsonLdRecipe_findsRecipeInsideGraphAndExtractsImage() {
val html = """
<html>
<head>
<meta property="og:image" content="https://cdn.example.com/og.jpg" />
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@graph": [
{ "@type": "WebPage", "name": "Blog" },
{
"@type": "Recipe",
"name": "Poulet curry coco",
"image": ["https://cdn.example.com/curry.jpg"]
}
]
}
</script>
</head>
<body>Contenu</body>
</html>
""".trimIndent()
val jsonLd = RecipeImporterAnalyzer.extractJsonLdRecipe(html)
assertNotNull(jsonLd)
assertTrue(jsonLd!!.contains("Poulet curry coco"))
val imageUrl = RecipeImporterAnalyzer.extractImageUrlFromHtml(html, jsonLd)
assertEquals("https://cdn.example.com/curry.jpg", imageUrl)
}
@Test
fun parseRecipeJson_parsesIngredientsStepsAndAppendsSourceUrl() {
val json = """
{
"isRecipe": true,
"title": "Gratin de courgettes",
"categoryTag": "MAIN",
"prepTimeMinutes": 35,
"servings": 4,
"ingredients": [
{ "name": "Courgette", "weight": 800, "unit": "g", "category": "VEGETABLE" },
{ "name": "Crème fraîche", "weight": 200, "unit": "ml", "category": "FAT_SEASONING" },
{ "name": "Œufs", "weight": 2, "unit": "portion", "category": "PROTEIN" }
],
"steps": [
"Couper les courgettes en rondelles.",
"Mélanger les œufs et la crème, puis enfourner 25 min à 180°C."
],
"notes": "Délicieux avec du comté râpé."
}
""".trimIndent()
val recipe = RecipeImporterAnalyzer.parseRecipeJson(
jsonString = json,
sourceUrl = "https://www.marmiton.org/recettes/gratin"
)
assertNotNull(recipe)
recipe!!
assertEquals("Gratin de courgettes", recipe.title)
assertEquals(RecipeCategoryTag.MAIN, recipe.categoryEnum())
assertEquals(35, recipe.prepTimeMinutes)
assertEquals(4, recipe.servings)
assertEquals(2, recipe.steps.size)
assertTrue(recipe.notes.contains("Source : https://www.marmiton.org/recettes/gratin"))
val parsed = recipe.parsedIngredients()
assertEquals(3, parsed.size)
assertEquals("Courgette", parsed[0].name)
assertEquals(800.0, parsed[0].weight ?: 0.0, 0.01)
assertEquals(FoodUnit.G, parsed[0].unit)
assertEquals(FoodCategory.VEGETABLE, parsed[0].category)
assertEquals(FoodUnit.ML, parsed[1].unit)
assertEquals(FoodUnit.PORTION, parsed[2].unit)
}
@Test
fun parseRecipeJson_returnsNullWhenNotARecipe() {
val json = """{"isRecipe": false, "title": "", "ingredients": [], "steps": []}"""
assertNull(RecipeImporterAnalyzer.parseRecipeJson(json))
}
}