Merge pull request #518 from ericszimmermann/ez_image_urls

Show images to detected URLs
This commit is contained in:
zjs81 authored and GitHub committed 2026-09-03 07:19:29 -07:00
commit dbd7f2aa75
35 files changed
+1067 -43

No files matched your search

+1 -1
View File
@@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-all.zip
+2 -2
View File
@@ -19,8 +19,8 @@ pluginManagement {
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "8.9.1" apply false
id("org.jetbrains.kotlin.android") version "2.1.0" apply false
id("com.android.application") version "8.11.1" apply false
id("org.jetbrains.kotlin.android") version "2.2.20" apply false
}
include(":app")
+48
View File
@@ -375,12 +375,14 @@ class MeshCoreConnector extends ChangeNotifier {
List<Channel> _cachedChannels = [];
final Map<int, bool> _channelSmazEnabled = {};
final Map<int, bool> _channelCyr2LatEnabled = {};
final Map<int, bool> _channelUrlImagesEnabled = {};
final Map<int, String?> _channelCyr2LatProfileId = {};
final Map<int, Region> _channelRegions = {};
bool _lastSentWasCliCommand =
false; // Track if last sent message was a CLI command
final Map<String, bool> _contactSmazEnabled = {};
final Map<String, bool> _contactCyr2LatEnabled = {};
final Map<String, bool> _contactUrlImagesEnabled = {};
final Map<String, String?> _contactCyr2LatProfileId = {};
final Set<String> _knownContactKeys = {};
final Map<String, int> _contactUnreadCount = {};
@@ -789,6 +791,15 @@ class MeshCoreConnector extends ChangeNotifier {
return _contactSmazEnabled[contactKeyHex] ?? false;
}
bool isChannelUrlImagesEnabled(int channelIndex) {
return _channelUrlImagesEnabled[channelIndex] ?? false;
}
bool isContactUrlImagesEnabled(String contactKeyHex) {
_ensureContactUrlImagesSettingLoaded(contactKeyHex);
return _contactUrlImagesEnabled[contactKeyHex] ?? false;
}
bool hasChannelRegion(int channelIndex) {
return (_channelRegions[channelIndex] ?? '').isNotEmpty;
}
@@ -931,6 +942,24 @@ class MeshCoreConnector extends ChangeNotifier {
notifyListeners();
}
Future<void> setChannelUrlImagesEnabled(
int channelIndex,
bool enabled,
) async {
_channelUrlImagesEnabled[channelIndex] = enabled;
await _channelSettingsStore.saveUrlImagesEnabled(channelIndex, enabled);
notifyListeners();
}
Future<void> setContactUrlImagesEnabled(
String contactKeyHex,
bool enabled,
) async {
_contactUrlImagesEnabled[contactKeyHex] = enabled;
await _contactSettingsStore.saveUrlImagesEnabled(contactKeyHex, enabled);
notifyListeners();
}
Future<void> setChannelCyr2LatEnabled(int channelIndex, bool enabled) async {
_channelCyr2LatEnabled[channelIndex] = enabled;
if (enabled) {
@@ -1101,6 +1130,7 @@ class MeshCoreConnector extends ChangeNotifier {
}
Future<void> loadContactCache() async {
_contactUrlImagesEnabled.clear();
final cached = await _contactStore.loadContacts();
_knownContactKeys
..clear()
@@ -1111,6 +1141,7 @@ class MeshCoreConnector extends ChangeNotifier {
for (final contact in cached) {
_ensureContactSmazSettingLoaded(contact.publicKeyHex);
_ensureContactCyr2LatSettingLoaded(contact.publicKeyHex);
_ensureContactUrlImagesSettingLoaded(contact.publicKeyHex);
}
}
@@ -1131,12 +1162,15 @@ class MeshCoreConnector extends ChangeNotifier {
Future<void> loadChannelSettings({int? maxChannels}) async {
_channelSmazEnabled.clear();
_channelCyr2LatEnabled.clear();
_channelUrlImagesEnabled.clear();
_channelRegions.clear();
final channelCount = maxChannels ?? _maxChannels;
for (int i = 0; i < channelCount; i++) {
_channelSmazEnabled[i] = await _channelSettingsStore.loadSmazEnabled(i);
_channelCyr2LatEnabled[i] = await _channelSettingsStore
.loadCyr2LatEnabled(i);
_channelUrlImagesEnabled[i] = await _channelSettingsStore
.loadUrlImagesEnabled(i);
_channelRegions[i] = await _channelRegionStore.loadRegion(i);
}
}
@@ -5329,6 +5363,8 @@ class MeshCoreConnector extends ChangeNotifier {
await _notificationService.showMessageNotification(
contactName: c?.name ?? 'Unknown',
message: resolvedText,
urlImagesEnabled:
c != null && isContactUrlImagesEnabled(c.publicKeyHex),
contactId: msg.senderKeyHex,
badgeCount: getTotalUnreadCount(),
);
@@ -5343,6 +5379,8 @@ class MeshCoreConnector extends ChangeNotifier {
await _notificationService.showMessageNotification(
contactName: c?.name ?? 'Unknown Room',
message: resolvedText,
urlImagesEnabled:
c != null && isContactUrlImagesEnabled(c.publicKeyHex),
contactId: msg.senderKeyHex,
badgeCount: getTotalUnreadCount(),
);
@@ -5493,6 +5531,15 @@ class MeshCoreConnector extends ChangeNotifier {
});
}
void _ensureContactUrlImagesSettingLoaded(String contactKeyHex) {
if (_contactUrlImagesEnabled.containsKey(contactKeyHex)) return;
_contactSettingsStore.loadUrlImagesEnabled(contactKeyHex).then((enabled) {
if (_contactUrlImagesEnabled[contactKeyHex] == enabled) return;
_contactUrlImagesEnabled[contactKeyHex] = enabled;
notifyListeners();
});
}
void _ensureContactCyr2LatProfileLoaded(String contactKeyHex) {
if (_contactCyr2LatProfileId.containsKey(contactKeyHex)) return;
_contactSettingsStore.loadCyr2LatProfileId(contactKeyHex).then((profileId) {
@@ -5647,6 +5694,7 @@ class MeshCoreConnector extends ChangeNotifier {
channelName: label,
senderName: message.senderName,
message: resolvedText,
urlImagesEnabled: isChannelUrlImagesEnabled(channelIndex),
channelIndex: message.channelIndex,
badgeCount: getTotalUnreadCount(),
);
+338
View File
@@ -0,0 +1,338 @@
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;
/// 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?>>();
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 _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) async {
final trimmed = text.trim();
if (trimmed.isEmpty) return null;
final pyxMatch = _pyxPattern.firstMatch(trimmed);
if (pyxMatch != null) {
return _extractFromUrl(
_trimBoundary(pyxMatch.group(0)!),
RegExp(r'''<img[^>]+src=["']([^"']+)["']''', caseSensitive: false),
);
}
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)!);
return 'https://ipfs.io/ipfs/$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) async {
final imageUrl = await parse(text);
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,
) {
final cached = _messageImageCache.remove(messageId);
if (cached != null) {
_messageImageCache[messageId] = cached;
return cached;
}
final parsing = parseVerified(text);
_messageImageCache[messageId] = parsing;
parsing.then((imageUrl) {
if (imageUrl == null &&
identical(_messageImageCache[messageId], parsing)) {
_messageImageCache.remove(messageId);
} 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 response = await http
.get(Uri.parse(pageUrl))
.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.parse(
pageUrl,
).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.builder,
});
final String messageId;
final String text;
final AsyncWidgetBuilder<String?> builder;
@override
State<MessageUrlImageFutureBuilder> createState() =>
_MessageUrlImageFutureBuilderState();
}
class _MessageUrlImageFutureBuilderState
extends State<MessageUrlImageFutureBuilder> {
late Future<String?> _imageFuture;
@override
void initState() {
super.initState();
_imageFuture = MessageUrlImageHelper.parseVerifiedForMessage(
widget.messageId,
widget.text,
);
}
@override
void didUpdateWidget(covariant MessageUrlImageFutureBuilder oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.messageId != widget.messageId) {
_imageFuture = MessageUrlImageHelper.parseVerifiedForMessage(
widget.messageId,
widget.text,
);
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String?>(
future: _imageFuture,
builder: widget.builder,
);
}
}
class MessageUrlImagePreview extends StatelessWidget {
const MessageUrlImagePreview({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: SizedBox(
width: 240,
height: 240,
child: CachedNetworkImage(
imageUrl: imageUrl,
fit: BoxFit.contain,
placeholder: (context, url) => ColoredBox(
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
View File
@@ -2626,6 +2626,8 @@
"messageStatus_pending": "Wird gesendet",
"messageStatus_failed": "Senden fehlgeschlagen",
"messageStatus_repeated": "Mehrfach gehört",
"urlImage_enable": "URL-Bilder anzeigen",
"urlImage_possible": "Mögliches URL-Bild; in den Einstellungen aktivieren.",
"contacts_moreOptions": "Weitere Optionen",
"contacts_searchOpen": "Suche öffnen",
"contacts_searchClose": "Suche schließen",
+2
View File
@@ -34,6 +34,8 @@
"messageStatus_pending": "Sending",
"messageStatus_failed": "Failed to send",
"messageStatus_repeated": "Heard repeated",
"urlImage_enable": "Enable URL images",
"urlImage_possible": "Possible URL image; enable it in Settings.",
"common_reboot": "Reboot",
"common_loading": "Loading...",
"common_notAvailable": "—",
+12
View File
@@ -334,6 +334,18 @@ abstract class AppLocalizations {
/// **'Heard repeated'**
String get messageStatus_repeated;
/// No description provided for @urlImage_enable.
///
/// In en, this message translates to:
/// **'Enable URL images'**
String get urlImage_enable;
/// No description provided for @urlImage_possible.
///
/// In en, this message translates to:
/// **'Possible URL image; enable it in Settings.'**
String get urlImage_possible;
/// No description provided for @common_reboot.
///
/// In en, this message translates to:
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get messageStatus_repeated => 'Повторно чуто';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Рестартирай';
+7
View File
@@ -110,6 +110,13 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get messageStatus_repeated => 'Mehrfach gehört';
@override
String get urlImage_enable => 'URL-Bilder anzeigen';
@override
String get urlImage_possible =>
'Mögliches URL-Bild; in den Einstellungen aktivieren.';
@override
String get common_reboot => 'Neustart';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get messageStatus_repeated => 'Heard repeated';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Reboot';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get messageStatus_repeated => 'Escuchado repetidamente';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Reiniciar';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get messageStatus_repeated => 'Reçu plusieurs fois';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Redémarrer';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get messageStatus_repeated => '– ismételte Heard';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Indítsa újra';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get messageStatus_repeated => 'Ricevuto ripetutamente';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Riavvia';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get messageStatus_repeated => '何度も聞いた';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => '再起動';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get messageStatus_repeated => '반복 수신됨';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => '재부팅';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get messageStatus_repeated => 'Hearsay, herhaald';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Herstarten';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get messageStatus_repeated => 'Usłyszałem to wielokrotnie';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Uruchom ponownie';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get messageStatus_repeated => 'Ouvi repetidamente';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Reiniciar';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get messageStatus_repeated => 'Услышал несколько раз';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Перезагрузить';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get messageStatus_repeated => 'Slyšal som to opakovane';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Restartovať';
+6
View File
@@ -111,6 +111,12 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get messageStatus_repeated => 'Slišal sem večkrat';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Ponoviti';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get messageStatus_repeated => 'Hördes upprepade gånger';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Start om';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get messageStatus_repeated => 'Почув неодноразово';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => 'Перезавантажити';
+6
View File
@@ -110,6 +110,12 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get messageStatus_repeated => '多次听到';
@override
String get urlImage_enable => 'Enable URL images';
@override
String get urlImage_possible => 'Possible URL image; enable it in Settings.';
@override
String get common_reboot => '重启';
+107 -21
View File
@@ -18,6 +18,7 @@ import '../helpers/chat_scroll_controller.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/cyr2lat.dart';
import '../helpers/gif_helper.dart';
import '../helpers/message_url_image_helper.dart';
import '../helpers/path_helper.dart';
import '../helpers/reaction_helper.dart';
import '../helpers/snack_bar_builder.dart';
@@ -412,6 +413,9 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
);
}
final urlImagesEnabled = connector.isChannelUrlImagesEnabled(
widget.channel.index,
);
// Images are not ChannelMessages: they arrive as GRP_DATA
// chunks and are owned by ReceivedImageStore, so the two
// sources are merged here in timestamp order and the list
@@ -500,7 +504,11 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
);
final message = row.message;
final bubble = message != null
? _buildMessageBubble(message, textScale)
? _buildMessageBubble(
message,
textScale,
urlImagesEnabled,
)
: _buildImageBubble(
row.image!,
textScale,
@@ -543,7 +551,11 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
connector.setChannelUnreadCount(widget.channel.index, count);
}
Widget _buildMessageBubble(ChannelMessage message, double textScale) {
Widget _buildMessageBubble(
ChannelMessage message,
double textScale,
bool urlImagesEnabled,
) {
final settingsService = context.watch<AppSettingsService>();
final enableTracing = settingsService.settings.enableMessageTracing;
final isOutgoing = message.isOutgoing;
@@ -583,6 +595,33 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
final metaColor = textColor.withValues(alpha: 0.65);
const bodyFontSize = 14.0;
Widget buildTextContent() {
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,
),
),
],
);
}
// Asymmetric radius matching chat_screen bubbles.
final borderRadius = isOutgoing
? const BorderRadius.only(
@@ -688,29 +727,76 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
),
],
)
else if (urlImagesEnabled)
MessageUrlImageFutureBuilder(
messageId: message.messageId,
text: 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: Align(
alignment: isOutgoing
? Alignment.centerRight
: Alignment.centerLeft,
child: MessageUrlImagePreview(
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 buildTextContent();
},
)
else
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: TranslatedMessageContent(
displayText: translatedDisplayText,
originalText: originalDisplayText,
style: TextStyle(
color: textColor,
fontSize: bodyFontSize * textScale,
if (MessageUrlImageHelper.hasPotentialImageUrl(
message.text,
))
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(
context.l10n.urlImage_possible,
style: TextStyle(
color: metaColor,
fontSize: 11 * textScale,
),
),
originalStyle: TextStyle(
fontSize: bodyFontSize * textScale,
fontStyle: FontStyle.italic,
color: textColor.withValues(alpha: 0.72),
),
onSecondaryTap: PlatformInfo.isDesktop
? () => _showMessageActions(message)
: null,
),
),
buildTextContent(),
],
),
if (enableTracing && displayPath.isNotEmpty) ...[
+12
View File
@@ -1533,6 +1533,7 @@ class _ChannelsScreenState extends State<ChannelsScreen>
final pskController = TextEditingController(text: channel.pskHex);
bool smazEnabled = connector.isChannelSmazEnabled(channel.index);
bool cyr2latEnabled = connector.isChannelCyr2LatEnabled(channel.index);
bool urlImagesEnabled = connector.isChannelUrlImagesEnabled(channel.index);
String? selectedCyr2LatProfileId = connector.getChannelCyr2LatProfileId(
channel.index,
);
@@ -1635,6 +1636,13 @@ class _ChannelsScreenState extends State<ChannelsScreen>
),
),
],
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text(sheetContext.l10n.urlImage_enable),
value: urlImagesEnabled,
onChanged: (value) =>
setSheetState(() => urlImagesEnabled = value),
),
const SizedBox(height: 24),
],
),
@@ -1684,6 +1692,10 @@ class _ChannelsScreenState extends State<ChannelsScreen>
channel.index,
cyr2latEnabled,
);
await connector.setChannelUrlImagesEnabled(
channel.index,
urlImagesEnabled,
);
await connector.setChannelCyr2LatProfileId(
channel.index,
selectedCyr2LatProfileId,
+110 -18
View File
@@ -13,6 +13,7 @@ import '../utils/platform_info.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../helpers/cyr2lat.dart';
import '../helpers/message_url_image_helper.dart';
import '../helpers/path_helper.dart';
import '../helpers/reaction_helper.dart';
import '../widgets/message_status_icon.dart';
@@ -895,6 +896,9 @@ class _ChatScreenState extends State<ChatScreen> {
bool cyr2latEnabled = connector.isContactCyr2LatEnabled(
contact.publicKeyHex,
);
bool urlImagesEnabled = connector.isContactUrlImagesEnabled(
contact.publicKeyHex,
);
String? selectedCyr2LatProfileId = connector.getContactCyr2LatProfileId(
contact.publicKeyHex,
);
@@ -994,6 +998,19 @@ class _ChatScreenState extends State<ChatScreen> {
),
],
const Divider(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text(context.l10n.urlImage_enable),
value: urlImagesEnabled,
onChanged: (value) {
connector.setContactUrlImagesEnabled(
contact.publicKeyHex,
value,
);
setDialogState(() => urlImagesEnabled = value);
},
),
const Divider(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: Text(context.l10n.contact_teleBase),
@@ -1335,6 +1352,9 @@ class _MessageBubble extends StatelessWidget {
final gifId = GifHelper.parseGif(message.text);
final poi = parseMarkerText(message.text);
final isFailed = message.status == MessageStatus.failed;
final urlImagesEnabled = context.select<MeshCoreConnector, bool>(
(connector) => connector.isContactUrlImagesEnabled(sourceId),
);
// Bubble colors — outgoing uses MeshPalette.me / meBorder / meInk.
final bubbleColor = isFailed
@@ -1382,6 +1402,30 @@ class _MessageBubble extends StatelessWidget {
? message.originalText
: (translatedDisplayText != messageText ? messageText : null);
Widget buildTextContent() {
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,
),
),
],
);
}
return Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: Column(
@@ -1469,28 +1513,76 @@ class _MessageBubble extends StatelessWidget {
),
],
)
else if (urlImagesEnabled)
MessageUrlImageFutureBuilder(
messageId: message.messageId,
text: 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: Align(
alignment: isOutgoing
? Alignment.centerRight
: Alignment.centerLeft,
child: MessageUrlImagePreview(
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 buildTextContent();
},
)
else
Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.end,
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Flexible(
child: TranslatedMessageContent(
displayText: translatedDisplayText,
originalText: originalDisplayText,
style: TextStyle(
color: textColor,
fontSize: bodyFontSize * textScale,
if (MessageUrlImageHelper.hasPotentialImageUrl(
message.text,
))
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(
context.l10n.urlImage_possible,
style: TextStyle(
color: metaColor,
fontSize: 11 * textScale,
),
),
originalStyle: TextStyle(
color: textColor.withValues(alpha: 0.72),
fontSize: bodyFontSize * textScale,
),
onSecondaryTap: PlatformInfo.isDesktop
? onLongPress
: null,
),
),
buildTextContent(),
],
),
if (enableTracing &&
+74
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_url_image_helper.dart';
import '../helpers/reaction_helper.dart';
import '../l10n/app_localizations.dart';
import '../utils/platform_info.dart';
@@ -196,14 +198,40 @@ class NotificationService {
return text;
}
Future<String?> _resolveNotificationImagePath(
String text, {
required bool urlImagesEnabled,
}) async {
if (!urlImagesEnabled) return null;
final imageUrl = await MessageUrlImageHelper.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,
required bool urlImagesEnabled,
String? contactId,
int? badgeCount,
}) async {
if (!await _ensureCanNotify()) return;
final imagePath = await _resolveNotificationImagePath(
message,
urlImagesEnabled: urlImagesEnabled,
);
final androidDetails = AndroidNotificationDetails(
'messages',
'Messages',
@@ -212,6 +240,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 +253,11 @@ class NotificationService {
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final macDetails = DarwinNotificationDetails(
@@ -226,6 +265,11 @@ class NotificationService {
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final notificationDetails = NotificationDetails(
@@ -299,11 +343,17 @@ class NotificationService {
Future<void> _showChannelMessageNotificationImpl({
required String channelName,
required String message,
required bool urlImagesEnabled,
int? channelIndex,
int? badgeCount,
}) async {
if (!await _ensureCanNotify()) return;
final imagePath = await _resolveNotificationImagePath(
message,
urlImagesEnabled: urlImagesEnabled,
);
final androidDetails = AndroidNotificationDetails(
'channel_messages',
'Channel Messages',
@@ -312,6 +362,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 +375,11 @@ class NotificationService {
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final macDetails = DarwinNotificationDetails(
@@ -326,6 +387,11 @@ class NotificationService {
presentBadge: true,
presentSound: true,
badgeNumber: badgeCount,
attachments: imagePath != null
? <DarwinNotificationAttachment>[
DarwinNotificationAttachment(imagePath),
]
: null,
);
final notificationDetails = NotificationDetails(
@@ -448,6 +514,7 @@ class NotificationService {
Future<void> showMessageNotification({
required String contactName,
required String message,
required bool urlImagesEnabled,
String? contactId,
int? badgeCount,
}) async {
@@ -458,6 +525,7 @@ class NotificationService {
type: _NotificationType.message,
title: contactName,
body: message,
urlImagesEnabled: urlImagesEnabled,
id: contactId,
badgeCount: badgeCount,
),
@@ -485,6 +553,7 @@ class NotificationService {
required String channelName,
required String senderName,
required String message,
required bool urlImagesEnabled,
int? channelIndex,
int? badgeCount,
}) async {
@@ -495,6 +564,7 @@ class NotificationService {
type: _NotificationType.channelMessage,
title: channelName,
body: '$senderName: $message',
urlImagesEnabled: urlImagesEnabled,
id: channelIndex?.toString(),
badgeCount: badgeCount,
),
@@ -556,6 +626,7 @@ class NotificationService {
await _showMessageNotificationImpl(
contactName: notification.title,
message: notification.body,
urlImagesEnabled: notification.urlImagesEnabled,
contactId: notification.id,
badgeCount: notification.badgeCount,
);
@@ -571,6 +642,7 @@ class NotificationService {
await _showChannelMessageNotificationImpl(
channelName: notification.title,
message: notification.body,
urlImagesEnabled: notification.urlImagesEnabled,
channelIndex: int.tryParse(notification.id ?? ''),
badgeCount: notification.badgeCount,
);
@@ -647,6 +719,7 @@ class _PendingNotification {
final _NotificationType type;
final String title;
final String body;
final bool urlImagesEnabled;
final String? id;
final int? badgeCount;
@@ -654,6 +727,7 @@ class _PendingNotification {
required this.type,
required this.title,
required this.body,
this.urlImagesEnabled = false,
this.id,
this.badgeCount,
});
+27
View File
@@ -4,6 +4,7 @@ import 'prefs_manager.dart';
class ChannelSettingsStore {
static const String _keyPrefix = 'channel_smaz_';
static const String _cyr2latKeyPrefix = 'channel_cyr2lat_';
static const String _urlImagesKeyPrefix = 'channel_url_images_';
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
@@ -11,6 +12,7 @@ class ChannelSettingsStore {
String get keyFor => '$_keyPrefix$publicKeyHex';
String get keyForCyr2Lat => '$_cyr2latKeyPrefix$publicKeyHex';
String get keyForUrlImages => '$_urlImagesKeyPrefix$publicKeyHex';
Future<bool> loadSmazEnabled(int channelIndex) async {
if (publicKeyHex.isEmpty) {
@@ -73,6 +75,31 @@ class ChannelSettingsStore {
await prefs.setBool(key, enabled);
}
Future<bool> loadUrlImagesEnabled(int channelIndex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(
'Public key hex is not set. Cannot load channel URL image settings.',
);
return false;
}
final prefs = PrefsManager.instance;
final key = '$keyForUrlImages$channelIndex';
return prefs.getBool(key) ?? false;
}
Future<void> saveUrlImagesEnabled(int channelIndex, bool enabled) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(
'Public key hex is not set. Cannot save channel URL image settings.',
);
return;
}
await PrefsManager.instance.setBool(
'$keyForUrlImages$channelIndex',
enabled,
);
}
Future<String?> loadCyr2LatProfileId(int channelIndex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(
+27
View File
@@ -4,6 +4,7 @@ import 'prefs_manager.dart';
class ContactSettingsStore {
static const String _keyPrefix = 'contact_smaz_';
static const String _cyr2latKeyPrefix = 'contact_cyr2lat_';
static const String _urlImagesKeyPrefix = 'contact_url_images_';
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
@@ -11,6 +12,7 @@ class ContactSettingsStore {
String get keyFor => '$_keyPrefix$publicKeyHex';
String get keyForCyr2Lat => '$_cyr2latKeyPrefix$publicKeyHex';
String get keyForUrlImages => '$_urlImagesKeyPrefix$publicKeyHex';
Future<bool> loadSmazEnabled(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
@@ -73,6 +75,31 @@ class ContactSettingsStore {
await prefs.setBool(key, enabled);
}
Future<bool> loadUrlImagesEnabled(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(
'Public key hex is not set. Cannot load contact URL image settings.',
);
return false;
}
final prefs = PrefsManager.instance;
final key = '$keyForUrlImages$contactKeyHex';
return prefs.getBool(key) ?? false;
}
Future<void> saveUrlImagesEnabled(String contactKeyHex, bool enabled) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(
'Public key hex is not set. Cannot save contact URL image settings.',
);
return;
}
await PrefsManager.instance.setBool(
'$keyForUrlImages$contactKeyHex',
enabled,
);
}
Future<String?> loadCyr2LatProfileId(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(
+1
View File
@@ -10,6 +10,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
list(APPEND FLUTTER_FFI_PLUGIN_LIST
flserial
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)
@@ -0,0 +1,93 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/message_url_image_helper.dart';
void main() {
group('MessageUrlImageHelper', () {
test('parses short pyx ids', () async {
final attachment = await MessageUrlImageHelper.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', () async {
final attachment = await MessageUrlImageHelper.parse(
'https://pyx.li/?i=Cd1KFiwu',
);
expect(attachment, isNotNull);
expect(attachment, 'https://pyx.li/i/Cd1KFiwu.jpg');
});
test('parses provider-hosted ipfs links', () async {
final attachment = await MessageUrlImageHelper.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', () async {
final attachment = await MessageUrlImageHelper.parse(
'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text',
);
expect(attachment, isNotNull);
expect(
attachment,
'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly',
);
});
test('parses direct ipfs cid urls without double slashes', () async {
final attachment = await MessageUrlImageHelper.parse(
'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text',
);
expect(
attachment,
'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly',
);
});
test('parses http image urls', () async {
final attachment = await MessageUrlImageHelper.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', () async {
expect(await MessageUrlImageHelper.parse('hello world'), isNull);
});
test('detects supported image URLs without resolving them', () {
expect(
MessageUrlImageHelper.hasPotentialImageUrl(
'https://pyx.li/?i=RzmdkTsE',
),
isTrue,
);
expect(
MessageUrlImageHelper.hasPotentialImageUrl('hello world'),
isFalse,
);
});
test('returns null for non-image ipfs gateway URL', () async {
final attachment = await MessageUrlImageHelper.parseVerified(
'https://lime-famous-rat-748.mypinata.cloud/ipfs/bafybeih3jqv36rsxqx7yw3k3ixhganrevrk7xmcxgkr2zuzjegxdytb3nq',
);
expect(attachment, isNull);
});
});
}
+101 -1
View File
@@ -1 +1,101 @@
{}
{
"bg": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"de": [
"reaction_report"
],
"es": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"fr": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"hu": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"it": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"ja": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"ko": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"nl": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"pl": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"pt": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"ru": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"sk": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"sl": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"sv": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"uk": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
],
"zh": [
"urlImage_enable",
"urlImage_possible",
"reaction_report"
]
}
+1
View File
@@ -13,6 +13,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
list(APPEND FLUTTER_FFI_PLUGIN_LIST
flserial
flutter_local_notifications_windows
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)