Files
meshcore-open/lib/helpers/message_url_image_helper.dart
zjs81 40fb80cf5c Size URL image previews to the image's aspect ratio
The preview now fills the bubble's available width and takes its height from
the loaded image, capped at 400dp for tall images. Loading and error states
are a compact full-width strip, and the error text is localized.
2026-11-23 22:24:01 -07:00

496 lines
15 KiB
Dart

import 'dart:async';
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:http/http.dart' as http;
import '../l10n/l10n.dart';
import '../models/app_settings.dart';
/// Finds and renders image URLs embedded in ordinary text messages.
///
/// This is deliberately separate from MeshCore's transmitted channel-image
/// protocol, which is handled by [ReceivedImageStore].
class MessageUrlImageHelper {
static final Map<String, Future<bool>> _verifiedImageCache =
<String, Future<bool>>{};
static const int _maxMessageImageCacheEntries = 200;
static final LinkedHashMap<String, Future<String?>> _messageImageCache =
LinkedHashMap<String, Future<String?>>();
/// HTTP client used to resolve sharing pages.
///
/// Tests override this because `flutter_test` blocks real network requests.
@visibleForTesting
static http.Client? httpClient;
/// Mirrors [AppSettings.loadLinkImages]. When false, nothing is fetched
/// for link images and every parse returns null.
static final ValueNotifier<bool> loadLinkImages = ValueNotifier<bool>(true);
static final RegExp _pyxPattern = RegExp(
r'''https?://pyx\.li/\?i=([A-Za-z0-9_-]+)''',
caseSensitive: false,
);
static final RegExp _ipfsUrlPattern = RegExp(
r'''https?://[^\s<>'"`]+/(?:ipfs|ipns)/[^\s<>'"`]+''',
caseSensitive: false,
);
static final RegExp _ipfsCidPattern = RegExp(
r'''ipfs:(?://)?([^\s<>'"`]+)''',
caseSensitive: false,
);
static final RegExp _ibbSharePattern = RegExp(
r'''https?://(?:www\.)?ibb\.co/[^\s<>'"`/?#]+(?:[/?#][^\s<>'"`]*)?''',
caseSensitive: false,
);
static final RegExp _imagePattern = RegExp(
r'''https?://[^\s<>'"`]+?\.(?:png|jpe?g|webp)(?:\?[^\s<>'"`]+)?(?:#[^\s<>'"`]+)?''',
caseSensitive: false,
);
/// Checks locally whether [text] contains a URL format this helper supports.
/// This deliberately does not resolve sharing pages or fetch image data.
static bool hasPotentialImageUrl(String text) {
return _pyxPattern.hasMatch(text) ||
_ipfsUrlPattern.hasMatch(text) ||
_ipfsCidPattern.hasMatch(text) ||
_ibbSharePattern.hasMatch(text) ||
_imagePattern.hasMatch(text);
}
static Future<String?> parse(
String text, {
String publicGateway = AppSettings.defaultPublicIpfsGateway,
bool respectLoadSetting = true,
}) async {
if (respectLoadSetting && !loadLinkImages.value) return null;
final trimmed = text.trim();
if (trimmed.isEmpty) return null;
final pyxMatch = _pyxPattern.firstMatch(trimmed);
if (pyxMatch != null) {
return 'https://pyx.li/i/${pyxMatch.group(1)!}.jpg';
}
final ipfsUrlMatch = _ipfsUrlPattern.firstMatch(trimmed);
if (ipfsUrlMatch != null) {
return _trimBoundary(ipfsUrlMatch.group(0)!);
}
final ipfsCidMatch = _ipfsCidPattern.firstMatch(trimmed);
if (ipfsCidMatch != null) {
final cid = _trimBoundary(ipfsCidMatch.group(1)!);
final gateway = normalizeIpfsGateway(publicGateway);
if (gateway.isEmpty) return null;
return '$gateway$cid';
}
final ibbMatch = _ibbSharePattern.firstMatch(trimmed);
if (ibbMatch != null) {
return _extractFromUrl(
_trimBoundary(ibbMatch.group(0)!),
RegExp(
r'''<meta[^>]+property=["']og:image["'][^>]+content=["']([^"']+)["']''',
caseSensitive: false,
),
);
}
final imageMatch = _imagePattern.firstMatch(trimmed);
if (imageMatch != null) {
return _trimBoundary(imageMatch.group(0)!);
}
return null;
}
static Future<String?> parseVerified(
String text, {
String publicGateway = AppSettings.defaultPublicIpfsGateway,
}) async {
final imageUrl = await parse(text, publicGateway: publicGateway);
if (imageUrl == null) return null;
final verified = await _verifyImageUrl(imageUrl);
return verified ? imageUrl : null;
}
/// Caches successful URL-image parsing by stable message identity.
///
/// Null results are evicted so temporary connectivity or host failures can
/// be retried when a message is shown again.
static Future<String?> parseVerifiedForMessage(
String messageId,
String text, {
String publicGateway = AppSettings.defaultPublicIpfsGateway,
}) {
if (!loadLinkImages.value) return Future<String?>.value();
final cacheKey = '$messageId|$publicGateway';
final cached = _messageImageCache.remove(cacheKey);
if (cached != null) {
_messageImageCache[cacheKey] = cached;
return cached;
}
final parsing = parseVerified(text, publicGateway: publicGateway);
_messageImageCache[cacheKey] = parsing;
parsing.then((imageUrl) {
if (imageUrl == null &&
identical(_messageImageCache[cacheKey], parsing)) {
_messageImageCache.remove(cacheKey);
} else if (imageUrl != null) {
while (_messageImageCache.length > _maxMessageImageCacheEntries) {
_messageImageCache.remove(_messageImageCache.keys.first);
}
}
});
return parsing;
}
static Future<String?> _extractFromUrl(String pageUrl, RegExp pattern) async {
try {
final uri = Uri.parse(pageUrl);
final client = httpClient;
final response = await (client == null ? http.get(uri) : client.get(uri))
.timeout(const Duration(seconds: 8));
if (response.statusCode < 200 || response.statusCode >= 300) {
return null;
}
final value = pattern.firstMatch(response.body)?.group(1);
if (value == null || value.isEmpty) return null;
final imageUrl = uri.resolve(value.replaceAll('&amp;', '&'));
return imageUrl.scheme == 'http' || imageUrl.scheme == 'https'
? imageUrl.toString()
: null;
} catch (_) {
return null;
}
}
static String _trimBoundary(String value) {
return value.trim().replaceAll(RegExp(r"[.,;:!?]+$"), '');
}
static Future<bool> _verifyImageUrl(String imageUrl) {
final cached = _verifiedImageCache[imageUrl];
if (cached != null) return cached;
final verification = _tryLoadImage(imageUrl);
_verifiedImageCache[imageUrl] = verification;
verification.then((verified) {
if (!verified && identical(_verifiedImageCache[imageUrl], verification)) {
_verifiedImageCache.remove(imageUrl);
}
});
return verification;
}
static Future<bool> _tryLoadImage(String imageUrl) async {
final completer = Completer<bool>();
final stream = CachedNetworkImageProvider(
imageUrl,
).resolve(const ImageConfiguration());
late final ImageStreamListener listener;
listener = ImageStreamListener(
(_, _) {
if (!completer.isCompleted) completer.complete(true);
stream.removeListener(listener);
},
onError: (_, _) {
if (!completer.isCompleted) completer.complete(false);
stream.removeListener(listener);
},
);
stream.addListener(listener);
return completer.future.timeout(
const Duration(seconds: 8),
onTimeout: () {
stream.removeListener(listener);
return false;
},
);
}
}
class MessageUrlImageFutureBuilder extends StatefulWidget {
const MessageUrlImageFutureBuilder({
super.key,
required this.messageId,
required this.text,
required this.publicGateway,
required this.builder,
});
final String messageId;
final String text;
final String publicGateway;
final AsyncWidgetBuilder<String?> builder;
@override
State<MessageUrlImageFutureBuilder> createState() =>
_MessageUrlImageFutureBuilderState();
}
class _MessageUrlImageFutureBuilderState
extends State<MessageUrlImageFutureBuilder> {
late Future<String?> _imageFuture;
@override
void initState() {
super.initState();
_imageFuture = _parse();
MessageUrlImageHelper.loadLinkImages.addListener(_onLoadLinkImagesChanged);
}
@override
void didUpdateWidget(covariant MessageUrlImageFutureBuilder oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.messageId != widget.messageId ||
oldWidget.publicGateway != widget.publicGateway) {
_imageFuture = _parse();
}
}
@override
void dispose() {
MessageUrlImageHelper.loadLinkImages.removeListener(
_onLoadLinkImagesChanged,
);
super.dispose();
}
Future<String?> _parse() {
return MessageUrlImageHelper.parseVerifiedForMessage(
widget.messageId,
widget.text,
publicGateway: widget.publicGateway,
);
}
void _onLoadLinkImagesChanged() {
setState(() => _imageFuture = _parse());
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String?>(
future: _imageFuture,
builder: widget.builder,
);
}
}
class MessageUrlImagePreview extends StatelessWidget {
const MessageUrlImagePreview({
super.key,
required this.imageUrl,
@visibleForTesting this.imageProvider,
});
static const double maxHeight = 400;
static const double fallbackWidth = 320;
static const double statusHeight = 130;
final String imageUrl;
final ImageProvider? imageProvider;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) => Dialog(
insetPadding: const EdgeInsets.all(12),
backgroundColor: Colors.black,
child: SizedBox(
width: double.infinity,
height: double.infinity,
child: Stack(
children: [
Positioned.fill(
child: InteractiveViewer(
boundaryMargin: const EdgeInsets.all(80),
minScale: 1.0,
maxScale: 3.0,
child: Center(
child: CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.contain,
placeholder: (context, url) => const Center(
child: CircularProgressIndicator(strokeWidth: 2),
),
errorWidget: (context, url, error) => const Center(
child: Icon(
Icons.broken_image,
color: Colors.white,
),
),
),
),
),
),
Positioned(
top: 12,
right: 12,
child: IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close, color: Colors.white),
style: IconButton.styleFrom(
backgroundColor: Colors.black54,
),
),
),
],
),
),
),
);
},
child: _AdaptiveUrlImage(
provider: imageProvider ?? CachedNetworkImageProvider(imageUrl),
),
);
}
}
/// Fits an image of [imageWidth] x [imageHeight] into [maxWidth], keeping its
/// aspect ratio. Images taller than [maxHeight] are scaled down whole instead.
Size urlImagePreviewSize(
double imageWidth,
double imageHeight,
double maxWidth, {
double maxHeight = MessageUrlImagePreview.maxHeight,
}) {
var width = maxWidth;
var height = width * imageHeight / imageWidth;
if (height > maxHeight) {
height = maxHeight;
width = height * imageWidth / imageHeight;
}
return Size(width, height);
}
class _AdaptiveUrlImage extends StatefulWidget {
const _AdaptiveUrlImage({required this.provider});
final ImageProvider provider;
@override
State<_AdaptiveUrlImage> createState() => _AdaptiveUrlImageState();
}
class _AdaptiveUrlImageState extends State<_AdaptiveUrlImage> {
ImageStream? _stream;
late final ImageStreamListener _listener = ImageStreamListener(
(info, _) {
if (!mounted) {
info.dispose();
return;
}
setState(() {
_info?.dispose();
_info = info;
_failed = false;
});
},
onError: (_, _) {
if (mounted) setState(() => _failed = true);
},
);
ImageInfo? _info;
bool _failed = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_resolve();
}
@override
void didUpdateWidget(covariant _AdaptiveUrlImage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.provider != widget.provider) {
_info?.dispose();
_info = null;
_failed = false;
_resolve();
}
}
void _resolve() {
final stream = widget.provider.resolve(
createLocalImageConfiguration(context),
);
if (stream.key == _stream?.key) return;
_stream?.removeListener(_listener);
_stream = stream..addListener(_listener);
}
@override
void dispose() {
_stream?.removeListener(_listener);
_info?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final color = Theme.of(context).colorScheme.surfaceContainerHighest;
return LayoutBuilder(
builder: (context, constraints) {
final maxWidth = constraints.maxWidth.isFinite
? constraints.maxWidth
: MessageUrlImagePreview.fallbackWidth;
final info = _info;
final Widget child;
if (info != null) {
final size = urlImagePreviewSize(
info.image.width.toDouble(),
info.image.height.toDouble(),
maxWidth,
);
child = SizedBox.fromSize(
size: size,
child: RawImage(image: info.image, fit: BoxFit.fill),
);
} else if (_failed) {
child = Container(
width: maxWidth,
height: MessageUrlImagePreview.statusHeight,
padding: const EdgeInsets.all(12),
alignment: Alignment.centerLeft,
color: color,
child: Text(
context.l10n.messageUrlImageLoadFailed,
style: Theme.of(context).textTheme.bodySmall,
),
);
} else {
child = SizedBox(
width: maxWidth,
height: MessageUrlImagePreview.statusHeight,
child: ColoredBox(
color: color,
child: const Center(
child: CircularProgressIndicator(strokeWidth: 2),
),
),
);
}
return ClipRRect(borderRadius: BorderRadius.circular(12), child: child);
},
);
}
}