diff --git a/lib/helpers/message_image_helper.dart b/lib/helpers/message_image_helper.dart new file mode 100644 index 00000000..be4ef1f1 --- /dev/null +++ b/lib/helpers/message_image_helper.dart @@ -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> _verifiedImageCache = + >{}; + + 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 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 _verifyImageUrl(String imageUrl) { + return _verifiedImageCache.putIfAbsent( + imageUrl, + () => _tryLoadImage(imageUrl), + ); + } + + static Future _tryLoadImage(String imageUrl) async { + final completer = Completer(); + 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, + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index a6f82100..82d570c7 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -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 get cyr2latCharMap { final profile = cyr2latProfiles.firstWhere( diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 90a0a132..8405beca 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -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( diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index ce170aed..8a789347 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -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 { ], ) else - Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.end, - children: [ - Flexible( - child: TranslatedMessageContent( - displayText: translatedDisplayText, - originalText: originalDisplayText, - style: TextStyle( - color: textColor, - fontSize: bodyFontSize * textScale, + FutureBuilder( + 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 { 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 { 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, diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index fb5039d2..1867f5de 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -412,7 +412,8 @@ class _ChannelsScreenState extends State 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; diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index bfe5a381..60b4d1b9 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -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( + 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 && diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 05ebf6b0..16d90ad1 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -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 _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 _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(imagePath), + ] + : null, ); final macDetails = DarwinNotificationDetails( @@ -226,6 +256,11 @@ class NotificationService { presentBadge: true, presentSound: true, badgeNumber: badgeCount, + attachments: imagePath != null + ? [ + 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(imagePath), + ] + : null, ); final macDetails = DarwinNotificationDetails( @@ -326,6 +374,11 @@ class NotificationService { presentBadge: true, presentSound: true, badgeNumber: badgeCount, + attachments: imagePath != null + ? [ + DarwinNotificationAttachment(imagePath), + ] + : null, ); final notificationDetails = NotificationDetails( diff --git a/test/helpers/message_image_helper_test.dart b/test/helpers/message_image_helper_test.dart new file mode 100644 index 00000000..a652394d --- /dev/null +++ b/test/helpers/message_image_helper_test.dart @@ -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); + }); + }); +} diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index cc218c95..c91a9c73 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -643,7 +643,6 @@ void main() { expect(contacts.first.path, equals(Uint8List.fromList([0x11, 0x22]))); }, ); - }); group('AppSettingsService — gps interval fallback', () { diff --git a/test/screens/path_trace_test.dart b/test/screens/path_trace_test.dart index 55c10b14..74b2b37a 100644 --- a/test/screens/path_trace_test.dart +++ b/test/screens/path_trace_test.dart @@ -22,7 +22,8 @@ class _FakeStorageService extends StorageService { ContactPathHistory history, ) async {} @override - Future loadPathHistory(String contactPubKeyHex) async => null; + Future loadPathHistory(String contactPubKeyHex) async => + null; @override Future clearPathHistory(String contactPubKeyHex) async {} } @@ -71,13 +72,18 @@ Widget _buildTestApp({ required MeshCoreConnector connector, required Widget child, }) { + final appSettingsService = AppSettingsService(); + return MultiProvider( providers: [ ChangeNotifierProvider.value(value: connector), - ChangeNotifierProvider( - create: (_) => AppSettingsService(), + ChangeNotifierProvider.value( + value: appSettingsService, + ), + ChangeNotifierProvider( + create: (_) => + MapTileCacheService(appSettingsService: appSettingsService), ), - Provider(create: (_) => MapTileCacheService()), ChangeNotifierProvider( create: (_) => PathHistoryService(_FakeStorageService()), ),