From 0150a7ce02762c589f5d15c64492e3258aeb7c1c Mon Sep 17 00:00:00 2001 From: vjrj Date: Fri, 10 Jul 2026 20:58:45 +0200 Subject: [PATCH 1/4] feat(market): show offer photos in the market list and detail Render offer.imageUrl (already carried by NIP-99) as a thumbnail on each market card and a hero image on the offer detail page. Remote images degrade gracefully: a spinner while loading, a neutral placeholder when the media server is unreachable. Publishing the photo comes next. --- apps/app_seeds/lib/i18n/ast.i18n.json | 137 ++++++++++++++---- apps/app_seeds/lib/i18n/en.i18n.json | 137 ++++++++++++++---- apps/app_seeds/lib/i18n/es.i18n.json | 137 ++++++++++++++---- apps/app_seeds/lib/i18n/pt.i18n.json | 137 ++++++++++++++---- apps/app_seeds/lib/i18n/strings.g.dart | 4 +- apps/app_seeds/lib/i18n/strings_ast.g.dart | 2 + apps/app_seeds/lib/i18n/strings_en.g.dart | 4 + apps/app_seeds/lib/i18n/strings_es.g.dart | 2 + apps/app_seeds/lib/i18n/strings_pt.g.dart | 2 + .../lib/ui/market_offer_detail_screen.dart | 4 + apps/app_seeds/lib/ui/market_screen.dart | 7 + apps/app_seeds/lib/ui/market_widgets.dart | 92 ++++++++++++ .../ui/market_offer_detail_screen_test.dart | 34 ++++- .../test/ui/market_widgets_test.dart | 45 ++++++ 14 files changed, 633 insertions(+), 111 deletions(-) create mode 100644 apps/app_seeds/test/ui/market_widgets_test.dart diff --git a/apps/app_seeds/lib/i18n/ast.i18n.json b/apps/app_seeds/lib/i18n/ast.i18n.json index 07cff98..31dd7a0 100644 --- a/apps/app_seeds/lib/i18n/ast.i18n.json +++ b/apps/app_seeds/lib/i18n/ast.i18n.json @@ -214,8 +214,18 @@ "anyMonth": "Cualquier mes", "noDate": "Indicar data de coyecha", "monthNames": [ - "xineru", "febreru", "marzu", "abril", "mayu", "xunu", - "xunetu", "agostu", "setiembre", "ochobre", "payares", "avientu" + "xineru", + "febreru", + "marzu", + "abril", + "mayu", + "xunu", + "xunetu", + "agostu", + "setiembre", + "ochobre", + "payares", + "avientu" ] }, "lotType": { @@ -330,30 +340,102 @@ "some": "dalgunes", "plenty": "munches", "pinch": "una migaya", - "handful": { "singular": "puñáu", "plural": "puñaos" }, - "teaspoon": { "singular": "cuyaradina", "plural": "cuyaradines" }, - "spoon": { "singular": "cuyar", "plural": "cuyares" }, - "cup": { "singular": "taza", "plural": "tazes" }, - "jar": { "singular": "bote", "plural": "botes" }, - "sack": { "singular": "sacu", "plural": "sacos" }, - "packet": { "singular": "sobre", "plural": "sobres" }, - "cob": { "singular": "panoya", "plural": "panoyes" }, - "pod": { "singular": "vaina", "plural": "vaines" }, - "ear": { "singular": "espiga", "plural": "espigues" }, - "head": { "singular": "cabezuela", "plural": "cabezueles" }, - "fruit": { "singular": "frutu", "plural": "frutos" }, - "bulb": { "singular": "bulbu", "plural": "bulbos" }, - "tuber": { "singular": "tubérculu", "plural": "tubérculos" }, - "seedHead": { "singular": "cabeza de simiente", "plural": "cabeces de simiente" }, - "bunch": { "singular": "manoyu", "plural": "manoyos" }, - "plant": { "singular": "planta", "plural": "plantes" }, - "pot": { "singular": "tiestu", "plural": "tiestos" }, - "tray": { "singular": "bandexa", "plural": "bandexes" }, - "seedling": { "singular": "plántula", "plural": "plántules" }, - "tree": { "singular": "árbol", "plural": "árboles" }, - "cutting": { "singular": "esqueje", "plural": "esquejes" }, - "grams": { "singular": "gramu", "plural": "gramos" }, - "count": { "singular": "grana", "plural": "granes" } + "handful": { + "singular": "puñáu", + "plural": "puñaos" + }, + "teaspoon": { + "singular": "cuyaradina", + "plural": "cuyaradines" + }, + "spoon": { + "singular": "cuyar", + "plural": "cuyares" + }, + "cup": { + "singular": "taza", + "plural": "tazes" + }, + "jar": { + "singular": "bote", + "plural": "botes" + }, + "sack": { + "singular": "sacu", + "plural": "sacos" + }, + "packet": { + "singular": "sobre", + "plural": "sobres" + }, + "cob": { + "singular": "panoya", + "plural": "panoyes" + }, + "pod": { + "singular": "vaina", + "plural": "vaines" + }, + "ear": { + "singular": "espiga", + "plural": "espigues" + }, + "head": { + "singular": "cabezuela", + "plural": "cabezueles" + }, + "fruit": { + "singular": "frutu", + "plural": "frutos" + }, + "bulb": { + "singular": "bulbu", + "plural": "bulbos" + }, + "tuber": { + "singular": "tubérculu", + "plural": "tubérculos" + }, + "seedHead": { + "singular": "cabeza de simiente", + "plural": "cabeces de simiente" + }, + "bunch": { + "singular": "manoyu", + "plural": "manoyos" + }, + "plant": { + "singular": "planta", + "plural": "plantes" + }, + "pot": { + "singular": "tiestu", + "plural": "tiestos" + }, + "tray": { + "singular": "bandexa", + "plural": "bandexes" + }, + "seedling": { + "singular": "plántula", + "plural": "plántules" + }, + "tree": { + "singular": "árbol", + "plural": "árboles" + }, + "cutting": { + "singular": "esqueje", + "plural": "esquejes" + }, + "grams": { + "singular": "gramu", + "plural": "gramos" + }, + "count": { + "singular": "grana", + "plural": "granes" + } }, "market": { "title": "Simiente cerca de ti", @@ -400,7 +482,8 @@ "sharedBy": "Compartíu por", "noProfile": "Esta persona entá nun compartió'l so perfil", "copyId": "Copiar códigu", - "idCopied": "Códigu copiáu" + "idCopied": "Códigu copiáu", + "photo": "Semeya" }, "profile": { "title": "El to perfil", diff --git a/apps/app_seeds/lib/i18n/en.i18n.json b/apps/app_seeds/lib/i18n/en.i18n.json index ee69b30..a746708 100644 --- a/apps/app_seeds/lib/i18n/en.i18n.json +++ b/apps/app_seeds/lib/i18n/en.i18n.json @@ -215,8 +215,18 @@ "anyMonth": "Any month", "noDate": "Set harvest date", "monthNames": [ - "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December" + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" ] }, "lotType": { @@ -331,30 +341,102 @@ "some": "some", "plenty": "plenty", "pinch": "a pinch", - "handful": { "singular": "handful", "plural": "handfuls" }, - "teaspoon": { "singular": "teaspoon", "plural": "teaspoons" }, - "spoon": { "singular": "spoon", "plural": "spoons" }, - "cup": { "singular": "cup", "plural": "cups" }, - "jar": { "singular": "jar", "plural": "jars" }, - "sack": { "singular": "sack", "plural": "sacks" }, - "packet": { "singular": "packet", "plural": "packets" }, - "cob": { "singular": "cob", "plural": "cobs" }, - "pod": { "singular": "pod", "plural": "pods" }, - "ear": { "singular": "ear", "plural": "ears" }, - "head": { "singular": "head", "plural": "heads" }, - "fruit": { "singular": "fruit", "plural": "fruits" }, - "bulb": { "singular": "bulb", "plural": "bulbs" }, - "tuber": { "singular": "tuber", "plural": "tubers" }, - "seedHead": { "singular": "seed head", "plural": "seed heads" }, - "bunch": { "singular": "bunch", "plural": "bunches" }, - "plant": { "singular": "plant", "plural": "plants" }, - "pot": { "singular": "pot", "plural": "pots" }, - "tray": { "singular": "tray", "plural": "trays" }, - "seedling": { "singular": "seedling", "plural": "seedlings" }, - "tree": { "singular": "tree", "plural": "trees" }, - "cutting": { "singular": "cutting", "plural": "cuttings" }, - "grams": { "singular": "gram", "plural": "grams" }, - "count": { "singular": "seed", "plural": "seeds" } + "handful": { + "singular": "handful", + "plural": "handfuls" + }, + "teaspoon": { + "singular": "teaspoon", + "plural": "teaspoons" + }, + "spoon": { + "singular": "spoon", + "plural": "spoons" + }, + "cup": { + "singular": "cup", + "plural": "cups" + }, + "jar": { + "singular": "jar", + "plural": "jars" + }, + "sack": { + "singular": "sack", + "plural": "sacks" + }, + "packet": { + "singular": "packet", + "plural": "packets" + }, + "cob": { + "singular": "cob", + "plural": "cobs" + }, + "pod": { + "singular": "pod", + "plural": "pods" + }, + "ear": { + "singular": "ear", + "plural": "ears" + }, + "head": { + "singular": "head", + "plural": "heads" + }, + "fruit": { + "singular": "fruit", + "plural": "fruits" + }, + "bulb": { + "singular": "bulb", + "plural": "bulbs" + }, + "tuber": { + "singular": "tuber", + "plural": "tubers" + }, + "seedHead": { + "singular": "seed head", + "plural": "seed heads" + }, + "bunch": { + "singular": "bunch", + "plural": "bunches" + }, + "plant": { + "singular": "plant", + "plural": "plants" + }, + "pot": { + "singular": "pot", + "plural": "pots" + }, + "tray": { + "singular": "tray", + "plural": "trays" + }, + "seedling": { + "singular": "seedling", + "plural": "seedlings" + }, + "tree": { + "singular": "tree", + "plural": "trees" + }, + "cutting": { + "singular": "cutting", + "plural": "cuttings" + }, + "grams": { + "singular": "gram", + "plural": "grams" + }, + "count": { + "singular": "seed", + "plural": "seeds" + } }, "market": { "title": "Seeds near you", @@ -403,7 +485,8 @@ "sharedBy": "Shared by", "noProfile": "This person hasn't shared a profile yet", "copyId": "Copy code", - "idCopied": "Code copied" + "idCopied": "Code copied", + "photo": "Photo" }, "profile": { "title": "Your profile", diff --git a/apps/app_seeds/lib/i18n/es.i18n.json b/apps/app_seeds/lib/i18n/es.i18n.json index 7c0e44a..0f1e1a6 100644 --- a/apps/app_seeds/lib/i18n/es.i18n.json +++ b/apps/app_seeds/lib/i18n/es.i18n.json @@ -214,8 +214,18 @@ "anyMonth": "Cualquier mes", "noDate": "Indicar fecha de cosecha", "monthNames": [ - "enero", "febrero", "marzo", "abril", "mayo", "junio", - "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre" + "enero", + "febrero", + "marzo", + "abril", + "mayo", + "junio", + "julio", + "agosto", + "septiembre", + "octubre", + "noviembre", + "diciembre" ] }, "lotType": { @@ -330,30 +340,102 @@ "some": "algunas", "plenty": "muchas", "pinch": "una pizca", - "handful": { "singular": "puñado", "plural": "puñados" }, - "teaspoon": { "singular": "cucharadita", "plural": "cucharaditas" }, - "spoon": { "singular": "cuchara", "plural": "cucharas" }, - "cup": { "singular": "taza", "plural": "tazas" }, - "jar": { "singular": "bote", "plural": "botes" }, - "sack": { "singular": "saco", "plural": "sacos" }, - "packet": { "singular": "sobre", "plural": "sobres" }, - "cob": { "singular": "mazorca", "plural": "mazorcas" }, - "pod": { "singular": "vaina", "plural": "vainas" }, - "ear": { "singular": "espiga", "plural": "espigas" }, - "head": { "singular": "cabezuela", "plural": "cabezuelas" }, - "fruit": { "singular": "fruto", "plural": "frutos" }, - "bulb": { "singular": "bulbo", "plural": "bulbos" }, - "tuber": { "singular": "tubérculo", "plural": "tubérculos" }, - "seedHead": { "singular": "cabeza de semillas", "plural": "cabezas de semillas" }, - "bunch": { "singular": "manojo", "plural": "manojos" }, - "plant": { "singular": "planta", "plural": "plantas" }, - "pot": { "singular": "maceta", "plural": "macetas" }, - "tray": { "singular": "bandeja", "plural": "bandejas" }, - "seedling": { "singular": "plántula", "plural": "plántulas" }, - "tree": { "singular": "árbol", "plural": "árboles" }, - "cutting": { "singular": "esqueje", "plural": "esquejes" }, - "grams": { "singular": "gramo", "plural": "gramos" }, - "count": { "singular": "semilla", "plural": "semillas" } + "handful": { + "singular": "puñado", + "plural": "puñados" + }, + "teaspoon": { + "singular": "cucharadita", + "plural": "cucharaditas" + }, + "spoon": { + "singular": "cuchara", + "plural": "cucharas" + }, + "cup": { + "singular": "taza", + "plural": "tazas" + }, + "jar": { + "singular": "bote", + "plural": "botes" + }, + "sack": { + "singular": "saco", + "plural": "sacos" + }, + "packet": { + "singular": "sobre", + "plural": "sobres" + }, + "cob": { + "singular": "mazorca", + "plural": "mazorcas" + }, + "pod": { + "singular": "vaina", + "plural": "vainas" + }, + "ear": { + "singular": "espiga", + "plural": "espigas" + }, + "head": { + "singular": "cabezuela", + "plural": "cabezuelas" + }, + "fruit": { + "singular": "fruto", + "plural": "frutos" + }, + "bulb": { + "singular": "bulbo", + "plural": "bulbos" + }, + "tuber": { + "singular": "tubérculo", + "plural": "tubérculos" + }, + "seedHead": { + "singular": "cabeza de semillas", + "plural": "cabezas de semillas" + }, + "bunch": { + "singular": "manojo", + "plural": "manojos" + }, + "plant": { + "singular": "planta", + "plural": "plantas" + }, + "pot": { + "singular": "maceta", + "plural": "macetas" + }, + "tray": { + "singular": "bandeja", + "plural": "bandejas" + }, + "seedling": { + "singular": "plántula", + "plural": "plántulas" + }, + "tree": { + "singular": "árbol", + "plural": "árboles" + }, + "cutting": { + "singular": "esqueje", + "plural": "esquejes" + }, + "grams": { + "singular": "gramo", + "plural": "gramos" + }, + "count": { + "singular": "semilla", + "plural": "semillas" + } }, "market": { "title": "Semillas cerca de ti", @@ -402,7 +484,8 @@ "sharedBy": "Compartido por", "noProfile": "Esta persona aún no ha compartido su perfil", "copyId": "Copiar código", - "idCopied": "Código copiado" + "idCopied": "Código copiado", + "photo": "Foto" }, "profile": { "title": "Tu perfil", diff --git a/apps/app_seeds/lib/i18n/pt.i18n.json b/apps/app_seeds/lib/i18n/pt.i18n.json index 8df35d2..72a30db 100644 --- a/apps/app_seeds/lib/i18n/pt.i18n.json +++ b/apps/app_seeds/lib/i18n/pt.i18n.json @@ -211,8 +211,18 @@ "anyMonth": "Qualquer mês", "noDate": "Definir data de colheita", "monthNames": [ - "janeiro", "fevereiro", "março", "abril", "maio", "junho", - "julho", "agosto", "setembro", "outubro", "novembro", "dezembro" + "janeiro", + "fevereiro", + "março", + "abril", + "maio", + "junho", + "julho", + "agosto", + "setembro", + "outubro", + "novembro", + "dezembro" ] }, "lotType": { @@ -327,30 +337,102 @@ "some": "bastantes", "plenty": "muitas", "pinch": "uma pitada", - "handful": { "singular": "mão-cheia", "plural": "mãos-cheias" }, - "teaspoon": { "singular": "colher de chá", "plural": "colheres de chá" }, - "spoon": { "singular": "colher", "plural": "colheres" }, - "cup": { "singular": "chávena", "plural": "chávenas" }, - "jar": { "singular": "frasco", "plural": "frascos" }, - "sack": { "singular": "saco", "plural": "sacos" }, - "packet": { "singular": "pacote", "plural": "pacotes" }, - "cob": { "singular": "maçaroca", "plural": "maçarocas" }, - "pod": { "singular": "vagem", "plural": "vagens" }, - "ear": { "singular": "espiga", "plural": "espigas" }, - "head": { "singular": "cabeça", "plural": "cabeças" }, - "fruit": { "singular": "fruto", "plural": "frutos" }, - "bulb": { "singular": "bolbo", "plural": "bolbos" }, - "tuber": { "singular": "tubérculo", "plural": "tubérculos" }, - "seedHead": { "singular": "capítulo", "plural": "capítulos" }, - "bunch": { "singular": "molho", "plural": "molhos" }, - "plant": { "singular": "planta", "plural": "plantas" }, - "pot": { "singular": "vaso", "plural": "vasos" }, - "tray": { "singular": "tabuleiro", "plural": "tabuleiros" }, - "seedling": { "singular": "plântula", "plural": "plântulas" }, - "tree": { "singular": "árvore", "plural": "árvores" }, - "cutting": { "singular": "estaca", "plural": "estacas" }, - "grams": { "singular": "grama", "plural": "gramas" }, - "count": { "singular": "semente", "plural": "sementes" } + "handful": { + "singular": "mão-cheia", + "plural": "mãos-cheias" + }, + "teaspoon": { + "singular": "colher de chá", + "plural": "colheres de chá" + }, + "spoon": { + "singular": "colher", + "plural": "colheres" + }, + "cup": { + "singular": "chávena", + "plural": "chávenas" + }, + "jar": { + "singular": "frasco", + "plural": "frascos" + }, + "sack": { + "singular": "saco", + "plural": "sacos" + }, + "packet": { + "singular": "pacote", + "plural": "pacotes" + }, + "cob": { + "singular": "maçaroca", + "plural": "maçarocas" + }, + "pod": { + "singular": "vagem", + "plural": "vagens" + }, + "ear": { + "singular": "espiga", + "plural": "espigas" + }, + "head": { + "singular": "cabeça", + "plural": "cabeças" + }, + "fruit": { + "singular": "fruto", + "plural": "frutos" + }, + "bulb": { + "singular": "bolbo", + "plural": "bolbos" + }, + "tuber": { + "singular": "tubérculo", + "plural": "tubérculos" + }, + "seedHead": { + "singular": "capítulo", + "plural": "capítulos" + }, + "bunch": { + "singular": "molho", + "plural": "molhos" + }, + "plant": { + "singular": "planta", + "plural": "plantas" + }, + "pot": { + "singular": "vaso", + "plural": "vasos" + }, + "tray": { + "singular": "tabuleiro", + "plural": "tabuleiros" + }, + "seedling": { + "singular": "plântula", + "plural": "plântulas" + }, + "tree": { + "singular": "árvore", + "plural": "árvores" + }, + "cutting": { + "singular": "estaca", + "plural": "estacas" + }, + "grams": { + "singular": "grama", + "plural": "gramas" + }, + "count": { + "singular": "semente", + "plural": "sementes" + } }, "market": { "title": "Sementes perto de ti", @@ -399,7 +481,8 @@ "sharedBy": "Partilhado por", "noProfile": "Esta pessoa ainda não partilhou o seu perfil", "copyId": "Copiar código", - "idCopied": "Código copiado" + "idCopied": "Código copiado", + "photo": "Foto" }, "profile": { "title": "O teu perfil", diff --git a/apps/app_seeds/lib/i18n/strings.g.dart b/apps/app_seeds/lib/i18n/strings.g.dart index fb59798..0277a3c 100644 --- a/apps/app_seeds/lib/i18n/strings.g.dart +++ b/apps/app_seeds/lib/i18n/strings.g.dart @@ -4,9 +4,9 @@ /// To regenerate, run: `dart run slang` /// /// Locales: 4 -/// Strings: 1548 (387 per locale) +/// Strings: 1552 (388 per locale) /// -/// Built on 2026-07-10 at 17:18 UTC +/// Built on 2026-07-10 at 18:55 UTC // coverage:ignore-file // ignore_for_file: type=lint, unused_import diff --git a/apps/app_seeds/lib/i18n/strings_ast.g.dart b/apps/app_seeds/lib/i18n/strings_ast.g.dart index 2f83eb6..1d7ac78 100644 --- a/apps/app_seeds/lib/i18n/strings_ast.g.dart +++ b/apps/app_seeds/lib/i18n/strings_ast.g.dart @@ -691,6 +691,7 @@ class _Translations$market$ast extends Translations$market$en { @override String get noProfile => 'Esta persona entá nun compartió\'l so perfil'; @override String get copyId => 'Copiar códigu'; @override String get idCopied => 'Códigu copiáu'; + @override String get photo => 'Semeya'; } // Path: profile @@ -1456,6 +1457,7 @@ extension on TranslationsAst { 'market.noProfile' => 'Esta persona entá nun compartió\'l so perfil', 'market.copyId' => 'Copiar códigu', 'market.idCopied' => 'Códigu copiáu', + 'market.photo' => 'Semeya', 'profile.title' => 'El to perfil', 'profile.name' => 'Nome', 'profile.nameHint' => 'Cómo te ven los demás', diff --git a/apps/app_seeds/lib/i18n/strings_en.g.dart b/apps/app_seeds/lib/i18n/strings_en.g.dart index 7785576..9ca3bab 100644 --- a/apps/app_seeds/lib/i18n/strings_en.g.dart +++ b/apps/app_seeds/lib/i18n/strings_en.g.dart @@ -1282,6 +1282,9 @@ class Translations$market$en { /// en: 'Code copied' String get idCopied => 'Code copied'; + + /// en: 'Photo' + String get photo => 'Photo'; } // Path: profile @@ -2220,6 +2223,7 @@ extension on Translations { 'market.noProfile' => 'This person hasn\'t shared a profile yet', 'market.copyId' => 'Copy code', 'market.idCopied' => 'Code copied', + 'market.photo' => 'Photo', 'profile.title' => 'Your profile', 'profile.name' => 'Display name', 'profile.nameHint' => 'How others see you', diff --git a/apps/app_seeds/lib/i18n/strings_es.g.dart b/apps/app_seeds/lib/i18n/strings_es.g.dart index 98d6f12..797f3a6 100644 --- a/apps/app_seeds/lib/i18n/strings_es.g.dart +++ b/apps/app_seeds/lib/i18n/strings_es.g.dart @@ -693,6 +693,7 @@ class _Translations$market$es extends Translations$market$en { @override String get noProfile => 'Esta persona aún no ha compartido su perfil'; @override String get copyId => 'Copiar código'; @override String get idCopied => 'Código copiado'; + @override String get photo => 'Foto'; } // Path: profile @@ -1460,6 +1461,7 @@ extension on TranslationsEs { 'market.noProfile' => 'Esta persona aún no ha compartido su perfil', 'market.copyId' => 'Copiar código', 'market.idCopied' => 'Código copiado', + 'market.photo' => 'Foto', 'profile.title' => 'Tu perfil', 'profile.name' => 'Nombre', 'profile.nameHint' => 'Cómo te ven los demás', diff --git a/apps/app_seeds/lib/i18n/strings_pt.g.dart b/apps/app_seeds/lib/i18n/strings_pt.g.dart index 22249a5..f74354e 100644 --- a/apps/app_seeds/lib/i18n/strings_pt.g.dart +++ b/apps/app_seeds/lib/i18n/strings_pt.g.dart @@ -690,6 +690,7 @@ class _Translations$market$pt extends Translations$market$en { @override String get noProfile => 'Esta pessoa ainda não partilhou o seu perfil'; @override String get copyId => 'Copiar código'; @override String get idCopied => 'Código copiado'; + @override String get photo => 'Foto'; } // Path: profile @@ -1454,6 +1455,7 @@ extension on TranslationsPt { 'market.noProfile' => 'Esta pessoa ainda não partilhou o seu perfil', 'market.copyId' => 'Copiar código', 'market.idCopied' => 'Código copiado', + 'market.photo' => 'Foto', 'profile.title' => 'O teu perfil', 'profile.name' => 'Nome', 'profile.nameHint' => 'Como os outros te veem', diff --git a/apps/app_seeds/lib/ui/market_offer_detail_screen.dart b/apps/app_seeds/lib/ui/market_offer_detail_screen.dart index ac81f23..0f408ed 100644 --- a/apps/app_seeds/lib/ui/market_offer_detail_screen.dart +++ b/apps/app_seeds/lib/ui/market_offer_detail_screen.dart @@ -123,6 +123,10 @@ class _MarketOfferDetailScreenState extends State { body: ListView( padding: const EdgeInsets.all(16), children: [ + if (o.imageUrl != null) ...[ + OfferHeroImage(url: o.imageUrl!, semanticLabel: t.market.photo), + const SizedBox(height: 16), + ], Row( children: [ Expanded( diff --git a/apps/app_seeds/lib/ui/market_screen.dart b/apps/app_seeds/lib/ui/market_screen.dart index 0c405a2..ef4a753 100644 --- a/apps/app_seeds/lib/ui/market_screen.dart +++ b/apps/app_seeds/lib/ui/market_screen.dart @@ -380,6 +380,13 @@ class _OfferCard extends StatelessWidget { children: [ Row( children: [ + if (offer.imageUrl != null) ...[ + OfferThumbnail( + url: offer.imageUrl!, + semanticLabel: t.market.photo, + ), + const SizedBox(width: 12), + ], Expanded( child: Text( offer.summary, diff --git a/apps/app_seeds/lib/ui/market_widgets.dart b/apps/app_seeds/lib/ui/market_widgets.dart index 155eefa..b743ada 100644 --- a/apps/app_seeds/lib/ui/market_widgets.dart +++ b/apps/app_seeds/lib/ui/market_widgets.dart @@ -14,6 +14,98 @@ String offerTypeLabel(Translations t, OfferType type) => switch (type) { OfferType.lend => t.share.exchange, }; +/// A small square thumbnail of an offer's photo for the market list card. +/// Remote (published) image, so it degrades gracefully: a spinner while it +/// loads and a neutral placeholder when the media server can't be reached. +class OfferThumbnail extends StatelessWidget { + const OfferThumbnail({ + required this.url, + required this.semanticLabel, + this.size = 56, + super.key, + }); + + final String url; + final String semanticLabel; + final double size; + + @override + Widget build(BuildContext context) { + return ClipRRect( + borderRadius: BorderRadius.circular(10), + child: Image.network( + url, + width: size, + height: size, + fit: BoxFit.cover, + semanticLabel: semanticLabel, + loadingBuilder: (context, child, progress) => progress == null + ? child + : _OfferImagePlaceholder(size: size, loading: true), + errorBuilder: (context, _, _) => _OfferImagePlaceholder(size: size), + ), + ); + } +} + +/// Full-width "hero" image atop the offer detail page. Same graceful +/// degradation as [OfferThumbnail]; hidden entirely when the offer has no photo. +class OfferHeroImage extends StatelessWidget { + const OfferHeroImage({ + required this.url, + required this.semanticLabel, + super.key, + }); + + final String url; + final String semanticLabel; + + @override + Widget build(BuildContext context) { + return ClipRRect( + borderRadius: BorderRadius.circular(14), + child: AspectRatio( + aspectRatio: 4 / 3, + child: Image.network( + url, + fit: BoxFit.cover, + semanticLabel: semanticLabel, + loadingBuilder: (context, child, progress) => progress == null + ? child + : const _OfferImagePlaceholder(loading: true), + errorBuilder: (context, _, _) => const _OfferImagePlaceholder(), + ), + ), + ); + } +} + +/// Neutral fill shown while a remote offer image loads or when it can't be +/// fetched — a marketplace is useless if a broken image blocks the card. +class _OfferImagePlaceholder extends StatelessWidget { + const _OfferImagePlaceholder({this.size, this.loading = false}); + + final double? size; + final bool loading; + + @override + Widget build(BuildContext context) { + return Container( + width: size, + height: size, + color: seedPrimaryContainer.withValues(alpha: 0.4), + alignment: Alignment.center, + child: loading + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.image_not_supported_outlined, color: seedMuted), + ); + } +} + /// The small pill showing an offer's reciprocity mode (give/swap/sell/wanted). class OfferTypeChip extends StatelessWidget { const OfferTypeChip({required this.label, super.key}); diff --git a/apps/app_seeds/test/ui/market_offer_detail_screen_test.dart b/apps/app_seeds/test/ui/market_offer_detail_screen_test.dart index 63fa9b4..d431faa 100644 --- a/apps/app_seeds/test/ui/market_offer_detail_screen_test.dart +++ b/apps/app_seeds/test/ui/market_offer_detail_screen_test.dart @@ -6,6 +6,7 @@ import 'package:tane/i18n/strings.g.dart'; import 'package:tane/services/social_service.dart'; import 'package:tane/services/social_settings.dart'; import 'package:tane/ui/market_offer_detail_screen.dart'; +import 'package:tane/ui/market_widgets.dart'; import '../support/test_support.dart'; @@ -25,7 +26,7 @@ Widget _wrap(MarketOfferDetailScreen screen) { ); } -Offer _offer({bool organic = false}) => Offer( +Offer _offer({bool organic = false, String? imageUrl}) => Offer( id: 'lot-1', authorPubkeyHex: 'ab' * 32, summary: 'Tomate rosa de Barbastro', @@ -33,6 +34,7 @@ Offer _offer({bool organic = false}) => Offer( category: 'Solanaceae', approxGeohash: 'sp3e9', isOrganic: organic, + imageUrl: imageUrl, ); void main() { @@ -70,4 +72,34 @@ void main() { expect(find.byKey(const Key('offerDetail.contact')), findsNothing); }); + + testWidgets('shows a hero image when the offer has a photo', (tester) async { + final social = await SocialService.fromRootSeedHex('00' * 32); + final settings = SocialSettings(InMemorySecretStore()); + await settings.setRelayUrls(const []); + + await tester.pumpWidget(_wrap(MarketOfferDetailScreen( + offer: _offer(imageUrl: 'https://media.example/abc.jpg'), + social: social, + settings: settings, + ))); + await tester.pumpAndSettle(); + + expect(find.byType(OfferHeroImage), findsOneWidget); + }); + + testWidgets('shows no hero image when the offer has none', (tester) async { + final social = await SocialService.fromRootSeedHex('00' * 32); + final settings = SocialSettings(InMemorySecretStore()); + await settings.setRelayUrls(const []); + + await tester.pumpWidget(_wrap(MarketOfferDetailScreen( + offer: _offer(), + social: social, + settings: settings, + ))); + await tester.pumpAndSettle(); + + expect(find.byType(OfferHeroImage), findsNothing); + }); } diff --git a/apps/app_seeds/test/ui/market_widgets_test.dart b/apps/app_seeds/test/ui/market_widgets_test.dart new file mode 100644 index 0000000..1108049 --- /dev/null +++ b/apps/app_seeds/test/ui/market_widgets_test.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:tane/ui/market_widgets.dart'; + +Widget _wrap(Widget child) => MaterialApp(home: Scaffold(body: Center(child: child))); + +void main() { + testWidgets('OfferThumbnail builds a network image', (tester) async { + await tester.pumpWidget( + _wrap(const OfferThumbnail( + url: 'https://media.example/abc.jpg', + semanticLabel: 'Photo', + )), + ); + // The image widget is present; its loadingBuilder/errorBuilder handle the + // remote fetch, so we only assert the widget is wired (no network in tests). + expect(find.byType(Image), findsOneWidget); + }); + + testWidgets('OfferThumbnail falls back to a placeholder when the load fails', + (tester) async { + await tester.pumpWidget( + _wrap(const OfferThumbnail( + url: 'https://media.example/missing.jpg', + semanticLabel: 'Photo', + )), + ); + // Let the (failed) network fetch resolve; the errorBuilder then shows a + // neutral icon instead of a broken image. + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + + expect(find.byIcon(Icons.image_not_supported_outlined), findsOneWidget); + }); + + testWidgets('OfferHeroImage builds a network image', (tester) async { + await tester.pumpWidget( + _wrap(const OfferHeroImage( + url: 'https://media.example/abc.jpg', + semanticLabel: 'Photo', + )), + ); + expect(find.byType(Image), findsOneWidget); + }); +} From 5bc1715637409a7c4e49ed59cef333a3882a6ad7 Mon Sep 17 00:00:00 2001 From: vjrj Date: Fri, 10 Jul 2026 21:04:47 +0200 Subject: [PATCH 2/4] feat(commons_core): Blossom MediaTransport for offer photos Add a MediaTransport interface (sibling of Offer/Message/Trust transports) and a Blossom (BUD-01/02) backend: sign a kind-24242 upload auth with the same secp256k1 identity, PUT the bytes over HTTP, return the content- addressed URL. Idempotent by SHA-256; http.Client injected for tests. --- packages/commons_core/lib/commons_core.dart | 2 + .../lib/src/social/media_transport.dart | 22 ++++ .../social/nostr/blossom_media_transport.dart | 114 ++++++++++++++++++ packages/commons_core/pubspec.yaml | 5 + .../social/blossom_media_transport_test.dart | 90 ++++++++++++++ 5 files changed, 233 insertions(+) create mode 100644 packages/commons_core/lib/src/social/media_transport.dart create mode 100644 packages/commons_core/lib/src/social/nostr/blossom_media_transport.dart create mode 100644 packages/commons_core/test/social/blossom_media_transport_test.dart diff --git a/packages/commons_core/lib/commons_core.dart b/packages/commons_core/lib/commons_core.dart index 515a513..e3e713b 100644 --- a/packages/commons_core/lib/commons_core.dart +++ b/packages/commons_core/lib/commons_core.dart @@ -13,7 +13,9 @@ export 'src/identity/nostr_key_derivation.dart'; export 'src/ids/id_gen.dart'; export 'src/social/certification.dart'; export 'src/social/geohash.dart'; +export 'src/social/media_transport.dart'; export 'src/social/message_transport.dart'; +export 'src/social/nostr/blossom_media_transport.dart'; export 'src/social/nostr/nostr_channel.dart'; export 'src/social/nostr/nostr_connection.dart'; export 'src/social/nostr/nostr_message_transport.dart'; diff --git a/packages/commons_core/lib/src/social/media_transport.dart b/packages/commons_core/lib/src/social/media_transport.dart new file mode 100644 index 0000000..4e7c044 --- /dev/null +++ b/packages/commons_core/lib/src/social/media_transport.dart @@ -0,0 +1,22 @@ +import 'dart:typed_data'; + +/// Uploads a public image and returns a URL peers can fetch — the hosting seam +/// for offer photos. An [Offer] carries only a URL on the wire (NIP-99), never +/// bytes; this transport turns local bytes into that URL. +/// +/// A sibling of [OfferTransport]/`MessageTransport`/`TrustTransport`, but it does +/// NOT ride the relay websocket: media goes over plain HTTP to a media server +/// (Blossom), so it takes its own endpoint rather than a `NostrChannel`. +/// +/// Uploading a photo here publishes it: an offer is a public shop window the +/// person elected to reveal, so its image is public too. This is distinct from +/// the encrypted-at-rest inventory — nothing local is exposed by this seam. +abstract interface class MediaTransport { + /// Uploads [bytes] and returns the public URL. Expected to be idempotent for + /// content-addressed backends (re-uploading the same bytes yields the same + /// URL). Throws when the server rejects the upload or is unreachable — callers + /// degrade by publishing the offer without an image. + Future upload(Uint8List bytes, {required String mimeType}); + + Future close(); +} diff --git a/packages/commons_core/lib/src/social/nostr/blossom_media_transport.dart b/packages/commons_core/lib/src/social/nostr/blossom_media_transport.dart new file mode 100644 index 0000000..e80aabc --- /dev/null +++ b/packages/commons_core/lib/src/social/nostr/blossom_media_transport.dart @@ -0,0 +1,114 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart' as crypto; +import 'package:http/http.dart' as http; +import 'package:nostr/nostr.dart'; + +import '../media_transport.dart'; + +/// [MediaTransport] backed by a Blossom media server (BUD-01/02). +/// +/// Blossom is content-addressed: a blob's URL is derived from its SHA-256, so +/// uploads are idempotent (the server dedups) and the URL is deterministic. We +/// authorize each upload with a signed kind-24242 event — the same secp256k1 +/// identity that signs offers — and PUT the bytes; no relay is involved. +class BlossomMediaTransport implements MediaTransport { + BlossomMediaTransport( + Uri server, + this._secretKeyHex, { + http.Client? client, + Duration authTtl = const Duration(hours: 1), + }) : _server = _normalize(server), + _client = client ?? http.Client(), + _ownsClient = client == null, + _authTtl = authTtl; + + /// Blossom kind for upload/list/delete authorization events (BUD-01). + static const authKind = 24242; + + final Uri _server; + final String _secretKeyHex; + final http.Client _client; + final bool _ownsClient; + final Duration _authTtl; + + @override + Future upload(Uint8List bytes, {required String mimeType}) async { + final sha = crypto.sha256.convert(bytes).toString(); + final auth = _authEvent(sha); + final response = await _client.put( + _server.resolve('upload'), + headers: { + 'Authorization': 'Nostr ${base64.encode(utf8.encode(auth.toJson()))}', + 'Content-Type': mimeType, + }, + body: bytes, + ); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw MediaUploadException( + 'Blossom upload failed (${response.statusCode})', + response.statusCode, + ); + } + return _urlFrom(response.body, sha); + } + + /// Signed kind-24242 authorization: declares an `upload`, the blob's hash, and + /// an expiry so a captured header can't be replayed forever. + Event _authEvent(String sha256hex) { + final expiry = + DateTime.now().add(_authTtl).millisecondsSinceEpoch ~/ 1000; + return Event.from( + kind: authKind, + content: 'Upload offer photo', + tags: [ + ['t', 'upload'], + ['x', sha256hex], + ['expiration', '$expiry'], + ], + secretKey: _secretKeyHex, + ); + } + + /// Prefers the `url` from the blob descriptor the server returns; falls back to + /// the deterministic `/` when the body is missing or unparsable. + Uri _urlFrom(String body, String sha256hex) { + if (body.isNotEmpty) { + try { + final decoded = json.decode(body); + if (decoded is Map && decoded['url'] is String) { + final url = (decoded['url'] as String).trim(); + if (url.isNotEmpty) return Uri.parse(url); + } + } on FormatException { + // Non-JSON body — fall through to the content-addressed URL. + } + } + return _server.resolve(sha256hex); + } + + static Uri _normalize(Uri server) { + // Ensure a trailing slash so `resolve('upload')` appends rather than + // replacing the last path segment. + if (server.path.endsWith('/')) return server; + return server.replace(path: '${server.path}/'); + } + + @override + Future close() async { + if (_ownsClient) _client.close(); + } +} + +/// Thrown when the media server rejects an upload. Callers treat it as "publish +/// the offer without a photo", never as a hard failure of sharing. +class MediaUploadException implements Exception { + const MediaUploadException(this.message, this.statusCode); + + final String message; + final int statusCode; + + @override + String toString() => 'MediaUploadException($statusCode): $message'; +} diff --git a/packages/commons_core/pubspec.yaml b/packages/commons_core/pubspec.yaml index ef9d76a..7a522b4 100644 --- a/packages/commons_core/pubspec.yaml +++ b/packages/commons_core/pubspec.yaml @@ -21,6 +21,11 @@ dependencies: # signing, NIP-19, NIP-44, gift wrap — the vetted crypto for the social layer # transport. We keep the relay/websocket layer and our derivation on top. nostr: ^2.0.0 + # Plain HTTP (BSD-3, AGPL-compatible) for the Blossom media server — offer + # photos are uploaded over HTTP, not the relay websocket. Client is injectable. + http: ^1.2.0 + # Sync SHA-256 (BSD-3) for content-addressed Blossom blob ids. + crypto: ^3.0.3 dev_dependencies: lints: ^6.0.0 diff --git a/packages/commons_core/test/social/blossom_media_transport_test.dart b/packages/commons_core/test/social/blossom_media_transport_test.dart new file mode 100644 index 0000000..15ea2d1 --- /dev/null +++ b/packages/commons_core/test/social/blossom_media_transport_test.dart @@ -0,0 +1,90 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:commons_core/commons_core.dart'; +import 'package:crypto/crypto.dart' as crypto; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:nostr/nostr.dart'; +import 'package:test/test.dart'; + +void main() { + Future secretKey() async { + final id = await NostrKeyDerivation.deriveFromSeed( + Uint8List(32)..fillRange(0, 32, 7), + ); + return id.privateKeyHex; + } + + final bytes = Uint8List.fromList(List.generate(64, (i) => i)); + final sha = crypto.sha256.convert(bytes).toString(); + + test('PUTs to /upload with a signed kind-24242 auth and returns the url', + () async { + late http.Request captured; + final client = MockClient((req) async { + captured = req; + return http.Response( + json.encode({'url': 'https://media.test/$sha.jpg', 'sha256': sha}), + 200, + ); + }); + final transport = BlossomMediaTransport( + Uri.parse('https://media.test'), + await secretKey(), + client: client, + ); + + final url = await transport.upload(bytes, mimeType: 'image/jpeg'); + + expect(url, Uri.parse('https://media.test/$sha.jpg')); + expect(captured.method, 'PUT'); + expect(captured.url, Uri.parse('https://media.test/upload')); + expect(captured.bodyBytes, bytes); + expect(captured.headers['content-type'], startsWith('image/jpeg')); + + // The Authorization header is a base64 Nostr event; decode and inspect it. + final header = captured.headers['authorization']!; + expect(header, startsWith('Nostr ')); + final event = Event.fromMap( + json.decode(utf8.decode(base64.decode(header.substring(6)))) + as Map, + verify: true, // a real Schnorr signature over the canonical id + ); + expect(event.kind, BlossomMediaTransport.authKind); + String? tag(String name) => event.tags + .firstWhere((t) => t.isNotEmpty && t[0] == name, orElse: () => const []) + .elementAtOrNull(1); + expect(tag('t'), 'upload'); + expect(tag('x'), sha); + expect(tag('expiration'), isNotNull); + }); + + test('falls back to / when the body carries no url', () async { + final client = MockClient((req) async => http.Response('', 200)); + final transport = BlossomMediaTransport( + Uri.parse('https://media.test/'), + await secretKey(), + client: client, + ); + + final url = await transport.upload(bytes, mimeType: 'image/jpeg'); + + expect(url, Uri.parse('https://media.test/$sha')); + }); + + test('throws MediaUploadException on a non-2xx response', () async { + final client = MockClient((req) async => http.Response('nope', 413)); + final transport = BlossomMediaTransport( + Uri.parse('https://media.test'), + await secretKey(), + client: client, + ); + + expect( + () => transport.upload(bytes, mimeType: 'image/jpeg'), + throwsA(isA() + .having((e) => e.statusCode, 'statusCode', 413)), + ); + }); +} From fa53295439db6533ef9049ed200d28dc1eaac84b Mon Sep 17 00:00:00 2001 From: vjrj Date: Fri, 10 Jul 2026 21:12:36 +0200 Subject: [PATCH 3/4] feat(market): host and publish the cover photo with each offer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wire the Blossom MediaTransport into publishing: shareable lots carry their varietyId, publishLots uploads the lot's cover photo and puts the returned URL on the offer (best-effort — a hosting failure still publishes the offer, just without a photo). Add a configurable media server (Comunes default, empty to opt out) to settings and the market advanced config. --- .../lib/data/variety_repository.dart | 14 ++- apps/app_seeds/lib/i18n/ast.i18n.json | 4 +- apps/app_seeds/lib/i18n/en.i18n.json | 4 +- apps/app_seeds/lib/i18n/es.i18n.json | 4 +- apps/app_seeds/lib/i18n/pt.i18n.json | 4 +- apps/app_seeds/lib/i18n/strings.g.dart | 4 +- apps/app_seeds/lib/i18n/strings_ast.g.dart | 4 + apps/app_seeds/lib/i18n/strings_en.g.dart | 8 ++ apps/app_seeds/lib/i18n/strings_es.g.dart | 4 + apps/app_seeds/lib/i18n/strings_pt.g.dart | 4 + .../lib/services/social_service.dart | 33 ++++- .../lib/services/social_settings.dart | 18 +++ apps/app_seeds/lib/state/offers_cubit.dart | 53 +++++++- apps/app_seeds/lib/ui/market_screen.dart | 20 +++- .../test/services/social_settings_test.dart | 9 ++ .../test/state/offers_cubit_test.dart | 113 +++++++++++++++++- .../test/social/nostr_transports_test.dart | 2 + 17 files changed, 280 insertions(+), 22 deletions(-) diff --git a/apps/app_seeds/lib/data/variety_repository.dart b/apps/app_seeds/lib/data/variety_repository.dart index 4c30010..21955d0 100644 --- a/apps/app_seeds/lib/data/variety_repository.dart +++ b/apps/app_seeds/lib/data/variety_repository.dart @@ -174,6 +174,7 @@ class SeedLabelEntry extends Equatable { class ShareableLot extends Equatable { const ShareableLot({ required this.lotId, + required this.varietyId, required this.summary, required this.offerStatus, this.category, @@ -183,6 +184,10 @@ class ShareableLot extends Equatable { final String lotId; + /// The lot's variety, so the publish step can fetch its cover photo to host + /// as the offer image. Not published itself — never leaves the device. + final String varietyId; + /// What to publish: the variety label (never the full inventory). final String summary; @@ -197,7 +202,7 @@ class ShareableLot extends Equatable { @override List get props => - [lotId, summary, offerStatus, category, harvestYear, isOrganic]; + [lotId, varietyId, summary, offerStatus, category, harvestYear, isOrganic]; } /// One germination test on a lot; [rate] is derived (0..1), null when it can't @@ -727,6 +732,12 @@ class VarietyRepository { return byVariety; } + /// The cover photo (lowest `sortOrder`) for a single variety, or null when it + /// has none. Used by the publish step to host an offer's image; reuses the + /// same "first photo" rule as the inventory avatar. + Future coverPhotoFor(String varietyId) async => + (await _firstPhotosFor([varietyId]))[varietyId]; + /// Maps each of [speciesIds] to its scientific name (one query). Future> _scientificNamesFor( Set speciesIds, @@ -1461,6 +1472,7 @@ class VarietyRepository { if (byId[l.varietyId] case final v?) ShareableLot( lotId: l.id, + varietyId: v.id, summary: v.label, offerStatus: l.offerStatus, category: v.category, diff --git a/apps/app_seeds/lib/i18n/ast.i18n.json b/apps/app_seeds/lib/i18n/ast.i18n.json index 31dd7a0..4fc4cec 100644 --- a/apps/app_seeds/lib/i18n/ast.i18n.json +++ b/apps/app_seeds/lib/i18n/ast.i18n.json @@ -483,7 +483,9 @@ "noProfile": "Esta persona entá nun compartió'l so perfil", "copyId": "Copiar códigu", "idCopied": "Códigu copiáu", - "photo": "Semeya" + "photo": "Semeya", + "mediaServerLabel": "Sirvidor de semeyes", + "mediaServerHelp": "Ónde s'agospien les semeyes de les ufiertes pa que otres persones les vean. Déxalo baleru pa compartir ensin semeyes." }, "profile": { "title": "El to perfil", diff --git a/apps/app_seeds/lib/i18n/en.i18n.json b/apps/app_seeds/lib/i18n/en.i18n.json index a746708..e663b1a 100644 --- a/apps/app_seeds/lib/i18n/en.i18n.json +++ b/apps/app_seeds/lib/i18n/en.i18n.json @@ -486,7 +486,9 @@ "noProfile": "This person hasn't shared a profile yet", "copyId": "Copy code", "idCopied": "Code copied", - "photo": "Photo" + "photo": "Photo", + "mediaServerLabel": "Photo server", + "mediaServerHelp": "Where offer photos are hosted so others can see them. Leave empty to share without photos." }, "profile": { "title": "Your profile", diff --git a/apps/app_seeds/lib/i18n/es.i18n.json b/apps/app_seeds/lib/i18n/es.i18n.json index 0f1e1a6..32c1257 100644 --- a/apps/app_seeds/lib/i18n/es.i18n.json +++ b/apps/app_seeds/lib/i18n/es.i18n.json @@ -485,7 +485,9 @@ "noProfile": "Esta persona aún no ha compartido su perfil", "copyId": "Copiar código", "idCopied": "Código copiado", - "photo": "Foto" + "photo": "Foto", + "mediaServerLabel": "Servidor de fotos", + "mediaServerHelp": "Dónde se alojan las fotos de las ofertas para que otras personas las vean. Déjalo vacío para compartir sin fotos." }, "profile": { "title": "Tu perfil", diff --git a/apps/app_seeds/lib/i18n/pt.i18n.json b/apps/app_seeds/lib/i18n/pt.i18n.json index 72a30db..e8fb01d 100644 --- a/apps/app_seeds/lib/i18n/pt.i18n.json +++ b/apps/app_seeds/lib/i18n/pt.i18n.json @@ -482,7 +482,9 @@ "noProfile": "Esta pessoa ainda não partilhou o seu perfil", "copyId": "Copiar código", "idCopied": "Código copiado", - "photo": "Foto" + "photo": "Foto", + "mediaServerLabel": "Servidor de fotos", + "mediaServerHelp": "Onde as fotos das ofertas ficam alojadas para que outras pessoas as vejam. Deixe vazio para partilhar sem fotos." }, "profile": { "title": "O teu perfil", diff --git a/apps/app_seeds/lib/i18n/strings.g.dart b/apps/app_seeds/lib/i18n/strings.g.dart index 0277a3c..c65da8b 100644 --- a/apps/app_seeds/lib/i18n/strings.g.dart +++ b/apps/app_seeds/lib/i18n/strings.g.dart @@ -4,9 +4,9 @@ /// To regenerate, run: `dart run slang` /// /// Locales: 4 -/// Strings: 1552 (388 per locale) +/// Strings: 1560 (390 per locale) /// -/// Built on 2026-07-10 at 18:55 UTC +/// Built on 2026-07-10 at 19:08 UTC // coverage:ignore-file // ignore_for_file: type=lint, unused_import diff --git a/apps/app_seeds/lib/i18n/strings_ast.g.dart b/apps/app_seeds/lib/i18n/strings_ast.g.dart index 1d7ac78..1c8c3f6 100644 --- a/apps/app_seeds/lib/i18n/strings_ast.g.dart +++ b/apps/app_seeds/lib/i18n/strings_ast.g.dart @@ -692,6 +692,8 @@ class _Translations$market$ast extends Translations$market$en { @override String get copyId => 'Copiar códigu'; @override String get idCopied => 'Códigu copiáu'; @override String get photo => 'Semeya'; + @override String get mediaServerLabel => 'Sirvidor de semeyes'; + @override String get mediaServerHelp => 'Ónde s\'agospien les semeyes de les ufiertes pa que otres persones les vean. Déxalo baleru pa compartir ensin semeyes.'; } // Path: profile @@ -1458,6 +1460,8 @@ extension on TranslationsAst { 'market.copyId' => 'Copiar códigu', 'market.idCopied' => 'Códigu copiáu', 'market.photo' => 'Semeya', + 'market.mediaServerLabel' => 'Sirvidor de semeyes', + 'market.mediaServerHelp' => 'Ónde s\'agospien les semeyes de les ufiertes pa que otres persones les vean. Déxalo baleru pa compartir ensin semeyes.', 'profile.title' => 'El to perfil', 'profile.name' => 'Nome', 'profile.nameHint' => 'Cómo te ven los demás', diff --git a/apps/app_seeds/lib/i18n/strings_en.g.dart b/apps/app_seeds/lib/i18n/strings_en.g.dart index 9ca3bab..47e7b21 100644 --- a/apps/app_seeds/lib/i18n/strings_en.g.dart +++ b/apps/app_seeds/lib/i18n/strings_en.g.dart @@ -1285,6 +1285,12 @@ class Translations$market$en { /// en: 'Photo' String get photo => 'Photo'; + + /// en: 'Photo server' + String get mediaServerLabel => 'Photo server'; + + /// en: 'Where offer photos are hosted so others can see them. Leave empty to share without photos.' + String get mediaServerHelp => 'Where offer photos are hosted so others can see them. Leave empty to share without photos.'; } // Path: profile @@ -2224,6 +2230,8 @@ extension on Translations { 'market.copyId' => 'Copy code', 'market.idCopied' => 'Code copied', 'market.photo' => 'Photo', + 'market.mediaServerLabel' => 'Photo server', + 'market.mediaServerHelp' => 'Where offer photos are hosted so others can see them. Leave empty to share without photos.', 'profile.title' => 'Your profile', 'profile.name' => 'Display name', 'profile.nameHint' => 'How others see you', diff --git a/apps/app_seeds/lib/i18n/strings_es.g.dart b/apps/app_seeds/lib/i18n/strings_es.g.dart index 797f3a6..c1062a8 100644 --- a/apps/app_seeds/lib/i18n/strings_es.g.dart +++ b/apps/app_seeds/lib/i18n/strings_es.g.dart @@ -694,6 +694,8 @@ class _Translations$market$es extends Translations$market$en { @override String get copyId => 'Copiar código'; @override String get idCopied => 'Código copiado'; @override String get photo => 'Foto'; + @override String get mediaServerLabel => 'Servidor de fotos'; + @override String get mediaServerHelp => 'Dónde se alojan las fotos de las ofertas para que otras personas las vean. Déjalo vacío para compartir sin fotos.'; } // Path: profile @@ -1462,6 +1464,8 @@ extension on TranslationsEs { 'market.copyId' => 'Copiar código', 'market.idCopied' => 'Código copiado', 'market.photo' => 'Foto', + 'market.mediaServerLabel' => 'Servidor de fotos', + 'market.mediaServerHelp' => 'Dónde se alojan las fotos de las ofertas para que otras personas las vean. Déjalo vacío para compartir sin fotos.', 'profile.title' => 'Tu perfil', 'profile.name' => 'Nombre', 'profile.nameHint' => 'Cómo te ven los demás', diff --git a/apps/app_seeds/lib/i18n/strings_pt.g.dart b/apps/app_seeds/lib/i18n/strings_pt.g.dart index f74354e..46e92de 100644 --- a/apps/app_seeds/lib/i18n/strings_pt.g.dart +++ b/apps/app_seeds/lib/i18n/strings_pt.g.dart @@ -691,6 +691,8 @@ class _Translations$market$pt extends Translations$market$en { @override String get copyId => 'Copiar código'; @override String get idCopied => 'Código copiado'; @override String get photo => 'Foto'; + @override String get mediaServerLabel => 'Servidor de fotos'; + @override String get mediaServerHelp => 'Onde as fotos das ofertas ficam alojadas para que outras pessoas as vejam. Deixe vazio para partilhar sem fotos.'; } // Path: profile @@ -1456,6 +1458,8 @@ extension on TranslationsPt { 'market.copyId' => 'Copiar código', 'market.idCopied' => 'Código copiado', 'market.photo' => 'Foto', + 'market.mediaServerLabel' => 'Servidor de fotos', + 'market.mediaServerHelp' => 'Onde as fotos das ofertas ficam alojadas para que outras pessoas as vejam. Deixe vazio para partilhar sem fotos.', 'profile.title' => 'O teu perfil', 'profile.name' => 'Nome', 'profile.nameHint' => 'Como os outros te veem', diff --git a/apps/app_seeds/lib/services/social_service.dart b/apps/app_seeds/lib/services/social_service.dart index 87463de..2a44e13 100644 --- a/apps/app_seeds/lib/services/social_service.dart +++ b/apps/app_seeds/lib/services/social_service.dart @@ -39,20 +39,34 @@ class SocialService { /// Opens a session against [relayUrls]: one fault-tolerant pool carrying all /// three transports (offers, messaging, trust). Relays that are down are /// skipped; throws only when none are reachable. Caller closes it. - Future openSession(List relayUrls) async { + /// + /// [mediaServerUrl] (a Blossom endpoint) enables offer photos: when set, the + /// session exposes a [MediaTransport] to host images. It rides HTTP, not the + /// relay pool, so it's independent of relay reachability. + Future openSession( + List relayUrls, { + String? mediaServerUrl, + }) async { final pool = await RelayPool.connect(relayUrls, identity: identity); - return SocialSession(pool); + return SocialSession(pool, mediaServerUrl: mediaServerUrl); } } /// One relay channel with the three transports on top — the -/// "one channel, three interfaces" shape, at the app layer. +/// "one channel, three interfaces" shape, at the app layer. Media rides its own +/// HTTP endpoint (Blossom), so it's a fourth transport but not on the channel. class SocialSession { - SocialSession(this._channel) + SocialSession(this._channel, {String? mediaServerUrl}) : offers = NostrOfferTransport(_channel), messages = NostrMessageTransport(_channel), trust = NostrTrustTransport(_channel), - profile = NostrProfileTransport(_channel); + profile = NostrProfileTransport(_channel), + media = (mediaServerUrl != null && mediaServerUrl.trim().isNotEmpty) + ? BlossomMediaTransport( + Uri.parse(mediaServerUrl.trim()), + _channel.privateKeyHex, + ) + : null; final NostrChannel _channel; @@ -61,7 +75,14 @@ class SocialSession { final TrustTransport trust; final ProfileTransport profile; - Future close() => _channel.close(); + /// Hosts offer photos, or null when no media server is configured (offers then + /// publish without images). + final MediaTransport? media; + + Future close() async { + await media?.close(); + await _channel.close(); + } } Uint8List _hexToBytes(String hex) { diff --git a/apps/app_seeds/lib/services/social_settings.dart b/apps/app_seeds/lib/services/social_settings.dart index 6cdcb7a..78cb8d8 100644 --- a/apps/app_seeds/lib/services/social_settings.dart +++ b/apps/app_seeds/lib/services/social_settings.dart @@ -17,6 +17,7 @@ class SocialSettings { static const _areaKey = 'tane.social.area_geohash'; static const _relaysKey = 'tane.social.relays'; static const _searchPrecisionKey = 'tane.social.search_precision'; + static const _mediaServerKey = 'tane.social.media_server'; /// How wide "your zone" searches, as a geohash prefix length: 5 ≈ ±2.4 km /// ("very close"), 4 ≈ ±20 km ("around here"), 3 ≈ ±78 km ("my region"). @@ -39,6 +40,11 @@ class SocialSettings { 'wss://relay.primal.net', ]; + /// Blossom media server used to host offer photos so peers can see them. The + /// Comunes-run server is the non-commercial default; the user can point this + /// at any Blossom server, or clear it to publish offers without photos. + static const String defaultMediaServer = 'https://blossom.comunes.org'; + /// The user's coarse area as a low-precision geohash (may be empty). Set /// manually or from device location; the transport coarsens it further. Future areaGeohash() async => (await _store.read(_areaKey)) ?? ''; @@ -73,6 +79,18 @@ class SocialSettings { Future setSearchPrecision(int precision) => _store.write(_searchPrecisionKey, '${_clampPrecision(precision)}'); + /// The Blossom media server for offer photos. Falls back to + /// [defaultMediaServer] until the user configures one; an explicitly saved + /// empty value turns photo hosting off (offers still publish, without images). + Future mediaServerUrl() async { + final raw = await _store.read(_mediaServerKey); + if (raw == null) return defaultMediaServer; // never configured + return raw.trim(); + } + + Future setMediaServerUrl(String url) => + _store.write(_mediaServerKey, url.trim()); + int _clampPrecision(int p) => p < minSearchPrecision ? minSearchPrecision : (p > maxSearchPrecision ? maxSearchPrecision : p); diff --git a/apps/app_seeds/lib/state/offers_cubit.dart b/apps/app_seeds/lib/state/offers_cubit.dart index 021def8..4768328 100644 --- a/apps/app_seeds/lib/state/offers_cubit.dart +++ b/apps/app_seeds/lib/state/offers_cubit.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:typed_data'; import 'package:commons_core/commons_core.dart'; import 'package:equatable/equatable.dart'; @@ -134,12 +135,26 @@ class OffersState extends Equatable { /// UI stays offline-tolerant (a null transport = the social layer is unavailable /// and the screen degrades gracefully). class OffersCubit extends Cubit { - OffersCubit(this._transport, {Future Function()? onDispose}) - : _onDispose = onDispose, + OffersCubit( + this._transport, { + MediaTransport? media, + Future Function(String varietyId)? coverPhoto, + Future Function()? onDispose, + }) : _media = media, + _coverPhoto = coverPhoto, + _onDispose = onDispose, super(const OffersState()); final OfferTransport? _transport; + /// Hosts an offer's cover photo so peers can see it; null when no media server + /// is configured, in which case offers publish without images. + final MediaTransport? _media; + + /// Fetches a variety's cover photo bytes (for hosting); null in tests or when + /// no inventory repo is wired. + final Future Function(String varietyId)? _coverPhoto; + /// Closes the owning [SocialSession]/connection when the cubit is disposed /// (null in tests, where the transport is a fake with nothing to close). final Future Function()? _onDispose; @@ -269,6 +284,7 @@ class OffersCubit extends Cubit { areaGeohash: areaGeohash, category: lot.category, isOrganic: lot.isOrganic, + imageUrl: await _hostCoverPhoto(lot.varietyId), ); final result = await transport.publish(offer); if (result.accepted) accepted++; @@ -281,6 +297,23 @@ class OffersCubit extends Cubit { return accepted; } + /// Uploads the lot's cover photo to the media server and returns its URL, or + /// null when there's no media server, no photo, or the upload fails. Hosting + /// is best-effort: a missing image never blocks publishing the offer. + Future _hostCoverPhoto(String varietyId) async { + final media = _media; + final coverPhoto = _coverPhoto; + if (media == null || coverPhoto == null) return null; + try { + final Uint8List? bytes = await coverPhoto(varietyId); + if (bytes == null || bytes.isEmpty) return null; + final url = await media.upload(bytes, mimeType: 'image/jpeg'); + return url.toString(); + } catch (_) { + return null; // degrade: publish the offer without a photo + } + } + @override Future close() async { _searchTimeout?.cancel(); @@ -295,13 +328,21 @@ class OffersCubit extends Cubit { /// fails), the cubit is created with a null transport and the screen still opens. Future createOffersCubit( SocialService social, - SocialSettings settings, -) async { + SocialSettings settings, { + VarietyRepository? repository, +}) async { final relays = await settings.relayUrls(); if (relays.isEmpty) return OffersCubit(null); try { - final session = await social.openSession(relays); - return OffersCubit(session.offers, onDispose: session.close); + final mediaServer = await settings.mediaServerUrl(); + final session = + await social.openSession(relays, mediaServerUrl: mediaServer); + return OffersCubit( + session.offers, + media: session.media, + coverPhoto: repository?.coverPhotoFor, + onDispose: session.close, + ); } catch (_) { return OffersCubit(null); // offline / no relay reachable } diff --git a/apps/app_seeds/lib/ui/market_screen.dart b/apps/app_seeds/lib/ui/market_screen.dart index ef4a753..bee0e9f 100644 --- a/apps/app_seeds/lib/ui/market_screen.dart +++ b/apps/app_seeds/lib/ui/market_screen.dart @@ -58,7 +58,11 @@ class _MarketScreenState extends State { final repo = widget.outbox != null ? context.read() : null; setState(() => _loading = true); - final cubit = await createOffersCubit(widget.social, widget.settings); + final cubit = await createOffersCubit( + widget.social, + widget.settings, + repository: repo, + ); final area = await widget.settings.areaGeohash(); if (!mounted) { await cubit.close(); @@ -599,6 +603,7 @@ class _ConfigSheet extends StatefulWidget { class _ConfigSheetState extends State<_ConfigSheet> { final _area = TextEditingController(); final _servers = TextEditingController(); + final _mediaServer = TextEditingController(); bool _loading = true; bool _locationBusy = false; String? _locationError; @@ -613,6 +618,7 @@ class _ConfigSheetState extends State<_ConfigSheet> { Future _load() async { _area.text = await widget.settings.areaGeohash(); _servers.text = (await widget.settings.relayUrls()).join('\n'); + _mediaServer.text = await widget.settings.mediaServerUrl(); _precision = await widget.settings.searchPrecision(); if (mounted) setState(() => _loading = false); } @@ -620,6 +626,7 @@ class _ConfigSheetState extends State<_ConfigSheet> { Future _save() async { await widget.settings.setAreaGeohash(_area.text); await widget.settings.setRelayUrls(_servers.text.split('\n')); + await widget.settings.setMediaServerUrl(_mediaServer.text); await widget.settings.setSearchPrecision(_precision); if (mounted) Navigator.of(context).pop(true); } @@ -649,6 +656,7 @@ class _ConfigSheetState extends State<_ConfigSheet> { void dispose() { _area.dispose(); _servers.dispose(); + _mediaServer.dispose(); super.dispose(); } @@ -788,6 +796,16 @@ class _ConfigSheetState extends State<_ConfigSheet> { helperMaxLines: 2, ), ), + const SizedBox(height: 14), + TextField( + key: const Key('market.mediaServer'), + controller: _mediaServer, + decoration: InputDecoration( + labelText: t.market.mediaServerLabel, + helperText: t.market.mediaServerHelp, + helperMaxLines: 2, + ), + ), ], ), ), diff --git a/apps/app_seeds/test/services/social_settings_test.dart b/apps/app_seeds/test/services/social_settings_test.dart index e8c8673..7dd571e 100644 --- a/apps/app_seeds/test/services/social_settings_test.dart +++ b/apps/app_seeds/test/services/social_settings_test.dart @@ -27,6 +27,15 @@ void main() { expect(await settings.relayUrls(), isEmpty); }); + test('media server defaults, is configurable, and can be turned off', + () async { + expect(await settings.mediaServerUrl(), SocialSettings.defaultMediaServer); + await settings.setMediaServerUrl(' https://blossom.example '); + expect(await settings.mediaServerUrl(), 'https://blossom.example'); + await settings.setMediaServerUrl(''); // explicit empty = no photo hosting + expect(await settings.mediaServerUrl(), ''); + }); + test('stores and normalises the area geohash (trim + lowercase)', () async { await settings.setAreaGeohash(' SP3E9 '); expect(await settings.areaGeohash(), 'sp3e9'); diff --git a/apps/app_seeds/test/state/offers_cubit_test.dart b/apps/app_seeds/test/state/offers_cubit_test.dart index 2698c49..6545373 100644 --- a/apps/app_seeds/test/state/offers_cubit_test.dart +++ b/apps/app_seeds/test/state/offers_cubit_test.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:typed_data'; import 'package:commons_core/commons_core.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -40,6 +41,24 @@ class FakeOfferTransport implements OfferTransport { Future close() async {} } +/// In-memory [MediaTransport]: hands back a fixed URL, or throws when [fail] is +/// set (to prove the publish step degrades to no-image instead of erroring). +class FakeMediaTransport implements MediaTransport { + FakeMediaTransport({this.fail = false}); + final bool fail; + int uploads = 0; + + @override + Future upload(Uint8List bytes, {required String mimeType}) async { + uploads++; + if (fail) throw const MediaUploadException('boom', 500); + return Uri.parse('https://media.test/hosted.jpg'); + } + + @override + Future close() async {} +} + /// Emits every published offer TWICE on discover — the way a relay legitimately /// resends an addressable event (a stored copy plus a live echo). Used to prove /// the cubit dedups instead of doubling the listing. @@ -269,12 +288,14 @@ void main() { const [ ShareableLot( lotId: 'lot-1', + varietyId: 'var-1', summary: 'Tomate', offerStatus: OfferStatus.shared, category: 'Solanaceae', ), ShareableLot( lotId: 'lot-2', + varietyId: 'var-2', summary: 'Judía', offerStatus: OfferStatus.exchange, ), @@ -291,6 +312,85 @@ void main() { await cubit.close(); }); + test('publishLots hosts the cover photo and puts its URL on the offer', + () async { + final transport = FakeOfferTransport(); + final media = FakeMediaTransport(); + final cubit = OffersCubit( + transport, + media: media, + coverPhoto: (id) async => Uint8List.fromList([1, 2, 3]), + ); + await cubit.publishLots( + const [ + ShareableLot( + lotId: 'lot-1', + varietyId: 'var-1', + summary: 'Tomate', + offerStatus: OfferStatus.shared, + ), + ], + authorPubkeyHex: 'ab' * 32, + areaGeohash: 'sp3e9', + ); + + await cubit.discover('sp3'); + await pumpEventQueue(); + expect(media.uploads, 1); + expect(cubit.state.offers.single.imageUrl, 'https://media.test/hosted.jpg'); + await cubit.close(); + }); + + test('publishLots still publishes (without image) when hosting fails', + () async { + final transport = FakeOfferTransport(); + final cubit = OffersCubit( + transport, + media: FakeMediaTransport(fail: true), + coverPhoto: (id) async => Uint8List.fromList([1, 2, 3]), + ); + final count = await cubit.publishLots( + const [ + ShareableLot( + lotId: 'lot-1', + varietyId: 'var-1', + summary: 'Tomate', + offerStatus: OfferStatus.shared, + ), + ], + authorPubkeyHex: 'ab' * 32, + areaGeohash: 'sp3e9', + ); + + expect(count, 1); // the offer still went out + await cubit.discover('sp3'); + await pumpEventQueue(); + expect(cubit.state.offers.single.imageUrl, isNull); + await cubit.close(); + }); + + test('publishLots without a media server publishes no image', () async { + final transport = FakeOfferTransport(); + final cubit = OffersCubit(transport); // no media, no coverPhoto + await cubit.publishLots( + const [ + ShareableLot( + lotId: 'lot-1', + varietyId: 'var-1', + summary: 'Tomate', + offerStatus: OfferStatus.shared, + ), + ], + authorPubkeyHex: 'ab' * 32, + areaGeohash: 'sp3e9', + ); + + await cubit.discover('sp3'); + await pumpEventQueue(); + expect(cubit.state.offers.single.imageUrl, isNull); + await cubit.close(); + }); + test('publishLots is a no-op offline or with no area', () async { final offline = OffersCubit(null); expect( @@ -298,6 +398,7 @@ void main() { const [ ShareableLot( lotId: 'x', + varietyId: 'vx', summary: 'x', offerStatus: OfferStatus.shared, ), @@ -315,6 +416,7 @@ void main() { const [ ShareableLot( lotId: 'x', + varietyId: 'vx', summary: 'x', offerStatus: OfferStatus.shared, ), @@ -336,13 +438,20 @@ void main() { cubit: cubit, shareableLots: const [ ShareableLot( - lotId: 'lot-1', summary: 'Tomate', offerStatus: OfferStatus.shared), + lotId: 'lot-1', + varietyId: 'var-1', + summary: 'Tomate', + offerStatus: OfferStatus.shared), ShareableLot( lotId: 'lot-2', + varietyId: 'var-2', summary: 'Judía', offerStatus: OfferStatus.exchange), ShareableLot( - lotId: 'lot-3', summary: 'Otro', offerStatus: OfferStatus.shared), + lotId: 'lot-3', + varietyId: 'var-3', + summary: 'Otro', + offerStatus: OfferStatus.shared), ], authorPubkeyHex: 'ab' * 32, areaGeohash: 'sp3e9', diff --git a/packages/commons_core/test/social/nostr_transports_test.dart b/packages/commons_core/test/social/nostr_transports_test.dart index 4ba25cc..3ab4f8c 100644 --- a/packages/commons_core/test/social/nostr_transports_test.dart +++ b/packages/commons_core/test/social/nostr_transports_test.dart @@ -35,6 +35,7 @@ void main() { type: OfferType.gift, category: 'Solanaceae', approxGeohash: 'sp3e9xyz', + imageUrl: 'https://media.test/tomate.jpg', )); expect(published.accepted, isTrue, reason: published.message); @@ -43,6 +44,7 @@ void main() { expect(found, hasLength(1)); expect(found.single.summary, 'Tomate rosa de Barbastro'); expect(found.single.authorPubkeyHex, alice.publicKeyHex); + expect(found.single.imageUrl, 'https://media.test/tomate.jpg'); await aliceT.close(); await bobT.close(); From 9109581be06bb95831a68cc940b297598ddb2606 Mon Sep 17 00:00:00 2001 From: vjrj Date: Fri, 10 Jul 2026 21:27:59 +0200 Subject: [PATCH 4/4] feat(market): embed offer photos inline instead of a media server Replace the Blossom media-server approach with a fully decentralized one: generate a small (~320px) JPEG thumbnail from the lot's cover photo and embed it in the offer event as a data: URI, so photos ride the relays with no server and no IP leak. The full photo stays in the encrypted inventory. - offer_thumbnail.dart: downscale-until-it-fits data-URI builder + decoder - market_widgets: render data: URIs from memory, http(s) URLs from network - offers_cubit: publish a thumbnail (best-effort) in place of an upload - drop MediaTransport/Blossom from commons_core (http/crypto deps) and the media-server setting; parked on branch parked/offer-photos-blossom Relay event-size limits cap the image to a thumbnail; higher-res sharing would need the parked Blossom path. --- apps/app_seeds/lib/i18n/ast.i18n.json | 4 +- apps/app_seeds/lib/i18n/en.i18n.json | 4 +- apps/app_seeds/lib/i18n/es.i18n.json | 4 +- apps/app_seeds/lib/i18n/pt.i18n.json | 4 +- apps/app_seeds/lib/i18n/strings.g.dart | 4 +- apps/app_seeds/lib/i18n/strings_ast.g.dart | 4 - apps/app_seeds/lib/i18n/strings_en.g.dart | 8 -- apps/app_seeds/lib/i18n/strings_es.g.dart | 4 - apps/app_seeds/lib/i18n/strings_pt.g.dart | 4 - .../lib/services/offer_thumbnail.dart | 56 +++++++++ .../lib/services/social_service.dart | 33 +---- .../lib/services/social_settings.dart | 18 --- apps/app_seeds/lib/state/offers_cubit.dart | 42 +++---- apps/app_seeds/lib/ui/market_screen.dart | 14 --- apps/app_seeds/lib/ui/market_widgets.dart | 79 +++++++----- .../test/services/offer_thumbnail_test.dart | 61 ++++++++++ .../test/services/social_settings_test.dart | 9 -- .../test/state/offers_cubit_test.dart | 39 ++---- .../test/ui/market_widgets_test.dart | 17 +++ packages/commons_core/lib/commons_core.dart | 2 - .../lib/src/social/media_transport.dart | 22 ---- .../social/nostr/blossom_media_transport.dart | 114 ------------------ packages/commons_core/pubspec.yaml | 5 - .../social/blossom_media_transport_test.dart | 90 -------------- 24 files changed, 230 insertions(+), 411 deletions(-) create mode 100644 apps/app_seeds/lib/services/offer_thumbnail.dart create mode 100644 apps/app_seeds/test/services/offer_thumbnail_test.dart delete mode 100644 packages/commons_core/lib/src/social/media_transport.dart delete mode 100644 packages/commons_core/lib/src/social/nostr/blossom_media_transport.dart delete mode 100644 packages/commons_core/test/social/blossom_media_transport_test.dart diff --git a/apps/app_seeds/lib/i18n/ast.i18n.json b/apps/app_seeds/lib/i18n/ast.i18n.json index 4fc4cec..31dd7a0 100644 --- a/apps/app_seeds/lib/i18n/ast.i18n.json +++ b/apps/app_seeds/lib/i18n/ast.i18n.json @@ -483,9 +483,7 @@ "noProfile": "Esta persona entá nun compartió'l so perfil", "copyId": "Copiar códigu", "idCopied": "Códigu copiáu", - "photo": "Semeya", - "mediaServerLabel": "Sirvidor de semeyes", - "mediaServerHelp": "Ónde s'agospien les semeyes de les ufiertes pa que otres persones les vean. Déxalo baleru pa compartir ensin semeyes." + "photo": "Semeya" }, "profile": { "title": "El to perfil", diff --git a/apps/app_seeds/lib/i18n/en.i18n.json b/apps/app_seeds/lib/i18n/en.i18n.json index e663b1a..a746708 100644 --- a/apps/app_seeds/lib/i18n/en.i18n.json +++ b/apps/app_seeds/lib/i18n/en.i18n.json @@ -486,9 +486,7 @@ "noProfile": "This person hasn't shared a profile yet", "copyId": "Copy code", "idCopied": "Code copied", - "photo": "Photo", - "mediaServerLabel": "Photo server", - "mediaServerHelp": "Where offer photos are hosted so others can see them. Leave empty to share without photos." + "photo": "Photo" }, "profile": { "title": "Your profile", diff --git a/apps/app_seeds/lib/i18n/es.i18n.json b/apps/app_seeds/lib/i18n/es.i18n.json index 32c1257..0f1e1a6 100644 --- a/apps/app_seeds/lib/i18n/es.i18n.json +++ b/apps/app_seeds/lib/i18n/es.i18n.json @@ -485,9 +485,7 @@ "noProfile": "Esta persona aún no ha compartido su perfil", "copyId": "Copiar código", "idCopied": "Código copiado", - "photo": "Foto", - "mediaServerLabel": "Servidor de fotos", - "mediaServerHelp": "Dónde se alojan las fotos de las ofertas para que otras personas las vean. Déjalo vacío para compartir sin fotos." + "photo": "Foto" }, "profile": { "title": "Tu perfil", diff --git a/apps/app_seeds/lib/i18n/pt.i18n.json b/apps/app_seeds/lib/i18n/pt.i18n.json index e8fb01d..72a30db 100644 --- a/apps/app_seeds/lib/i18n/pt.i18n.json +++ b/apps/app_seeds/lib/i18n/pt.i18n.json @@ -482,9 +482,7 @@ "noProfile": "Esta pessoa ainda não partilhou o seu perfil", "copyId": "Copiar código", "idCopied": "Código copiado", - "photo": "Foto", - "mediaServerLabel": "Servidor de fotos", - "mediaServerHelp": "Onde as fotos das ofertas ficam alojadas para que outras pessoas as vejam. Deixe vazio para partilhar sem fotos." + "photo": "Foto" }, "profile": { "title": "O teu perfil", diff --git a/apps/app_seeds/lib/i18n/strings.g.dart b/apps/app_seeds/lib/i18n/strings.g.dart index c65da8b..e5d9a61 100644 --- a/apps/app_seeds/lib/i18n/strings.g.dart +++ b/apps/app_seeds/lib/i18n/strings.g.dart @@ -4,9 +4,9 @@ /// To regenerate, run: `dart run slang` /// /// Locales: 4 -/// Strings: 1560 (390 per locale) +/// Strings: 1552 (388 per locale) /// -/// Built on 2026-07-10 at 19:08 UTC +/// Built on 2026-07-10 at 19:23 UTC // coverage:ignore-file // ignore_for_file: type=lint, unused_import diff --git a/apps/app_seeds/lib/i18n/strings_ast.g.dart b/apps/app_seeds/lib/i18n/strings_ast.g.dart index 1c8c3f6..1d7ac78 100644 --- a/apps/app_seeds/lib/i18n/strings_ast.g.dart +++ b/apps/app_seeds/lib/i18n/strings_ast.g.dart @@ -692,8 +692,6 @@ class _Translations$market$ast extends Translations$market$en { @override String get copyId => 'Copiar códigu'; @override String get idCopied => 'Códigu copiáu'; @override String get photo => 'Semeya'; - @override String get mediaServerLabel => 'Sirvidor de semeyes'; - @override String get mediaServerHelp => 'Ónde s\'agospien les semeyes de les ufiertes pa que otres persones les vean. Déxalo baleru pa compartir ensin semeyes.'; } // Path: profile @@ -1460,8 +1458,6 @@ extension on TranslationsAst { 'market.copyId' => 'Copiar códigu', 'market.idCopied' => 'Códigu copiáu', 'market.photo' => 'Semeya', - 'market.mediaServerLabel' => 'Sirvidor de semeyes', - 'market.mediaServerHelp' => 'Ónde s\'agospien les semeyes de les ufiertes pa que otres persones les vean. Déxalo baleru pa compartir ensin semeyes.', 'profile.title' => 'El to perfil', 'profile.name' => 'Nome', 'profile.nameHint' => 'Cómo te ven los demás', diff --git a/apps/app_seeds/lib/i18n/strings_en.g.dart b/apps/app_seeds/lib/i18n/strings_en.g.dart index 47e7b21..9ca3bab 100644 --- a/apps/app_seeds/lib/i18n/strings_en.g.dart +++ b/apps/app_seeds/lib/i18n/strings_en.g.dart @@ -1285,12 +1285,6 @@ class Translations$market$en { /// en: 'Photo' String get photo => 'Photo'; - - /// en: 'Photo server' - String get mediaServerLabel => 'Photo server'; - - /// en: 'Where offer photos are hosted so others can see them. Leave empty to share without photos.' - String get mediaServerHelp => 'Where offer photos are hosted so others can see them. Leave empty to share without photos.'; } // Path: profile @@ -2230,8 +2224,6 @@ extension on Translations { 'market.copyId' => 'Copy code', 'market.idCopied' => 'Code copied', 'market.photo' => 'Photo', - 'market.mediaServerLabel' => 'Photo server', - 'market.mediaServerHelp' => 'Where offer photos are hosted so others can see them. Leave empty to share without photos.', 'profile.title' => 'Your profile', 'profile.name' => 'Display name', 'profile.nameHint' => 'How others see you', diff --git a/apps/app_seeds/lib/i18n/strings_es.g.dart b/apps/app_seeds/lib/i18n/strings_es.g.dart index c1062a8..797f3a6 100644 --- a/apps/app_seeds/lib/i18n/strings_es.g.dart +++ b/apps/app_seeds/lib/i18n/strings_es.g.dart @@ -694,8 +694,6 @@ class _Translations$market$es extends Translations$market$en { @override String get copyId => 'Copiar código'; @override String get idCopied => 'Código copiado'; @override String get photo => 'Foto'; - @override String get mediaServerLabel => 'Servidor de fotos'; - @override String get mediaServerHelp => 'Dónde se alojan las fotos de las ofertas para que otras personas las vean. Déjalo vacío para compartir sin fotos.'; } // Path: profile @@ -1464,8 +1462,6 @@ extension on TranslationsEs { 'market.copyId' => 'Copiar código', 'market.idCopied' => 'Código copiado', 'market.photo' => 'Foto', - 'market.mediaServerLabel' => 'Servidor de fotos', - 'market.mediaServerHelp' => 'Dónde se alojan las fotos de las ofertas para que otras personas las vean. Déjalo vacío para compartir sin fotos.', 'profile.title' => 'Tu perfil', 'profile.name' => 'Nombre', 'profile.nameHint' => 'Cómo te ven los demás', diff --git a/apps/app_seeds/lib/i18n/strings_pt.g.dart b/apps/app_seeds/lib/i18n/strings_pt.g.dart index 46e92de..f74354e 100644 --- a/apps/app_seeds/lib/i18n/strings_pt.g.dart +++ b/apps/app_seeds/lib/i18n/strings_pt.g.dart @@ -691,8 +691,6 @@ class _Translations$market$pt extends Translations$market$en { @override String get copyId => 'Copiar código'; @override String get idCopied => 'Código copiado'; @override String get photo => 'Foto'; - @override String get mediaServerLabel => 'Servidor de fotos'; - @override String get mediaServerHelp => 'Onde as fotos das ofertas ficam alojadas para que outras pessoas as vejam. Deixe vazio para partilhar sem fotos.'; } // Path: profile @@ -1458,8 +1456,6 @@ extension on TranslationsPt { 'market.copyId' => 'Copiar código', 'market.idCopied' => 'Código copiado', 'market.photo' => 'Foto', - 'market.mediaServerLabel' => 'Servidor de fotos', - 'market.mediaServerHelp' => 'Onde as fotos das ofertas ficam alojadas para que outras pessoas as vejam. Deixe vazio para partilhar sem fotos.', 'profile.title' => 'O teu perfil', 'profile.name' => 'Nome', 'profile.nameHint' => 'Como os outros te veem', diff --git a/apps/app_seeds/lib/services/offer_thumbnail.dart b/apps/app_seeds/lib/services/offer_thumbnail.dart new file mode 100644 index 0000000..81e756a --- /dev/null +++ b/apps/app_seeds/lib/services/offer_thumbnail.dart @@ -0,0 +1,56 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:image/image.dart' as img; + +/// Builds a tiny `data:image/jpeg;base64,…` thumbnail from a full photo, small +/// enough to ride *inside* a Nostr offer event — no media server, fully +/// decentralized. The full-resolution photo stays in the encrypted local +/// inventory; only this shrunken preview is published so peers can see the seed. +/// +/// Relays cap event size, so we downscale (longest edge) and re-encode until the +/// base64 fits under [maxBytes]. Returns null when the bytes aren't a decodable +/// image or no size small enough is reachable — the offer then publishes without +/// a photo (graceful, never a hard failure). +String? offerThumbnailDataUri( + Uint8List bytes, { + int maxBytes = 40000, + List edges = const [320, 256, 192, 128], + int quality = 68, +}) { + try { + final decoded = img.decodeImage(bytes); + if (decoded == null) return null; + + for (final edge in edges) { + final resized = _fitWithin(decoded, edge); + final jpeg = img.encodeJpg(resized, quality: quality); + final b64 = base64.encode(jpeg); + if (b64.length <= maxBytes) return 'data:image/jpeg;base64,$b64'; + } + return null; // even the smallest edge didn't fit — skip the image + } catch (_) { + return null; // undecodable/corrupt bytes — publish without a photo + } +} + +/// Extracts the raw bytes from a `data:...;base64,…` URI, or null when [uri] is +/// not a base64 data URI. Used by the UI to render an inline thumbnail with +/// `Image.memory` instead of a network fetch. +Uint8List? decodeDataUri(String uri) { + if (!uri.startsWith('data:')) return null; + try { + return Uri.parse(uri).data?.contentAsBytes(); + } on FormatException { + return null; + } +} + +/// Resizes [image] so its longest edge is at most [edge], preserving aspect +/// ratio. Never upscales a photo that's already smaller. +img.Image _fitWithin(img.Image image, int edge) { + if (image.width <= edge && image.height <= edge) return image; + return image.width >= image.height + ? img.copyResize(image, width: edge) + : img.copyResize(image, height: edge); +} diff --git a/apps/app_seeds/lib/services/social_service.dart b/apps/app_seeds/lib/services/social_service.dart index 2a44e13..87463de 100644 --- a/apps/app_seeds/lib/services/social_service.dart +++ b/apps/app_seeds/lib/services/social_service.dart @@ -39,34 +39,20 @@ class SocialService { /// Opens a session against [relayUrls]: one fault-tolerant pool carrying all /// three transports (offers, messaging, trust). Relays that are down are /// skipped; throws only when none are reachable. Caller closes it. - /// - /// [mediaServerUrl] (a Blossom endpoint) enables offer photos: when set, the - /// session exposes a [MediaTransport] to host images. It rides HTTP, not the - /// relay pool, so it's independent of relay reachability. - Future openSession( - List relayUrls, { - String? mediaServerUrl, - }) async { + Future openSession(List relayUrls) async { final pool = await RelayPool.connect(relayUrls, identity: identity); - return SocialSession(pool, mediaServerUrl: mediaServerUrl); + return SocialSession(pool); } } /// One relay channel with the three transports on top — the -/// "one channel, three interfaces" shape, at the app layer. Media rides its own -/// HTTP endpoint (Blossom), so it's a fourth transport but not on the channel. +/// "one channel, three interfaces" shape, at the app layer. class SocialSession { - SocialSession(this._channel, {String? mediaServerUrl}) + SocialSession(this._channel) : offers = NostrOfferTransport(_channel), messages = NostrMessageTransport(_channel), trust = NostrTrustTransport(_channel), - profile = NostrProfileTransport(_channel), - media = (mediaServerUrl != null && mediaServerUrl.trim().isNotEmpty) - ? BlossomMediaTransport( - Uri.parse(mediaServerUrl.trim()), - _channel.privateKeyHex, - ) - : null; + profile = NostrProfileTransport(_channel); final NostrChannel _channel; @@ -75,14 +61,7 @@ class SocialSession { final TrustTransport trust; final ProfileTransport profile; - /// Hosts offer photos, or null when no media server is configured (offers then - /// publish without images). - final MediaTransport? media; - - Future close() async { - await media?.close(); - await _channel.close(); - } + Future close() => _channel.close(); } Uint8List _hexToBytes(String hex) { diff --git a/apps/app_seeds/lib/services/social_settings.dart b/apps/app_seeds/lib/services/social_settings.dart index 78cb8d8..6cdcb7a 100644 --- a/apps/app_seeds/lib/services/social_settings.dart +++ b/apps/app_seeds/lib/services/social_settings.dart @@ -17,7 +17,6 @@ class SocialSettings { static const _areaKey = 'tane.social.area_geohash'; static const _relaysKey = 'tane.social.relays'; static const _searchPrecisionKey = 'tane.social.search_precision'; - static const _mediaServerKey = 'tane.social.media_server'; /// How wide "your zone" searches, as a geohash prefix length: 5 ≈ ±2.4 km /// ("very close"), 4 ≈ ±20 km ("around here"), 3 ≈ ±78 km ("my region"). @@ -40,11 +39,6 @@ class SocialSettings { 'wss://relay.primal.net', ]; - /// Blossom media server used to host offer photos so peers can see them. The - /// Comunes-run server is the non-commercial default; the user can point this - /// at any Blossom server, or clear it to publish offers without photos. - static const String defaultMediaServer = 'https://blossom.comunes.org'; - /// The user's coarse area as a low-precision geohash (may be empty). Set /// manually or from device location; the transport coarsens it further. Future areaGeohash() async => (await _store.read(_areaKey)) ?? ''; @@ -79,18 +73,6 @@ class SocialSettings { Future setSearchPrecision(int precision) => _store.write(_searchPrecisionKey, '${_clampPrecision(precision)}'); - /// The Blossom media server for offer photos. Falls back to - /// [defaultMediaServer] until the user configures one; an explicitly saved - /// empty value turns photo hosting off (offers still publish, without images). - Future mediaServerUrl() async { - final raw = await _store.read(_mediaServerKey); - if (raw == null) return defaultMediaServer; // never configured - return raw.trim(); - } - - Future setMediaServerUrl(String url) => - _store.write(_mediaServerKey, url.trim()); - int _clampPrecision(int p) => p < minSearchPrecision ? minSearchPrecision : (p > maxSearchPrecision ? maxSearchPrecision : p); diff --git a/apps/app_seeds/lib/state/offers_cubit.dart b/apps/app_seeds/lib/state/offers_cubit.dart index 4768328..c312571 100644 --- a/apps/app_seeds/lib/state/offers_cubit.dart +++ b/apps/app_seeds/lib/state/offers_cubit.dart @@ -8,6 +8,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import '../data/variety_repository.dart'; import '../services/offer_mapper.dart'; import '../services/offer_outbox.dart'; +import '../services/offer_thumbnail.dart'; import '../services/social_service.dart'; import '../services/social_settings.dart'; @@ -137,24 +138,24 @@ class OffersState extends Equatable { class OffersCubit extends Cubit { OffersCubit( this._transport, { - MediaTransport? media, Future Function(String varietyId)? coverPhoto, + String? Function(Uint8List bytes)? thumbnail, Future Function()? onDispose, - }) : _media = media, - _coverPhoto = coverPhoto, + }) : _coverPhoto = coverPhoto, + _thumbnail = thumbnail, _onDispose = onDispose, super(const OffersState()); final OfferTransport? _transport; - /// Hosts an offer's cover photo so peers can see it; null when no media server - /// is configured, in which case offers publish without images. - final MediaTransport? _media; - - /// Fetches a variety's cover photo bytes (for hosting); null in tests or when - /// no inventory repo is wired. + /// Fetches a variety's cover photo bytes; null in tests or when no inventory + /// repo is wired. final Future Function(String varietyId)? _coverPhoto; + /// Turns full photo bytes into a small `data:` thumbnail embedded in the offer + /// (no media server). Null → offers publish without a photo. + final String? Function(Uint8List bytes)? _thumbnail; + /// Closes the owning [SocialSession]/connection when the cubit is disposed /// (null in tests, where the transport is a fake with nothing to close). final Future Function()? _onDispose; @@ -284,7 +285,7 @@ class OffersCubit extends Cubit { areaGeohash: areaGeohash, category: lot.category, isOrganic: lot.isOrganic, - imageUrl: await _hostCoverPhoto(lot.varietyId), + imageUrl: await _coverThumbnail(lot.varietyId), ); final result = await transport.publish(offer); if (result.accepted) accepted++; @@ -297,18 +298,17 @@ class OffersCubit extends Cubit { return accepted; } - /// Uploads the lot's cover photo to the media server and returns its URL, or - /// null when there's no media server, no photo, or the upload fails. Hosting - /// is best-effort: a missing image never blocks publishing the offer. - Future _hostCoverPhoto(String varietyId) async { - final media = _media; + /// Builds a small inline `data:` thumbnail from the lot's cover photo to embed + /// in the offer, or null when there's no photo, no thumbnailer, or it can't be + /// shrunk to fit. Best-effort: a missing image never blocks publishing. + Future _coverThumbnail(String varietyId) async { final coverPhoto = _coverPhoto; - if (media == null || coverPhoto == null) return null; + final thumbnail = _thumbnail; + if (coverPhoto == null || thumbnail == null) return null; try { final Uint8List? bytes = await coverPhoto(varietyId); if (bytes == null || bytes.isEmpty) return null; - final url = await media.upload(bytes, mimeType: 'image/jpeg'); - return url.toString(); + return thumbnail(bytes); } catch (_) { return null; // degrade: publish the offer without a photo } @@ -334,13 +334,11 @@ Future createOffersCubit( final relays = await settings.relayUrls(); if (relays.isEmpty) return OffersCubit(null); try { - final mediaServer = await settings.mediaServerUrl(); - final session = - await social.openSession(relays, mediaServerUrl: mediaServer); + final session = await social.openSession(relays); return OffersCubit( session.offers, - media: session.media, coverPhoto: repository?.coverPhotoFor, + thumbnail: offerThumbnailDataUri, onDispose: session.close, ); } catch (_) { diff --git a/apps/app_seeds/lib/ui/market_screen.dart b/apps/app_seeds/lib/ui/market_screen.dart index bee0e9f..a919286 100644 --- a/apps/app_seeds/lib/ui/market_screen.dart +++ b/apps/app_seeds/lib/ui/market_screen.dart @@ -603,7 +603,6 @@ class _ConfigSheet extends StatefulWidget { class _ConfigSheetState extends State<_ConfigSheet> { final _area = TextEditingController(); final _servers = TextEditingController(); - final _mediaServer = TextEditingController(); bool _loading = true; bool _locationBusy = false; String? _locationError; @@ -618,7 +617,6 @@ class _ConfigSheetState extends State<_ConfigSheet> { Future _load() async { _area.text = await widget.settings.areaGeohash(); _servers.text = (await widget.settings.relayUrls()).join('\n'); - _mediaServer.text = await widget.settings.mediaServerUrl(); _precision = await widget.settings.searchPrecision(); if (mounted) setState(() => _loading = false); } @@ -626,7 +624,6 @@ class _ConfigSheetState extends State<_ConfigSheet> { Future _save() async { await widget.settings.setAreaGeohash(_area.text); await widget.settings.setRelayUrls(_servers.text.split('\n')); - await widget.settings.setMediaServerUrl(_mediaServer.text); await widget.settings.setSearchPrecision(_precision); if (mounted) Navigator.of(context).pop(true); } @@ -656,7 +653,6 @@ class _ConfigSheetState extends State<_ConfigSheet> { void dispose() { _area.dispose(); _servers.dispose(); - _mediaServer.dispose(); super.dispose(); } @@ -796,16 +792,6 @@ class _ConfigSheetState extends State<_ConfigSheet> { helperMaxLines: 2, ), ), - const SizedBox(height: 14), - TextField( - key: const Key('market.mediaServer'), - controller: _mediaServer, - decoration: InputDecoration( - labelText: t.market.mediaServerLabel, - helperText: t.market.mediaServerHelp, - helperMaxLines: 2, - ), - ), ], ), ), diff --git a/apps/app_seeds/lib/ui/market_widgets.dart b/apps/app_seeds/lib/ui/market_widgets.dart index b743ada..20c9f31 100644 --- a/apps/app_seeds/lib/ui/market_widgets.dart +++ b/apps/app_seeds/lib/ui/market_widgets.dart @@ -2,6 +2,7 @@ import 'package:commons_core/commons_core.dart'; import 'package:flutter/material.dart'; import '../i18n/strings.g.dart'; +import '../services/offer_thumbnail.dart'; import 'theme.dart'; /// Human words for an offer's reciprocity mode. Shared by the market list and @@ -15,8 +16,9 @@ String offerTypeLabel(Translations t, OfferType type) => switch (type) { }; /// A small square thumbnail of an offer's photo for the market list card. -/// Remote (published) image, so it degrades gracefully: a spinner while it -/// loads and a neutral placeholder when the media server can't be reached. +/// The image usually rides inline in the offer as a `data:` URI (decentralized, +/// no server), so it renders straight from memory; an `http(s)` URL is still +/// supported for interop and degrades gracefully (spinner, then placeholder). class OfferThumbnail extends StatelessWidget { const OfferThumbnail({ required this.url, @@ -33,23 +35,18 @@ class OfferThumbnail extends StatelessWidget { Widget build(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.circular(10), - child: Image.network( + child: _offerImage( url, + semanticLabel: semanticLabel, width: size, height: size, - fit: BoxFit.cover, - semanticLabel: semanticLabel, - loadingBuilder: (context, child, progress) => progress == null - ? child - : _OfferImagePlaceholder(size: size, loading: true), - errorBuilder: (context, _, _) => _OfferImagePlaceholder(size: size), ), ); } } -/// Full-width "hero" image atop the offer detail page. Same graceful -/// degradation as [OfferThumbnail]; hidden entirely when the offer has no photo. +/// Full-width "hero" image atop the offer detail page. Same source handling as +/// [OfferThumbnail]; hidden entirely when the offer has no photo. class OfferHeroImage extends StatelessWidget { const OfferHeroImage({ required this.url, @@ -66,33 +63,61 @@ class OfferHeroImage extends StatelessWidget { borderRadius: BorderRadius.circular(14), child: AspectRatio( aspectRatio: 4 / 3, - child: Image.network( - url, - fit: BoxFit.cover, - semanticLabel: semanticLabel, - loadingBuilder: (context, child, progress) => progress == null - ? child - : const _OfferImagePlaceholder(loading: true), - errorBuilder: (context, _, _) => const _OfferImagePlaceholder(), - ), + child: _offerImage(url, semanticLabel: semanticLabel), ), ); } } -/// Neutral fill shown while a remote offer image loads or when it can't be -/// fetched — a marketplace is useless if a broken image blocks the card. -class _OfferImagePlaceholder extends StatelessWidget { - const _OfferImagePlaceholder({this.size, this.loading = false}); +/// Renders an offer image from either an inline `data:` URI (via memory) or a +/// remote URL (via network), always cropping to fill and falling back to a +/// neutral placeholder — a broken image must never block the card. +Widget _offerImage( + String url, { + required String semanticLabel, + double? width, + double? height, +}) { + final inline = decodeDataUri(url); + if (inline != null) { + return Image.memory( + inline, + width: width, + height: height, + fit: BoxFit.cover, + semanticLabel: semanticLabel, + errorBuilder: (context, _, _) => + _OfferImagePlaceholder(width: width, height: height), + ); + } + return Image.network( + url, + width: width, + height: height, + fit: BoxFit.cover, + semanticLabel: semanticLabel, + loadingBuilder: (context, child, progress) => progress == null + ? child + : _OfferImagePlaceholder(width: width, height: height, loading: true), + errorBuilder: (context, _, _) => + _OfferImagePlaceholder(width: width, height: height), + ); +} - final double? size; +/// Neutral fill shown while a remote offer image loads or when it can't be +/// decoded/fetched — a marketplace is useless if a broken image blocks the card. +class _OfferImagePlaceholder extends StatelessWidget { + const _OfferImagePlaceholder({this.width, this.height, this.loading = false}); + + final double? width; + final double? height; final bool loading; @override Widget build(BuildContext context) { return Container( - width: size, - height: size, + width: width, + height: height, color: seedPrimaryContainer.withValues(alpha: 0.4), alignment: Alignment.center, child: loading diff --git a/apps/app_seeds/test/services/offer_thumbnail_test.dart b/apps/app_seeds/test/services/offer_thumbnail_test.dart new file mode 100644 index 0000000..a0e9530 --- /dev/null +++ b/apps/app_seeds/test/services/offer_thumbnail_test.dart @@ -0,0 +1,61 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:image/image.dart' as img; +import 'package:tane/services/offer_thumbnail.dart'; + +void main() { + /// A real, decodable photo far bigger than a thumbnail, with varied pixels so + /// JPEG can't compress it to nothing. + Uint8List bigPhoto() { + final image = img.Image(width: 1280, height: 960); + for (var y = 0; y < image.height; y++) { + for (var x = 0; x < image.width; x++) { + image.setPixelRgb(x, y, (x * 7) % 256, (y * 5) % 256, (x + y) % 256); + } + } + return img.encodeJpg(image, quality: 90); + } + + test('produces a small jpeg data-URI that fits the byte budget', () { + final uri = offerThumbnailDataUri(bigPhoto(), maxBytes: 40000); + + expect(uri, isNotNull); + expect(uri!, startsWith('data:image/jpeg;base64,')); + final b64 = uri.substring('data:image/jpeg;base64,'.length); + expect(b64.length, lessThanOrEqualTo(40000)); + + // The payload really is a smaller image than the source. + final decoded = img.decodeJpg(base64.decode(b64))!; + expect(decoded.width, lessThanOrEqualTo(320)); + expect(decoded.height, lessThanOrEqualTo(320)); + }); + + test('never upscales an already-tiny image', () { + final small = img.encodeJpg(img.Image(width: 64, height: 48), quality: 80); + final uri = offerThumbnailDataUri(small); + + expect(uri, isNotNull); + final b64 = uri!.substring('data:image/jpeg;base64,'.length); + final decoded = img.decodeJpg(base64.decode(b64))!; + expect(decoded.width, 64); + expect(decoded.height, 48); + }); + + test('returns null for bytes that are not an image', () { + expect(offerThumbnailDataUri(Uint8List.fromList([1, 2, 3, 4])), isNull); + }); + + group('decodeDataUri', () { + test('round-trips a base64 data URI to its bytes', () { + final bytes = Uint8List.fromList([9, 8, 7, 6]); + final uri = 'data:image/jpeg;base64,${base64.encode(bytes)}'; + expect(decodeDataUri(uri), bytes); + }); + + test('returns null for a plain http url', () { + expect(decodeDataUri('https://example.org/a.jpg'), isNull); + }); + }); +} diff --git a/apps/app_seeds/test/services/social_settings_test.dart b/apps/app_seeds/test/services/social_settings_test.dart index 7dd571e..e8c8673 100644 --- a/apps/app_seeds/test/services/social_settings_test.dart +++ b/apps/app_seeds/test/services/social_settings_test.dart @@ -27,15 +27,6 @@ void main() { expect(await settings.relayUrls(), isEmpty); }); - test('media server defaults, is configurable, and can be turned off', - () async { - expect(await settings.mediaServerUrl(), SocialSettings.defaultMediaServer); - await settings.setMediaServerUrl(' https://blossom.example '); - expect(await settings.mediaServerUrl(), 'https://blossom.example'); - await settings.setMediaServerUrl(''); // explicit empty = no photo hosting - expect(await settings.mediaServerUrl(), ''); - }); - test('stores and normalises the area geohash (trim + lowercase)', () async { await settings.setAreaGeohash(' SP3E9 '); expect(await settings.areaGeohash(), 'sp3e9'); diff --git a/apps/app_seeds/test/state/offers_cubit_test.dart b/apps/app_seeds/test/state/offers_cubit_test.dart index 6545373..ce8a3f1 100644 --- a/apps/app_seeds/test/state/offers_cubit_test.dart +++ b/apps/app_seeds/test/state/offers_cubit_test.dart @@ -41,24 +41,6 @@ class FakeOfferTransport implements OfferTransport { Future close() async {} } -/// In-memory [MediaTransport]: hands back a fixed URL, or throws when [fail] is -/// set (to prove the publish step degrades to no-image instead of erroring). -class FakeMediaTransport implements MediaTransport { - FakeMediaTransport({this.fail = false}); - final bool fail; - int uploads = 0; - - @override - Future upload(Uint8List bytes, {required String mimeType}) async { - uploads++; - if (fail) throw const MediaUploadException('boom', 500); - return Uri.parse('https://media.test/hosted.jpg'); - } - - @override - Future close() async {} -} - /// Emits every published offer TWICE on discover — the way a relay legitimately /// resends an addressable event (a stored copy plus a live echo). Used to prove /// the cubit dedups instead of doubling the listing. @@ -312,14 +294,17 @@ void main() { await cubit.close(); }); - test('publishLots hosts the cover photo and puts its URL on the offer', + test('publishLots embeds an inline thumbnail data-URI on the offer', () async { final transport = FakeOfferTransport(); - final media = FakeMediaTransport(); + var thumbnailed = 0; final cubit = OffersCubit( transport, - media: media, coverPhoto: (id) async => Uint8List.fromList([1, 2, 3]), + thumbnail: (bytes) { + thumbnailed++; + return 'data:image/jpeg;base64,AAAA'; + }, ); await cubit.publishLots( const [ @@ -336,18 +321,18 @@ void main() { await cubit.discover('sp3'); await pumpEventQueue(); - expect(media.uploads, 1); - expect(cubit.state.offers.single.imageUrl, 'https://media.test/hosted.jpg'); + expect(thumbnailed, 1); + expect(cubit.state.offers.single.imageUrl, 'data:image/jpeg;base64,AAAA'); await cubit.close(); }); - test('publishLots still publishes (without image) when hosting fails', + test('publishLots still publishes (without image) when thumbnailing fails', () async { final transport = FakeOfferTransport(); final cubit = OffersCubit( transport, - media: FakeMediaTransport(fail: true), coverPhoto: (id) async => Uint8List.fromList([1, 2, 3]), + thumbnail: (bytes) => throw Exception('boom'), ); final count = await cubit.publishLots( const [ @@ -369,9 +354,9 @@ void main() { await cubit.close(); }); - test('publishLots without a media server publishes no image', () async { + test('publishLots without a thumbnailer publishes no image', () async { final transport = FakeOfferTransport(); - final cubit = OffersCubit(transport); // no media, no coverPhoto + final cubit = OffersCubit(transport); // no thumbnail, no coverPhoto await cubit.publishLots( const [ ShareableLot( diff --git a/apps/app_seeds/test/ui/market_widgets_test.dart b/apps/app_seeds/test/ui/market_widgets_test.dart index 1108049..7a57f23 100644 --- a/apps/app_seeds/test/ui/market_widgets_test.dart +++ b/apps/app_seeds/test/ui/market_widgets_test.dart @@ -4,7 +4,24 @@ import 'package:tane/ui/market_widgets.dart'; Widget _wrap(Widget child) => MaterialApp(home: Scaffold(body: Center(child: child))); +/// A 1×1 PNG as an inline data URI — the shape offers actually publish. +const _dataUri = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lE' + 'QVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='; + void main() { + testWidgets('OfferThumbnail renders an inline data-URI from memory', + (tester) async { + await tester.pumpWidget( + _wrap(const OfferThumbnail(url: _dataUri, semanticLabel: 'Photo')), + ); + await tester.pump(); + + expect(find.byType(Image), findsOneWidget); + // Decoded fine — no broken-image placeholder. + expect(find.byIcon(Icons.image_not_supported_outlined), findsNothing); + }); + testWidgets('OfferThumbnail builds a network image', (tester) async { await tester.pumpWidget( _wrap(const OfferThumbnail( diff --git a/packages/commons_core/lib/commons_core.dart b/packages/commons_core/lib/commons_core.dart index e3e713b..515a513 100644 --- a/packages/commons_core/lib/commons_core.dart +++ b/packages/commons_core/lib/commons_core.dart @@ -13,9 +13,7 @@ export 'src/identity/nostr_key_derivation.dart'; export 'src/ids/id_gen.dart'; export 'src/social/certification.dart'; export 'src/social/geohash.dart'; -export 'src/social/media_transport.dart'; export 'src/social/message_transport.dart'; -export 'src/social/nostr/blossom_media_transport.dart'; export 'src/social/nostr/nostr_channel.dart'; export 'src/social/nostr/nostr_connection.dart'; export 'src/social/nostr/nostr_message_transport.dart'; diff --git a/packages/commons_core/lib/src/social/media_transport.dart b/packages/commons_core/lib/src/social/media_transport.dart deleted file mode 100644 index 4e7c044..0000000 --- a/packages/commons_core/lib/src/social/media_transport.dart +++ /dev/null @@ -1,22 +0,0 @@ -import 'dart:typed_data'; - -/// Uploads a public image and returns a URL peers can fetch — the hosting seam -/// for offer photos. An [Offer] carries only a URL on the wire (NIP-99), never -/// bytes; this transport turns local bytes into that URL. -/// -/// A sibling of [OfferTransport]/`MessageTransport`/`TrustTransport`, but it does -/// NOT ride the relay websocket: media goes over plain HTTP to a media server -/// (Blossom), so it takes its own endpoint rather than a `NostrChannel`. -/// -/// Uploading a photo here publishes it: an offer is a public shop window the -/// person elected to reveal, so its image is public too. This is distinct from -/// the encrypted-at-rest inventory — nothing local is exposed by this seam. -abstract interface class MediaTransport { - /// Uploads [bytes] and returns the public URL. Expected to be idempotent for - /// content-addressed backends (re-uploading the same bytes yields the same - /// URL). Throws when the server rejects the upload or is unreachable — callers - /// degrade by publishing the offer without an image. - Future upload(Uint8List bytes, {required String mimeType}); - - Future close(); -} diff --git a/packages/commons_core/lib/src/social/nostr/blossom_media_transport.dart b/packages/commons_core/lib/src/social/nostr/blossom_media_transport.dart deleted file mode 100644 index e80aabc..0000000 --- a/packages/commons_core/lib/src/social/nostr/blossom_media_transport.dart +++ /dev/null @@ -1,114 +0,0 @@ -import 'dart:convert'; -import 'dart:typed_data'; - -import 'package:crypto/crypto.dart' as crypto; -import 'package:http/http.dart' as http; -import 'package:nostr/nostr.dart'; - -import '../media_transport.dart'; - -/// [MediaTransport] backed by a Blossom media server (BUD-01/02). -/// -/// Blossom is content-addressed: a blob's URL is derived from its SHA-256, so -/// uploads are idempotent (the server dedups) and the URL is deterministic. We -/// authorize each upload with a signed kind-24242 event — the same secp256k1 -/// identity that signs offers — and PUT the bytes; no relay is involved. -class BlossomMediaTransport implements MediaTransport { - BlossomMediaTransport( - Uri server, - this._secretKeyHex, { - http.Client? client, - Duration authTtl = const Duration(hours: 1), - }) : _server = _normalize(server), - _client = client ?? http.Client(), - _ownsClient = client == null, - _authTtl = authTtl; - - /// Blossom kind for upload/list/delete authorization events (BUD-01). - static const authKind = 24242; - - final Uri _server; - final String _secretKeyHex; - final http.Client _client; - final bool _ownsClient; - final Duration _authTtl; - - @override - Future upload(Uint8List bytes, {required String mimeType}) async { - final sha = crypto.sha256.convert(bytes).toString(); - final auth = _authEvent(sha); - final response = await _client.put( - _server.resolve('upload'), - headers: { - 'Authorization': 'Nostr ${base64.encode(utf8.encode(auth.toJson()))}', - 'Content-Type': mimeType, - }, - body: bytes, - ); - if (response.statusCode < 200 || response.statusCode >= 300) { - throw MediaUploadException( - 'Blossom upload failed (${response.statusCode})', - response.statusCode, - ); - } - return _urlFrom(response.body, sha); - } - - /// Signed kind-24242 authorization: declares an `upload`, the blob's hash, and - /// an expiry so a captured header can't be replayed forever. - Event _authEvent(String sha256hex) { - final expiry = - DateTime.now().add(_authTtl).millisecondsSinceEpoch ~/ 1000; - return Event.from( - kind: authKind, - content: 'Upload offer photo', - tags: [ - ['t', 'upload'], - ['x', sha256hex], - ['expiration', '$expiry'], - ], - secretKey: _secretKeyHex, - ); - } - - /// Prefers the `url` from the blob descriptor the server returns; falls back to - /// the deterministic `/` when the body is missing or unparsable. - Uri _urlFrom(String body, String sha256hex) { - if (body.isNotEmpty) { - try { - final decoded = json.decode(body); - if (decoded is Map && decoded['url'] is String) { - final url = (decoded['url'] as String).trim(); - if (url.isNotEmpty) return Uri.parse(url); - } - } on FormatException { - // Non-JSON body — fall through to the content-addressed URL. - } - } - return _server.resolve(sha256hex); - } - - static Uri _normalize(Uri server) { - // Ensure a trailing slash so `resolve('upload')` appends rather than - // replacing the last path segment. - if (server.path.endsWith('/')) return server; - return server.replace(path: '${server.path}/'); - } - - @override - Future close() async { - if (_ownsClient) _client.close(); - } -} - -/// Thrown when the media server rejects an upload. Callers treat it as "publish -/// the offer without a photo", never as a hard failure of sharing. -class MediaUploadException implements Exception { - const MediaUploadException(this.message, this.statusCode); - - final String message; - final int statusCode; - - @override - String toString() => 'MediaUploadException($statusCode): $message'; -} diff --git a/packages/commons_core/pubspec.yaml b/packages/commons_core/pubspec.yaml index 7a522b4..ef9d76a 100644 --- a/packages/commons_core/pubspec.yaml +++ b/packages/commons_core/pubspec.yaml @@ -21,11 +21,6 @@ dependencies: # signing, NIP-19, NIP-44, gift wrap — the vetted crypto for the social layer # transport. We keep the relay/websocket layer and our derivation on top. nostr: ^2.0.0 - # Plain HTTP (BSD-3, AGPL-compatible) for the Blossom media server — offer - # photos are uploaded over HTTP, not the relay websocket. Client is injectable. - http: ^1.2.0 - # Sync SHA-256 (BSD-3) for content-addressed Blossom blob ids. - crypto: ^3.0.3 dev_dependencies: lints: ^6.0.0 diff --git a/packages/commons_core/test/social/blossom_media_transport_test.dart b/packages/commons_core/test/social/blossom_media_transport_test.dart deleted file mode 100644 index 15ea2d1..0000000 --- a/packages/commons_core/test/social/blossom_media_transport_test.dart +++ /dev/null @@ -1,90 +0,0 @@ -import 'dart:convert'; -import 'dart:typed_data'; - -import 'package:commons_core/commons_core.dart'; -import 'package:crypto/crypto.dart' as crypto; -import 'package:http/http.dart' as http; -import 'package:http/testing.dart'; -import 'package:nostr/nostr.dart'; -import 'package:test/test.dart'; - -void main() { - Future secretKey() async { - final id = await NostrKeyDerivation.deriveFromSeed( - Uint8List(32)..fillRange(0, 32, 7), - ); - return id.privateKeyHex; - } - - final bytes = Uint8List.fromList(List.generate(64, (i) => i)); - final sha = crypto.sha256.convert(bytes).toString(); - - test('PUTs to /upload with a signed kind-24242 auth and returns the url', - () async { - late http.Request captured; - final client = MockClient((req) async { - captured = req; - return http.Response( - json.encode({'url': 'https://media.test/$sha.jpg', 'sha256': sha}), - 200, - ); - }); - final transport = BlossomMediaTransport( - Uri.parse('https://media.test'), - await secretKey(), - client: client, - ); - - final url = await transport.upload(bytes, mimeType: 'image/jpeg'); - - expect(url, Uri.parse('https://media.test/$sha.jpg')); - expect(captured.method, 'PUT'); - expect(captured.url, Uri.parse('https://media.test/upload')); - expect(captured.bodyBytes, bytes); - expect(captured.headers['content-type'], startsWith('image/jpeg')); - - // The Authorization header is a base64 Nostr event; decode and inspect it. - final header = captured.headers['authorization']!; - expect(header, startsWith('Nostr ')); - final event = Event.fromMap( - json.decode(utf8.decode(base64.decode(header.substring(6)))) - as Map, - verify: true, // a real Schnorr signature over the canonical id - ); - expect(event.kind, BlossomMediaTransport.authKind); - String? tag(String name) => event.tags - .firstWhere((t) => t.isNotEmpty && t[0] == name, orElse: () => const []) - .elementAtOrNull(1); - expect(tag('t'), 'upload'); - expect(tag('x'), sha); - expect(tag('expiration'), isNotNull); - }); - - test('falls back to / when the body carries no url', () async { - final client = MockClient((req) async => http.Response('', 200)); - final transport = BlossomMediaTransport( - Uri.parse('https://media.test/'), - await secretKey(), - client: client, - ); - - final url = await transport.upload(bytes, mimeType: 'image/jpeg'); - - expect(url, Uri.parse('https://media.test/$sha')); - }); - - test('throws MediaUploadException on a non-2xx response', () async { - final client = MockClient((req) async => http.Response('nope', 413)); - final transport = BlossomMediaTransport( - Uri.parse('https://media.test'), - await secretKey(), - client: client, - ); - - expect( - () => transport.upload(bytes, mimeType: 'image/jpeg'), - throwsA(isA() - .having((e) => e.statusCode, 'statusCode', 413)), - ); - }); -}