show images to detected URLs

This commit is contained in:
ericz committed 2026-08-07 19:28:43 +02:00
1 parent 98f6cf3745
commit 55529c3a61
10 files changed
+477 -68

No files matched your search

+195
View File
@@ -0,0 +1,195 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
class MessageImageHelper {
static final Map<String, Future<bool>> _verifiedImageCache =
<String, Future<bool>>{};
static final RegExp _pyxPattern = RegExp(
r'''https?://pyx\.li/\?i=([^\s<>'"`]+)''',
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 _imagePattern = RegExp(
r'''https?://[^\s<>'"`]+?\.(?:png|jpe?g|webp)(?:\?[^\s<>'"`]+)?(?:#[^\s<>'"`]+)?''',
caseSensitive: false,
);
static String? parse(String text) {
final trimmed = text.trim();
if (trimmed.isEmpty) return null;
String? imageUrl;
final pyxMatch = _pyxPattern.firstMatch(trimmed);
if (pyxMatch != null) {
final id = _trimBoundary(pyxMatch.group(1)!);
imageUrl = 'https://pyx.li/i/$id.jpg';
}
final ipfsUrlMatch = _ipfsUrlPattern.firstMatch(trimmed);
if (ipfsUrlMatch != null) {
imageUrl = _trimBoundary(ipfsUrlMatch.group(0)!);
}
final ipfsCidMatch = _ipfsCidPattern.firstMatch(trimmed);
if (ipfsCidMatch != null) {
final cid = _trimBoundary(ipfsCidMatch.group(1)!);
imageUrl = 'https://ipfs.io/ipfs/$cid';
}
final imageMatch = _imagePattern.firstMatch(trimmed);
if (imageMatch != null) {
imageUrl = _trimBoundary(imageMatch.group(0)!);
}
return imageUrl;
}
static Future<String?> parseVerified(String text) async {
final imageUrl = parse(text);
if (imageUrl == null) return null;
final verified = await _verifyImageUrl(imageUrl);
return verified ? imageUrl : null;
}
static String _trimBoundary(String value) {
return value.trim().replaceAll(RegExp(r"[.,;:!?]+$"), '');
}
static Future<bool> _verifyImageUrl(String imageUrl) {
return _verifiedImageCache.putIfAbsent(
imageUrl,
() => _tryLoadImage(imageUrl),
);
}
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 MessageImagePreview extends StatelessWidget {
const MessageImagePreview({super.key, required this.imageUrl});
final String imageUrl;
@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: ClipRRect(
borderRadius: BorderRadius.circular(12),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 240, maxHeight: 240),
child: CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.contain,
placeholder: (context, url) => Container(
width: 200,
height: 140,
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: const Center(
child: CircularProgressIndicator(strokeWidth: 2),
),
),
errorWidget: (context, url, error) => Container(
padding: const EdgeInsets.all(12),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Text(
'Unable to load image',
style: Theme.of(context).textTheme.bodySmall,
),
),
),
),
),
);
}
}
+2 -4
View File
@@ -76,8 +76,7 @@ class Cyr2LatProfile {
class AppSettings {
static const Object _unset = Object();
static const String stadiaDemo =
'51bd0381-4685-4666-bae8-48940f6d77c0';
static const String stadiaDemo = '51bd0381-4685-4666-bae8-48940f6d77c0';
final bool clearPathOnMaxRetry;
final bool mapShowRepeaters;
@@ -137,8 +136,7 @@ class AppSettings {
return apiKey;
}
bool get usesstadiaDemo =>
effectiveMapTileApiKey == stadiaDemo;
bool get usesstadiaDemo => effectiveMapTileApiKey == stadiaDemo;
Map<String, String> get cyr2latCharMap {
final profile = cyr2latProfiles.firstWhere(
+1 -3
View File
@@ -1153,9 +1153,7 @@ class AppSettingsScreen extends StatelessWidget {
) {
final currentApiKey = settingsService.settings.mapTileApiKey?.trim() ?? '';
final maskedApiKey = _maskApiKey(
currentApiKey.isEmpty
? AppSettings.stadiaDemo
: currentApiKey,
currentApiKey.isEmpty ? AppSettings.stadiaDemo : currentApiKey,
);
final controller = TextEditingController(text: maskedApiKey);
showDialog(
+77 -34
View File
@@ -16,6 +16,7 @@ import '../helpers/chat_scroll_controller.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/cyr2lat.dart';
import '../helpers/gif_helper.dart';
import '../helpers/message_image_helper.dart';
import '../helpers/path_helper.dart';
import '../helpers/reaction_helper.dart';
import '../helpers/snack_bar_builder.dart';
@@ -657,29 +658,77 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
],
)
else
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Flexible(
child: TranslatedMessageContent(
displayText: translatedDisplayText,
originalText: originalDisplayText,
style: TextStyle(
color: textColor,
fontSize: bodyFontSize * textScale,
FutureBuilder<String?>(
future: MessageImageHelper.parseVerified(
message.text,
),
builder: (context, snapshot) {
final imageAttachment = snapshot.data;
if (imageAttachment != null) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 4,
),
child: MessageImagePreview(
imageUrl: imageAttachment,
),
),
Padding(
padding: const EdgeInsets.only(top: 8),
child: TranslatedMessageContent(
displayText: translatedDisplayText,
originalText: originalDisplayText,
style: TextStyle(
color: textColor,
fontSize: bodyFontSize * textScale,
),
originalStyle: TextStyle(
fontSize: bodyFontSize * textScale,
fontStyle: FontStyle.italic,
color: textColor.withValues(
alpha: 0.72,
),
),
onSecondaryTap: PlatformInfo.isDesktop
? () => _showMessageActions(message)
: null,
),
),
],
);
}
return Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Flexible(
child: TranslatedMessageContent(
displayText: translatedDisplayText,
originalText: originalDisplayText,
style: TextStyle(
color: textColor,
fontSize: bodyFontSize * textScale,
),
originalStyle: TextStyle(
fontSize: bodyFontSize * textScale,
fontStyle: FontStyle.italic,
color: textColor.withValues(
alpha: 0.72,
),
),
onSecondaryTap: PlatformInfo.isDesktop
? () => _showMessageActions(message)
: null,
),
),
originalStyle: TextStyle(
fontSize: bodyFontSize * textScale,
fontStyle: FontStyle.italic,
color: textColor.withValues(alpha: 0.72),
),
onSecondaryTap: PlatformInfo.isDesktop
? () => _showMessageActions(message)
: null,
),
),
],
],
);
},
),
if (enableTracing && displayPath.isNotEmpty) ...[
const SizedBox(height: 3),
@@ -700,9 +749,9 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
child: Text(
context.l10n.channels_via(
_formatPathPrefixes(
displayPath,
displayPathHashWidth,
),
displayPath,
displayPathHashWidth,
),
),
style: MeshTheme.mono(
fontSize: 9.5 * textScale,
@@ -1214,25 +1263,19 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
decoration: InputDecoration(
hintText: context.l10n.chat_typeMessage,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(
MeshRadii.md,
),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(
color: scheme.outlineVariant,
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
MeshRadii.md,
),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(
color: scheme.outlineVariant,
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(
MeshRadii.md,
),
borderRadius: BorderRadius.circular(MeshRadii.md),
borderSide: BorderSide(
color: scheme.primary,
width: 1.5,
+2 -1
View File
@@ -412,7 +412,8 @@ class _ChannelsScreenState extends State<ChannelsScreen>
final messages = connector.getChannelMessages(channel);
final lastMessage = messages.isNotEmpty ? messages.last : null;
final lastMessageText = lastMessage?.text ?? '';
final lastPreview = lastMessageText.isNotEmpty &&
final lastPreview =
lastMessageText.isNotEmpty &&
GifHelper.parseGif(lastMessageText) != null
? context.l10n.chat_receivedGif
: lastMessageText;
+70 -21
View File
@@ -12,6 +12,7 @@ import '../utils/platform_info.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/cyr2lat.dart';
import '../helpers/message_image_helper.dart';
import '../helpers/path_helper.dart';
import '../helpers/reaction_helper.dart';
import '../widgets/message_status_icon.dart';
@@ -1441,28 +1442,76 @@ class _MessageBubble extends StatelessWidget {
],
)
else
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Flexible(
child: TranslatedMessageContent(
displayText: translatedDisplayText,
originalText: originalDisplayText,
style: TextStyle(
color: textColor,
fontSize: bodyFontSize * textScale,
FutureBuilder<String?>(
future: MessageImageHelper.parseVerified(
message.text,
),
builder: (context, snapshot) {
final imageAttachment = snapshot.data;
if (imageAttachment != null) {
return Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 4,
),
child: MessageImagePreview(
imageUrl: imageAttachment,
),
),
Padding(
padding: const EdgeInsets.only(top: 8),
child: TranslatedMessageContent(
displayText: translatedDisplayText,
originalText: originalDisplayText,
style: TextStyle(
color: textColor,
fontSize: bodyFontSize * textScale,
),
originalStyle: TextStyle(
color: textColor.withValues(
alpha: 0.72,
),
fontSize: bodyFontSize * textScale,
),
onSecondaryTap: PlatformInfo.isDesktop
? onLongPress
: null,
),
),
],
);
}
return Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Flexible(
child: TranslatedMessageContent(
displayText: translatedDisplayText,
originalText: originalDisplayText,
style: TextStyle(
color: textColor,
fontSize: bodyFontSize * textScale,
),
originalStyle: TextStyle(
color: textColor.withValues(
alpha: 0.72,
),
fontSize: bodyFontSize * textScale,
),
onSecondaryTap: PlatformInfo.isDesktop
? onLongPress
: null,
),
),
originalStyle: TextStyle(
color: textColor.withValues(alpha: 0.72),
fontSize: bodyFontSize * textScale,
),
onSecondaryTap: PlatformInfo.isDesktop
? onLongPress
: null,
),
),
],
],
);
},
),
if (enableTracing &&
isOutgoing &&
+53
View File
@@ -3,7 +3,9 @@ import 'dart:ui';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import '../helpers/message_image_helper.dart';
import '../helpers/reaction_helper.dart';
import '../l10n/app_localizations.dart';
import '../utils/platform_info.dart';
@@ -196,6 +198,21 @@ class NotificationService {
return text;
}
Future<String?> _resolveNotificationImagePath(String text) async {
final imageUrl = await MessageImageHelper.parseVerified(text);
if (imageUrl == null) return null;
try {
// Cache the image so notification platforms can read it from disk.
final imageFile = await DefaultCacheManager().getSingleFile(imageUrl);
if (!imageFile.existsSync()) return null;
return imageFile.path;
} catch (e) {
debugPrint('Failed to resolve notification image: $e');
return null;
}
}
Future<void> _showMessageNotificationImpl({
required String contactName,
required String message,
@@ -204,6 +221,8 @@ class NotificationService {
}) async {
if (!await _ensureCanNotify()) return;
final imagePath = await _resolveNotificationImagePath(message);
final androidDetails = AndroidNotificationDetails(
'messages',
'Messages',
@@ -212,6 +231,12 @@ class NotificationService {
priority: Priority.high,
icon: '@mipmap/ic_launcher',
number: badgeCount,
styleInformation: imagePath != null
? BigPictureStyleInformation(
FilePathAndroidBitmap(imagePath),
summaryText: formatNotificationText(message),
)
: null,
);
final iosDetails = DarwinNotificationDetails(
@@ -219,6 +244,11 @@ class NotificationService {
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final macDetails = DarwinNotificationDetails(
@@ -226,6 +256,11 @@ class NotificationService {
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final notificationDetails = NotificationDetails(
@@ -304,6 +339,8 @@ class NotificationService {
}) async {
if (!await _ensureCanNotify()) return;
final imagePath = await _resolveNotificationImagePath(message);
final androidDetails = AndroidNotificationDetails(
'channel_messages',
'Channel Messages',
@@ -312,6 +349,12 @@ class NotificationService {
priority: Priority.high,
icon: '@mipmap/ic_launcher',
number: badgeCount,
styleInformation: imagePath != null
? BigPictureStyleInformation(
FilePathAndroidBitmap(imagePath),
summaryText: formatNotificationText(message),
)
: null,
);
final iosDetails = DarwinNotificationDetails(
@@ -319,6 +362,11 @@ class NotificationService {
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final macDetails = DarwinNotificationDetails(
@@ -326,6 +374,11 @@ class NotificationService {
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final notificationDetails = NotificationDetails(
@@ -0,0 +1,67 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/message_image_helper.dart';
void main() {
group('MessageImageHelper', () {
test('parses short pyx ids', () {
final attachment = MessageImageHelper.parse(
'my picture: https://pyx.li/?i=RzmdkTsE text',
);
expect(attachment, isNotNull);
expect(attachment, 'https://pyx.li/i/RzmdkTsE.jpg');
});
test('parses direct pyx image urls', () {
final attachment = MessageImageHelper.parse('https://pyx.li/?i=Cd1KFiwu');
expect(attachment, isNotNull);
expect(attachment, 'https://pyx.li/i/Cd1KFiwu.jpg');
});
test('parses provider-hosted ipfs links', () {
final attachment = MessageImageHelper.parse(
'my picture: https://uneven-plum-tarantula.myfilebase.com/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text',
);
expect(attachment, isNotNull);
expect(
attachment,
'https://uneven-plum-tarantula.myfilebase.com/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly',
);
});
test('parses direct ipfs cid urls', () {
final attachment = MessageImageHelper.parse(
'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text',
);
expect(attachment, isNotNull);
expect(
attachment,
'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly',
);
});
test('parses http image urls', () {
final attachment = MessageImageHelper.parse(
'see this image https://example.com/picture.png?size=large additional text',
);
expect(attachment, isNotNull);
expect(attachment, 'https://example.com/picture.png?size=large');
});
test('returns null for plain text', () {
expect(MessageImageHelper.parse('hello world'), isNull);
});
test('returns null for non-image ipfs gateway url', () async {
final attachment = await MessageImageHelper.parseVerified(
'https://lime-famous-rat-748.mypinata.cloud/ipfs/bafybeih3jqv36rsxqx7yw3k3ixhganrevrk7xmcxgkr2zuzjegxdytb3nq',
);
expect(attachment, isNull);
});
});
}
-1
View File
@@ -643,7 +643,6 @@ void main() {
expect(contacts.first.path, equals(Uint8List.fromList([0x11, 0x22])));
},
);
});
group('AppSettingsService — gps interval fallback', () {
+10 -4
View File
@@ -22,7 +22,8 @@ class _FakeStorageService extends StorageService {
ContactPathHistory history,
) async {}
@override
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async => null;
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async =>
null;
@override
Future<void> clearPathHistory(String contactPubKeyHex) async {}
}
@@ -71,13 +72,18 @@ Widget _buildTestApp({
required MeshCoreConnector connector,
required Widget child,
}) {
final appSettingsService = AppSettingsService();
return MultiProvider(
providers: [
ChangeNotifierProvider<MeshCoreConnector>.value(value: connector),
ChangeNotifierProvider<AppSettingsService>(
create: (_) => AppSettingsService(),
ChangeNotifierProvider<AppSettingsService>.value(
value: appSettingsService,
),
ChangeNotifierProvider<MapTileCacheService>(
create: (_) =>
MapTileCacheService(appSettingsService: appSettingsService),
),
Provider<MapTileCacheService>(create: (_) => MapTileCacheService()),
ChangeNotifierProvider<PathHistoryService>(
create: (_) => PathHistoryService(_FakeStorageService()),
),