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.
This commit is contained in:
parent
5017ea51e0
commit
2b419e6516
24 changed files with 230 additions and 411 deletions
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
|
|
@ -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',
|
||||
|
|
|
|||
56
apps/app_seeds/lib/services/offer_thumbnail.dart
Normal file
56
apps/app_seeds/lib/services/offer_thumbnail.dart
Normal file
|
|
@ -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<int> 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);
|
||||
}
|
||||
|
|
@ -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<SocialSession> openSession(
|
||||
List<String> relayUrls, {
|
||||
String? mediaServerUrl,
|
||||
}) async {
|
||||
Future<SocialSession> openSession(List<String> 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<void> close() async {
|
||||
await media?.close();
|
||||
await _channel.close();
|
||||
}
|
||||
Future<void> close() => _channel.close();
|
||||
}
|
||||
|
||||
Uint8List _hexToBytes(String hex) {
|
||||
|
|
|
|||
|
|
@ -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<String> areaGeohash() async => (await _store.read(_areaKey)) ?? '';
|
||||
|
|
@ -79,18 +73,6 @@ class SocialSettings {
|
|||
Future<void> 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<String> mediaServerUrl() async {
|
||||
final raw = await _store.read(_mediaServerKey);
|
||||
if (raw == null) return defaultMediaServer; // never configured
|
||||
return raw.trim();
|
||||
}
|
||||
|
||||
Future<void> setMediaServerUrl(String url) =>
|
||||
_store.write(_mediaServerKey, url.trim());
|
||||
|
||||
int _clampPrecision(int p) => p < minSearchPrecision
|
||||
? minSearchPrecision
|
||||
: (p > maxSearchPrecision ? maxSearchPrecision : p);
|
||||
|
|
|
|||
|
|
@ -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<OffersState> {
|
||||
OffersCubit(
|
||||
this._transport, {
|
||||
MediaTransport? media,
|
||||
Future<Uint8List?> Function(String varietyId)? coverPhoto,
|
||||
String? Function(Uint8List bytes)? thumbnail,
|
||||
Future<void> 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<Uint8List?> 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<void> Function()? _onDispose;
|
||||
|
|
@ -284,7 +285,7 @@ class OffersCubit extends Cubit<OffersState> {
|
|||
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<OffersState> {
|
|||
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<String?> _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<String?> _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<OffersCubit> 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 (_) {
|
||||
|
|
|
|||
|
|
@ -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<void> _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<void> _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,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
61
apps/app_seeds/test/services/offer_thumbnail_test.dart
Normal file
61
apps/app_seeds/test/services/offer_thumbnail_test.dart
Normal file
|
|
@ -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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -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');
|
||||
|
|
|
|||
|
|
@ -41,24 +41,6 @@ class FakeOfferTransport implements OfferTransport {
|
|||
Future<void> 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<Uri> 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<void> 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(
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue