From a4a7e007329aeb811cf80dfea1beb2c5638ad18e Mon Sep 17 00:00:00 2001 From: ericz Date: Sun, 11 Oct 2026 13:14:14 +0200 Subject: [PATCH 01/15] upload url image or file to ipfs --- lib/helpers/ipfs_upload_helper.dart | 187 ++++++++++ lib/helpers/message_url_image_helper.dart | 83 ++++- lib/l10n/app_en.arb | 24 ++ lib/l10n/app_localizations.dart | 102 ++++++ lib/l10n/app_localizations_bg.dart | 58 +++ lib/l10n/app_localizations_de.dart | 58 +++ lib/l10n/app_localizations_en.dart | 58 +++ lib/l10n/app_localizations_es.dart | 58 +++ lib/l10n/app_localizations_fr.dart | 58 +++ lib/l10n/app_localizations_hu.dart | 58 +++ lib/l10n/app_localizations_it.dart | 58 +++ lib/l10n/app_localizations_ja.dart | 58 +++ lib/l10n/app_localizations_ko.dart | 58 +++ lib/l10n/app_localizations_nl.dart | 58 +++ lib/l10n/app_localizations_pl.dart | 58 +++ lib/l10n/app_localizations_pt.dart | 58 +++ lib/l10n/app_localizations_ru.dart | 58 +++ lib/l10n/app_localizations_sk.dart | 58 +++ lib/l10n/app_localizations_sl.dart | 58 +++ lib/l10n/app_localizations_sv.dart | 58 +++ lib/l10n/app_localizations_uk.dart | 58 +++ lib/l10n/app_localizations_zh.dart | 58 +++ lib/main.dart | 8 + lib/models/app_settings.dart | 57 +++ lib/screens/app_settings_screen.dart | 328 ++++++++++++++++- lib/screens/channel_chat_screen.dart | 129 ++++++- lib/screens/chat_screen.dart | 178 +++++++-- lib/services/app_settings_service.dart | 18 + lib/services/notification_service.dart | 11 +- .../message_url_image_helper_test.dart | 95 ++++- test/models/model_changes_test.dart | 17 + .../tcp_transport_service_native_test.dart | 52 ++- untranslated.json | 342 +++++++++++++++++- 33 files changed, 2594 insertions(+), 81 deletions(-) create mode 100644 lib/helpers/ipfs_upload_helper.dart diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart new file mode 100644 index 00000000..8d294568 --- /dev/null +++ b/lib/helpers/ipfs_upload_helper.dart @@ -0,0 +1,187 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +import '../models/app_settings.dart'; + +class IpfsUploadHelper { + static http.Client? httpClient; + + static String mimeTypeForFileName(String fileName) { + switch (fileName.toLowerCase().split('.').last) { + case 'jpg': + case 'jpeg': + return 'image/jpeg'; + case 'png': + return 'image/png'; + case 'gif': + return 'image/gif'; + case 'webp': + return 'image/webp'; + case 'heic': + return 'image/heic'; + default: + return 'application/octet-stream'; + } + } + + static Future uploadImageWithSettings({ + required AppSettings settings, + required Uint8List bytes, + required String fileName, + required String mimeType, + }) { + return uploadImage( + bytes: bytes, + fileName: fileName, + mimeType: mimeType, + uploadEndpoint: settings.uploadIpfsEndpoint, + uploadApiKey: settings.uploadIpfsApiKey, + uploadGateway: settings.uploadIpfsGateway, + ); + } + + static Future uploadImage({ + required Uint8List bytes, + required String fileName, + required String mimeType, + required String uploadEndpoint, + required String uploadApiKey, + String uploadGateway = '', + }) async { + final endpoint = uploadEndpoint.trim(); + if (endpoint.isEmpty) { + throw ArgumentError('Configure an IPFS upload endpoint first.'); + } + + final token = uploadApiKey.trim(); + final endpointUri = Uri.parse(endpoint); + final endpointHost = endpointUri.host.toLowerCase(); + final isPinata = + endpointHost.contains('pinata') || + endpoint.toLowerCase().contains('pinfiletoipfs'); + final isFilebase = endpointHost.contains('filebase'); + final isKubo = !isPinata && !isFilebase; + final safeFileName = _sanitizeUploadFileName(fileName); + if (isFilebase && token.isEmpty) { + throw ArgumentError('Filebase RPC requires an API token.'); + } + + final Uri uploadUri; + final request = http.MultipartRequest('POST', endpointUri) + ..files.add( + http.MultipartFile.fromBytes('file', bytes, filename: safeFileName), + ); + + if (isPinata) { + if (token.isEmpty) { + throw ArgumentError('Pinata requires an API key or JWT.'); + } + request.headers['Authorization'] = 'Bearer $token'; + request.fields['pinataOptions'] = jsonEncode({'cidVersion': 1}); + request.fields['pinataMetadata'] = jsonEncode({'name': safeFileName}); + uploadUri = endpointUri; + } else { + final parameters = {'cid-version': '1'}; + if (isKubo) parameters['pin'] = 'true'; + uploadUri = endpointUri.replace( + queryParameters: {...endpointUri.queryParameters, ...parameters}, + ); + if (token.isNotEmpty) { + request.headers['Authorization'] = 'Bearer $token'; + } + } + + final finalRequest = request.url == uploadUri + ? request + : (http.MultipartRequest('POST', uploadUri) + ..headers.addAll(request.headers) + ..fields.addAll(request.fields) + ..files.addAll(request.files)); + final client = httpClient; + final response = await (client == null + ? finalRequest.send() + : client.send(finalRequest)); + final body = await response.stream.bytesToString(); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw Exception('IPFS upload failed (${response.statusCode}): $body'); + } + + final cid = _extractUploadCid(body, isPinata: isPinata); + if (cid == null || cid.isEmpty) { + throw Exception('IPFS upload did not return a CID.'); + } + + if (isKubo) { + await _copyKuboFileToMfs( + endpoint: endpoint, + cid: cid, + fileName: safeFileName, + authorization: token.isEmpty ? null : 'Bearer $token', + ); + } + + final gateway = normalizeIpfsGateway(uploadGateway); + return gateway.isEmpty ? 'ipfs://$cid' : '$gateway$cid'; + } + + static Future _copyKuboFileToMfs({ + required String endpoint, + required String cid, + required String fileName, + required String? authorization, + }) async { + final uploadUri = Uri.parse(endpoint); + final copyPath = uploadUri.path.replaceFirst( + RegExp(r'/add/?$'), + '/files/cp', + ); + if (copyPath == uploadUri.path) { + throw ArgumentError('Kubo upload endpoint must end with /add.'); + } + + final mfsPath = '/meshcore_uploads/$cid-$fileName'; + final copyUri = uploadUri.replace( + path: copyPath, + query: + 'arg=${Uri.encodeQueryComponent('/ipfs/$cid')}' + '&arg=${Uri.encodeQueryComponent(mfsPath)}&parents=true', + ); + final headers = authorization == null + ? {} + : {'Authorization': authorization}; + final client = httpClient; + final response = await (client == null + ? http.post(copyUri, headers: headers) + : client.post(copyUri, headers: headers)); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw Exception( + 'Kubo MFS import failed (${response.statusCode}): ${response.body}', + ); + } + } + + static String _sanitizeUploadFileName(String name) { + final cleaned = name.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_').trim(); + return cleaned.isEmpty ? 'shared-image' : cleaned; + } + + static String? _extractUploadCid(String body, {required bool isPinata}) { + final lines = const LineSplitter() + .convert(body) + .where((line) => line.trim().isNotEmpty) + .toList(); + for (final line in lines.reversed) { + try { + final decoded = jsonDecode(line); + if (decoded is! Map) continue; + final value = isPinata ? decoded['IpfsHash'] : decoded['Hash']; + if (value is String && value.isNotEmpty) return value; + } catch (_) { + continue; + } + } + return null; + } +} diff --git a/lib/helpers/message_url_image_helper.dart b/lib/helpers/message_url_image_helper.dart index 3f2a7835..30eb4e2f 100644 --- a/lib/helpers/message_url_image_helper.dart +++ b/lib/helpers/message_url_image_helper.dart @@ -1,10 +1,14 @@ import 'dart:async'; import 'dart:collection'; +import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:http/http.dart' as http; +import 'ipfs_upload_helper.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 @@ -22,6 +26,41 @@ class MessageUrlImageHelper { @visibleForTesting static http.Client? httpClient; + /// Compatibility facade for the dedicated IPFS upload helper. + static Future uploadImageWithSettings({ + required AppSettings settings, + required Uint8List bytes, + required String fileName, + required String mimeType, + }) { + IpfsUploadHelper.httpClient = httpClient; + return IpfsUploadHelper.uploadImageWithSettings( + settings: settings, + bytes: bytes, + fileName: fileName, + mimeType: mimeType, + ); + } + + static Future uploadImage({ + required Uint8List bytes, + required String fileName, + required String mimeType, + required String uploadEndpoint, + required String uploadApiKey, + String uploadGateway = '', + }) async { + IpfsUploadHelper.httpClient = httpClient; + return IpfsUploadHelper.uploadImage( + bytes: bytes, + fileName: fileName, + mimeType: mimeType, + uploadEndpoint: uploadEndpoint, + uploadApiKey: uploadApiKey, + uploadGateway: uploadGateway, + ); + } + static final RegExp _pyxPattern = RegExp( r'''https?://pyx\.li/\?i=([A-Za-z0-9_-]+)''', caseSensitive: false, @@ -57,7 +96,10 @@ class MessageUrlImageHelper { _imagePattern.hasMatch(text); } - static Future parse(String text) async { + static Future parse( + String text, { + String publicGateway = AppSettings.defaultPublicIpfsGateway, + }) async { final trimmed = text.trim(); if (trimmed.isEmpty) return null; @@ -74,7 +116,9 @@ class MessageUrlImageHelper { final ipfsCidMatch = _ipfsCidPattern.firstMatch(trimmed); if (ipfsCidMatch != null) { final cid = _trimBoundary(ipfsCidMatch.group(1)!); - return 'https://ipfs.io/ipfs/$cid'; + final gateway = normalizeIpfsGateway(publicGateway); + if (gateway.isEmpty) return null; + return '$gateway$cid'; } final ibbMatch = _ibbSharePattern.firstMatch(trimmed); @@ -96,8 +140,11 @@ class MessageUrlImageHelper { return null; } - static Future parseVerified(String text) async { - final imageUrl = await parse(text); + static Future 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); @@ -110,20 +157,22 @@ class MessageUrlImageHelper { /// be retried when a message is shown again. static Future parseVerifiedForMessage( String messageId, - String text, - ) { - final cached = _messageImageCache.remove(messageId); + String text, { + String publicGateway = AppSettings.defaultPublicIpfsGateway, + }) { + final cacheKey = '$messageId|$publicGateway'; + final cached = _messageImageCache.remove(cacheKey); if (cached != null) { - _messageImageCache[messageId] = cached; + _messageImageCache[cacheKey] = cached; return cached; } - final parsing = parseVerified(text); - _messageImageCache[messageId] = parsing; + final parsing = parseVerified(text, publicGateway: publicGateway); + _messageImageCache[cacheKey] = parsing; parsing.then((imageUrl) { if (imageUrl == null && - identical(_messageImageCache[messageId], parsing)) { - _messageImageCache.remove(messageId); + identical(_messageImageCache[cacheKey], parsing)) { + _messageImageCache.remove(cacheKey); } else if (imageUrl != null) { while (_messageImageCache.length > _maxMessageImageCacheEntries) { _messageImageCache.remove(_messageImageCache.keys.first); @@ -207,11 +256,13 @@ class MessageUrlImageFutureBuilder extends StatefulWidget { 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 builder; @override @@ -229,6 +280,7 @@ class _MessageUrlImageFutureBuilderState _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( widget.messageId, widget.text, + publicGateway: widget.publicGateway, ); } @@ -239,6 +291,13 @@ class _MessageUrlImageFutureBuilderState _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( widget.messageId, widget.text, + publicGateway: widget.publicGateway, + ); + } else if (oldWidget.publicGateway != widget.publicGateway) { + _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( + widget.messageId, + widget.text, + publicGateway: widget.publicGateway, ); } } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index caa51590..a30412c9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -448,6 +448,20 @@ "appSettings_routeWeightFailureDecrementSubtitle": "Weight removed from a path after failed delivery", "appSettings_maxMessageRetries": "Max Message Retries", "appSettings_maxMessageRetriesSubtitle": "Number of retry attempts before marking a message as failed", + "appSettings_ipfsImageLinks": "IPFS provider configuration", + "appSettings_ipfsImageLinksSubtitle": "Upload for url Images (or Files) via IPFS provider and default gateway to receive", + "appSettings_publicIpfsGateway": "Public gateway", + "appSettings_ipfsGatewayDeactivated": "Deactivated", + "appSettings_ipfsGatewayPinata": "Pinata", + "appSettings_ipfsGatewayFilebase": "Filebase", + "appSettings_ipfsGatewayCustom": "Custom (Kubo)", + "appSettings_uploadIpfsProvider": "Upload provider", + "appSettings_uploadIpfsGateway": "Upload gateway", + "appSettings_uploadIpfsGatewaySubtitle": "Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.", + "appSettings_uploadIpfsEndpoint": "Upload endpoint", + "appSettings_uploadIpfsEndpointSubtitle": "The API endpoint used to upload files", + "appSettings_uploadIpfsApiKey": "Upload API key", + "appSettings_ipfsImageLinksDescription": "Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.", "appSettings_battery": "Battery", "appSettings_batteryChemistry": "Battery Chemistry", "appSettings_batteryChemistryPerDevice": "Set per device ({deviceName})", @@ -910,6 +924,16 @@ "chat_removeGif": "Remove GIF", "chat_cancelReply": "Cancel reply", "chat_sendImageLora": "Send low-res image over radio", + "chat_sendImageIpfs": "Send image or file via IPFS", + "chat_ipfsUploadFailed": "IPFS upload failed: {error}", + "@chat_ipfsUploadFailed": { + "placeholders": { + "error": { + "type": "String" + } + } + }, + "chat_ipfsUploadNotConfigured": "Configure an IPFS upload provider in App Settings first.", "chat_imagePickFailed": "Couldn't open that image", "@chat_imagePickFailed": { "description": "Shown when picking or reading a photo to send fails" diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 4b1af121..4f1b928a 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -1924,6 +1924,90 @@ abstract class AppLocalizations { /// **'Number of retry attempts before marking a message as failed'** String get appSettings_maxMessageRetriesSubtitle; + /// No description provided for @appSettings_ipfsImageLinks. + /// + /// In en, this message translates to: + /// **'IPFS provider configuration'** + String get appSettings_ipfsImageLinks; + + /// No description provided for @appSettings_ipfsImageLinksSubtitle. + /// + /// In en, this message translates to: + /// **'Upload for url Images (or Files) via IPFS provider and default gateway to receive'** + String get appSettings_ipfsImageLinksSubtitle; + + /// No description provided for @appSettings_publicIpfsGateway. + /// + /// In en, this message translates to: + /// **'Public gateway'** + String get appSettings_publicIpfsGateway; + + /// No description provided for @appSettings_ipfsGatewayDeactivated. + /// + /// In en, this message translates to: + /// **'Deactivated'** + String get appSettings_ipfsGatewayDeactivated; + + /// No description provided for @appSettings_ipfsGatewayPinata. + /// + /// In en, this message translates to: + /// **'Pinata'** + String get appSettings_ipfsGatewayPinata; + + /// No description provided for @appSettings_ipfsGatewayFilebase. + /// + /// In en, this message translates to: + /// **'Filebase'** + String get appSettings_ipfsGatewayFilebase; + + /// No description provided for @appSettings_ipfsGatewayCustom. + /// + /// In en, this message translates to: + /// **'Custom (Kubo)'** + String get appSettings_ipfsGatewayCustom; + + /// No description provided for @appSettings_uploadIpfsProvider. + /// + /// In en, this message translates to: + /// **'Upload provider'** + String get appSettings_uploadIpfsProvider; + + /// No description provided for @appSettings_uploadIpfsGateway. + /// + /// In en, this message translates to: + /// **'Upload gateway'** + String get appSettings_uploadIpfsGateway; + + /// No description provided for @appSettings_uploadIpfsGatewaySubtitle. + /// + /// In en, this message translates to: + /// **'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'** + String get appSettings_uploadIpfsGatewaySubtitle; + + /// No description provided for @appSettings_uploadIpfsEndpoint. + /// + /// In en, this message translates to: + /// **'Upload endpoint'** + String get appSettings_uploadIpfsEndpoint; + + /// No description provided for @appSettings_uploadIpfsEndpointSubtitle. + /// + /// In en, this message translates to: + /// **'The API endpoint used to upload files'** + String get appSettings_uploadIpfsEndpointSubtitle; + + /// No description provided for @appSettings_uploadIpfsApiKey. + /// + /// In en, this message translates to: + /// **'Upload API key'** + String get appSettings_uploadIpfsApiKey; + + /// No description provided for @appSettings_ipfsImageLinksDescription. + /// + /// In en, this message translates to: + /// **'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'** + String get appSettings_ipfsImageLinksDescription; + /// No description provided for @appSettings_battery. /// /// In en, this message translates to: @@ -3112,6 +3196,24 @@ abstract class AppLocalizations { /// **'Send low-res image over radio'** String get chat_sendImageLora; + /// No description provided for @chat_sendImageIpfs. + /// + /// In en, this message translates to: + /// **'Send image or file via IPFS'** + String get chat_sendImageIpfs; + + /// No description provided for @chat_ipfsUploadFailed. + /// + /// In en, this message translates to: + /// **'IPFS upload failed: {error}'** + String chat_ipfsUploadFailed(String error); + + /// No description provided for @chat_ipfsUploadNotConfigured. + /// + /// In en, this message translates to: + /// **'Configure an IPFS upload provider in App Settings first.'** + String get chat_ipfsUploadNotConfigured; + /// Shown when picking or reading a photo to send fails /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index bb999a01..2cf51388 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1058,6 +1058,52 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Брой опити за повторно изпращане, преди съобщението да бъде маркирано като неуспешно.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Батерия'; @@ -1749,6 +1795,18 @@ class AppLocalizationsBg extends AppLocalizations { @override String get chat_sendImageLora => 'Изпращане на изображение чрез MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Не мог да откривам та изображин'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 7c099a2a..4917478d 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1053,6 +1053,52 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Anzahl der Versuche, eine Nachricht erneut zu senden, bevor sie als fehlgeschlagen markiert wird.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Akku'; @@ -1748,6 +1794,18 @@ class AppLocalizationsDe extends AppLocalizations { @override String get chat_sendImageLora => 'Bild über MeshCore senden'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Konnte dieses Bild nicht öffnen.'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index ce4fc6cc..3fb9d784 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1037,6 +1037,52 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Number of retry attempts before marking a message as failed'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Battery'; @@ -1717,6 +1763,18 @@ class AppLocalizationsEn extends AppLocalizations { @override String get chat_sendImageLora => 'Send low-res image over radio'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Couldn\'t open that image'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 21d23fdd..c67dda31 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1050,6 +1050,52 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Número de intentos de reintento antes de marcar un mensaje como fallido.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batería'; @@ -1744,6 +1790,18 @@ class AppLocalizationsEs extends AppLocalizations { @override String get chat_sendImageLora => 'Enviar imagen mediante MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'No pude abrir esa imagen'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 94a4133f..3c78016c 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1056,6 +1056,52 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Nombre de tentatives avant de marquer un message comme ayant échoué.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batterie'; @@ -1748,6 +1794,18 @@ class AppLocalizationsFr extends AppLocalizations { @override String get chat_sendImageLora => 'Envoyer une image via MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Je n\'ai pas pu ouvrir cette image'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index d02c4227..59442375 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1045,6 +1045,52 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Az üzenet sikertelenként való megjelölése előtti újrapróbálkozások száma'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Akkumulátor'; @@ -1738,6 +1784,18 @@ class AppLocalizationsHu extends AppLocalizations { @override String get chat_sendImageLora => 'Kép küldése MeshCore-on keresztül'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Nem tudtam ezt a fenti fényre kapni'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 877c0975..881a1b64 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1056,6 +1056,52 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Numero di tentativi di riprova prima di considerare un messaggio come fallito.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batteria'; @@ -1748,6 +1794,18 @@ class AppLocalizationsIt extends AppLocalizations { @override String get chat_sendImageLora => 'Invia immagine tramite MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Non sono riuscito ad aprire quell\'immagine'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 240eea50..7d745b3b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -993,6 +993,52 @@ class AppLocalizationsJa extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => 'メッセージを失敗として扱うまでの再試行回数'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'バッテリー'; @@ -1661,6 +1707,18 @@ class AppLocalizationsJa extends AppLocalizations { @override String get chat_sendImageLora => 'MeshCore経由で画像を送信'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'その画像を開けませんでした'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index d4b9be2d..f6a74b65 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -997,6 +997,52 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => '메시지를 실패로 처리하기 전 시도 횟수'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => '배터리'; @@ -1666,6 +1712,18 @@ class AppLocalizationsKo extends AppLocalizations { @override String get chat_sendImageLora => 'MeshCore를 통해 이미지 보내기'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => '그 이미지를 열 수 없었어요.'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index db418ab4..4b65ca26 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1046,6 +1046,52 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Aantal pogingen om een bericht opnieuw te versturen voordat het als mislukt wordt gemarkeerd'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batterij'; @@ -1734,6 +1780,18 @@ class AppLocalizationsNl extends AppLocalizations { String get chat_sendImageLora => 'Afbeelding in lage resolutie via radio verzenden'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Kon die afbeelding niet openen'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index a1959873..c9864fd0 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1062,6 +1062,52 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Liczba prób ponownego wysłania wiadomości przed oznaczaniem jej jako nieudanej'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Bateria'; @@ -1763,6 +1809,18 @@ class AppLocalizationsPl extends AppLocalizations { @override String get chat_sendImageLora => 'Wyślij obraz przez MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Nie mogłem otworzyć tego obrazu'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index bab9270c..c0954bfe 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1054,6 +1054,52 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Número de tentativas de reenvio antes de classificar uma mensagem como falha.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Bateria'; @@ -1744,6 +1790,18 @@ class AppLocalizationsPt extends AppLocalizations { @override String get chat_sendImageLora => 'Enviar imagem via MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Não consegui abrir essa imagem'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 4882c690..756e3276 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1059,6 +1059,52 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Количество попыток повторной отправки сообщения перед тем, как пометить его как неудачное.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Батарея'; @@ -1748,6 +1794,18 @@ class AppLocalizationsRu extends AppLocalizations { @override String get chat_sendImageLora => 'Отправить изображение через MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Не удалось открыть это изображение'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 72213043..b86d8563 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1045,6 +1045,52 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Počet pokusov o odošleť pred označením správy ako neúspešnej'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batéria'; @@ -1736,6 +1782,18 @@ class AppLocalizationsSk extends AppLocalizations { @override String get chat_sendImageLora => 'Odoslať obrázok cez MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Nesmiela jsem otvoriť tento obrázok'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index d84d6857..423a51c3 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1047,6 +1047,52 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Število poskusov ponovnega poslanja, preden se sporočilo označuje kot neuspešno'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Baterija'; @@ -1735,6 +1781,18 @@ class AppLocalizationsSl extends AppLocalizations { @override String get chat_sendImageLora => 'Pošlji sliko prek MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Nispeval sem tega ta slik'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index c760c91f..70ed34eb 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1036,6 +1036,52 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Antal försök att skicka om ett meddelande innan det markeras som misslyckat.'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Batteri'; @@ -1723,6 +1769,18 @@ class AppLocalizationsSv extends AppLocalizations { @override String get chat_sendImageLora => 'Skicka bild via MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Kunde inte öppna bilden'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 72ef4c94..194fffc5 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1049,6 +1049,52 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_maxMessageRetriesSubtitle => 'Кількість спроб повторного відправлення повідомлення перед тим, як позначити його як невдале'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => 'Батарея'; @@ -1738,6 +1784,18 @@ class AppLocalizationsUk extends AppLocalizations { @override String get chat_sendImageLora => 'Надіслати зображення через MeshCore'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => 'Неможливо відкрити це изображення'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 88df6c9c..46ffc0ba 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -979,6 +979,52 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_maxMessageRetriesSubtitle => '在将消息标记为失败之前,允许尝试的次数'; + @override + String get appSettings_ipfsImageLinks => 'IPFS provider configuration'; + + @override + String get appSettings_ipfsImageLinksSubtitle => + 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + + @override + String get appSettings_publicIpfsGateway => 'Public gateway'; + + @override + String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + + @override + String get appSettings_ipfsGatewayPinata => 'Pinata'; + + @override + String get appSettings_ipfsGatewayFilebase => 'Filebase'; + + @override + String get appSettings_ipfsGatewayCustom => 'Custom (Kubo)'; + + @override + String get appSettings_uploadIpfsProvider => 'Upload provider'; + + @override + String get appSettings_uploadIpfsGateway => 'Upload gateway'; + + @override + String get appSettings_uploadIpfsGatewaySubtitle => + 'Gateway to share Image or File as url-link. Leave empty to use ipfs: format, which may not be opened by other clients.'; + + @override + String get appSettings_uploadIpfsEndpoint => 'Upload endpoint'; + + @override + String get appSettings_uploadIpfsEndpointSubtitle => + 'The API endpoint used to upload files'; + + @override + String get appSettings_uploadIpfsApiKey => 'Upload API key'; + + @override + String get appSettings_ipfsImageLinksDescription => + 'Public gateway downloads ipfs: format images. Upload gateway is used to generate share links for uploaded url images or files.'; + @override String get appSettings_battery => '电池'; @@ -1643,6 +1689,18 @@ class AppLocalizationsZh extends AppLocalizations { @override String get chat_sendImageLora => '通过 MeshCore 发送图片'; + @override + String get chat_sendImageIpfs => 'Send image or file via IPFS'; + + @override + String chat_ipfsUploadFailed(String error) { + return 'IPFS upload failed: $error'; + } + + @override + String get chat_ipfsUploadNotConfigured => + 'Configure an IPFS upload provider in App Settings first.'; + @override String get chat_imagePickFailed => '无法打开该图片'; diff --git a/lib/main.dart b/lib/main.dart index f5f54751..02550f25 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -132,6 +132,14 @@ void main() async { // Initialize notification service final notificationService = NotificationService(); + notificationService.setPublicIpfsGateway( + appSettingsService.settings.publicIpfsGateway, + ); + appSettingsService.addListener(() { + notificationService.setPublicIpfsGateway( + appSettingsService.settings.publicIpfsGateway, + ); + }); await notificationService.initialize(); await backgroundService.initialize(); backgroundService.setLanguageOverrideProvider( diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index ef954f28..99ef609a 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -3,6 +3,32 @@ import 'translation_support.dart'; enum UnitSystem { metric, imperial } +String normalizeIpfsGateway(String value) { + var gateway = value.trim(); + if (gateway.isEmpty) return gateway; + if (!gateway.startsWith('http://') && !gateway.startsWith('https://')) { + gateway = 'https://$gateway'; + } + gateway = gateway.replaceAll('{cid}', ''); + if (gateway.endsWith('/ipfs')) gateway = '$gateway/'; + if (!gateway.endsWith('/ipfs/')) { + gateway = '${gateway.endsWith('/') ? gateway : '$gateway/'}ipfs/'; + } + return gateway; +} + +String migratePublicIpfsGateway(String? value) { + final gateway = value?.trim(); + if (gateway == null || + gateway == 'https://ipfs.io/ipfs/' || + gateway == 'https://ipfs.io/ipfs' || + gateway == 'https://dweb.link/ipfs/' || + gateway == 'https://dweb.link/ipfs') { + return AppSettings.defaultPublicIpfsGateway; + } + return gateway; +} + extension UnitSystemValue on UnitSystem { String get value { switch (this) { @@ -78,6 +104,7 @@ class Cyr2LatProfile { class AppSettings { static const Object _unset = Object(); static const String stadiaDemo = '51bd0381-4685-4666-bae8-48940f6d77c0'; + static const String defaultPublicIpfsGateway = ''; final bool clearPathOnMaxRetry; final bool mapShowRepeaters; @@ -130,6 +157,10 @@ class AppSettings { final int tcpServerPort; final bool jumpToOldestUnread; final bool imageMessagesEnabled; + final String publicIpfsGateway; + final String uploadIpfsGateway; + final String uploadIpfsEndpoint; + final String uploadIpfsApiKey; /// Whether a received image is decoded as soon as it is reassembled. /// @@ -180,6 +211,10 @@ class AppSettings { return apiKey; } + String get effectiveUploadIpfsGateway { + return uploadIpfsGateway.trim(); + } + bool get usesstadiaDemo => effectiveMapTileApiKey == stadiaDemo; Map get cyr2latCharMap { @@ -239,6 +274,10 @@ class AppSettings { this.tcpServerPort = 0, this.jumpToOldestUnread = false, this.imageMessagesEnabled = false, + this.publicIpfsGateway = defaultPublicIpfsGateway, + this.uploadIpfsGateway = '', + this.uploadIpfsEndpoint = '', + this.uploadIpfsApiKey = '', this.imageProcessAutomatically = false, this.imageCodecEnabled = false, this.imageCodecSelectedModelId, @@ -321,6 +360,10 @@ class AppSettings { 'tcp_server_port': tcpServerPort, 'jump_to_oldest_unread': jumpToOldestUnread, 'image_messages_enabled': imageMessagesEnabled, + 'public_ipfs_gateway': publicIpfsGateway, + 'upload_ipfs_gateway': uploadIpfsGateway, + 'upload_ipfs_endpoint': uploadIpfsEndpoint, + 'upload_ipfs_api_key': uploadIpfsApiKey, 'image_process_automatically': imageProcessAutomatically, 'image_codec_enabled': imageCodecEnabled, 'image_codec_selected_model_id': imageCodecSelectedModelId, @@ -428,6 +471,12 @@ class AppSettings { tcpServerPort: json['tcp_server_port'] as int? ?? 0, jumpToOldestUnread: json['jump_to_oldest_unread'] as bool? ?? false, imageMessagesEnabled: json['image_messages_enabled'] as bool? ?? false, + publicIpfsGateway: migratePublicIpfsGateway( + json['public_ipfs_gateway'] as String?, + ), + uploadIpfsGateway: json['upload_ipfs_gateway'] as String? ?? '', + uploadIpfsEndpoint: json['upload_ipfs_endpoint'] as String? ?? '', + uploadIpfsApiKey: json['upload_ipfs_api_key'] as String? ?? '', imageProcessAutomatically: json['image_process_automatically'] as bool? ?? false, imageCodecEnabled: json['image_codec_enabled'] as bool? ?? false, @@ -548,6 +597,10 @@ class AppSettings { int? tcpServerPort, bool? jumpToOldestUnread, bool? imageMessagesEnabled, + String? publicIpfsGateway, + String? uploadIpfsGateway, + String? uploadIpfsEndpoint, + String? uploadIpfsApiKey, bool? imageProcessAutomatically, bool? imageCodecEnabled, Object? imageCodecSelectedModelId = _unset, @@ -633,6 +686,10 @@ class AppSettings { tcpServerPort: tcpServerPort ?? this.tcpServerPort, jumpToOldestUnread: jumpToOldestUnread ?? this.jumpToOldestUnread, imageMessagesEnabled: imageMessagesEnabled ?? this.imageMessagesEnabled, + publicIpfsGateway: publicIpfsGateway ?? this.publicIpfsGateway, + uploadIpfsGateway: uploadIpfsGateway ?? this.uploadIpfsGateway, + uploadIpfsEndpoint: uploadIpfsEndpoint ?? this.uploadIpfsEndpoint, + uploadIpfsApiKey: uploadIpfsApiKey ?? this.uploadIpfsApiKey, imageProcessAutomatically: imageProcessAutomatically ?? this.imageProcessAutomatically, imageCodecEnabled: imageCodecEnabled ?? this.imageCodecEnabled, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index d32a443b..64325ac4 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -701,6 +701,18 @@ class AppSettingsScreen extends StatelessWidget { ), ], const Divider(height: 1, indent: 16), + ListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + leading: const Icon(Icons.link_outlined, size: 20), + title: Text(context.l10n.appSettings_ipfsImageLinks), + subtitle: Text(context.l10n.appSettings_ipfsImageLinksSubtitle), + trailing: const Icon(Icons.chevron_right, size: 18), + onTap: () => _showIpfsImageLinksDialog(context, settingsService), + ), + const Divider(height: 1, indent: 16), _ScrollIntoViewOnce( enabled: focusImageMessages, child: SwitchListTile( @@ -723,7 +735,6 @@ class AppSettingsScreen extends StatelessWidget { ), ), if (settingsService.settings.imageMessagesEnabled) ...[ - const Divider(height: 1, indent: 16), SwitchListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, @@ -751,6 +762,16 @@ class AppSettingsScreen extends StatelessWidget { } } + void _showIpfsImageLinksDialog( + BuildContext context, + AppSettingsService settingsService, + ) { + showDialog( + context: context, + builder: (_) => _IpfsImageLinksDialog(settingsService: settingsService), + ); + } + /// Model registry for image messages: the download entry point, the /// downloaded weights, and — when the build simply cannot run the codec — /// [ImageCodecService.unavailableReason] instead of a dead download button. @@ -2649,6 +2670,311 @@ class AppSettingsScreen extends StatelessWidget { } } +class _IpfsImageLinksDialog extends StatefulWidget { + const _IpfsImageLinksDialog({required this.settingsService}); + + final AppSettingsService settingsService; + + @override + State<_IpfsImageLinksDialog> createState() => _IpfsImageLinksDialogState(); +} + +class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { + late final TextEditingController _publicController; + late final TextEditingController _uploadGatewayController; + late final TextEditingController _endpointController; + late final TextEditingController _apiKeyController; + late final String _currentApiKey; + late final String _maskedApiKey; + late String _selectedGateway; + late String _selectedUploadProvider; + bool _apiKeyEditing = false; + bool _apiKeyChanged = false; + + @override + void initState() { + super.initState(); + final settings = widget.settingsService.settings; + _publicController = TextEditingController( + text: normalizeIpfsGateway(settings.publicIpfsGateway), + ); + _uploadGatewayController = TextEditingController( + text: normalizeIpfsGateway(settings.uploadIpfsGateway), + ); + _endpointController = TextEditingController( + text: settings.uploadIpfsEndpoint, + ); + _currentApiKey = settings.uploadIpfsApiKey.trim(); + _maskedApiKey = _currentApiKey.isEmpty ? '' : _maskApiKey(_currentApiKey); + _apiKeyController = TextEditingController(text: _maskedApiKey); + _selectedGateway = _gatewayPreset(_publicController.text); + _selectedUploadProvider = _uploadProvider( + _uploadGatewayController.text, + _endpointController.text, + _currentApiKey, + ); + } + + @override + void dispose() { + _publicController.dispose(); + _uploadGatewayController.dispose(); + _endpointController.dispose(); + _apiKeyController.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return AlertDialog( + title: Text(l10n.appSettings_ipfsImageLinks), + content: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(l10n.appSettings_ipfsImageLinksDescription), + const SizedBox(height: 12), + DropdownButtonFormField( + initialValue: _selectedGateway, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.appSettings_publicIpfsGateway, + ), + items: [ + DropdownMenuItem( + value: 'deactivated', + child: Text(l10n.appSettings_ipfsGatewayDeactivated), + ), + DropdownMenuItem( + value: 'pinata', + child: Text(l10n.appSettings_ipfsGatewayPinata), + ), + DropdownMenuItem( + value: 'filebase', + child: Text(l10n.appSettings_ipfsGatewayFilebase), + ), + DropdownMenuItem( + value: 'custom', + child: Text(l10n.appSettings_ipfsGatewayCustom), + ), + ], + onChanged: _selectGateway, + ), + const SizedBox(height: 10), + TextField( + controller: _publicController, + decoration: InputDecoration( + labelText: l10n.appSettings_publicIpfsGateway, + ), + keyboardType: TextInputType.url, + autocorrect: false, + onChanged: (_) { + if (_selectedGateway != 'custom') { + setState(() => _selectedGateway = 'custom'); + } + }, + ), + const Divider(height: 20), + DropdownButtonFormField( + initialValue: _selectedUploadProvider, + isExpanded: true, + decoration: InputDecoration( + labelText: l10n.appSettings_uploadIpfsProvider, + ), + items: [ + DropdownMenuItem( + value: 'pinata', + child: Text(l10n.appSettings_ipfsGatewayPinata), + ), + DropdownMenuItem( + value: 'filebase', + child: Text(l10n.appSettings_ipfsGatewayFilebase), + ), + DropdownMenuItem( + value: 'custom', + child: Text(l10n.appSettings_ipfsGatewayCustom), + ), + DropdownMenuItem( + value: 'deactivated', + child: Text(l10n.appSettings_ipfsGatewayDeactivated), + ), + ], + onChanged: _selectUploadProvider, + ), + const SizedBox(height: 10), + TextField( + controller: _uploadGatewayController, + decoration: InputDecoration( + labelText: l10n.appSettings_uploadIpfsGateway, + helperText: l10n.appSettings_uploadIpfsGatewaySubtitle, + helperMaxLines: 3, + ), + keyboardType: TextInputType.url, + autocorrect: false, + onChanged: (_) => _markCustomUploadProvider(), + ), + const SizedBox(height: 10), + TextField( + controller: _endpointController, + decoration: InputDecoration( + labelText: l10n.appSettings_uploadIpfsEndpoint, + helperText: l10n.appSettings_uploadIpfsEndpointSubtitle, + helperMaxLines: 3, + ), + keyboardType: TextInputType.url, + autocorrect: false, + onChanged: (_) => _markCustomUploadProvider(), + ), + const SizedBox(height: 10), + TextField( + controller: _apiKeyController, + decoration: InputDecoration( + labelText: l10n.appSettings_uploadIpfsApiKey, + ), + autocorrect: false, + enableSuggestions: false, + onTap: () { + if (_apiKeyEditing) return; + setState(() { + _apiKeyEditing = true; + _apiKeyController.clear(); + }); + }, + onChanged: (_) { + _apiKeyChanged = true; + _markCustomUploadProvider(); + }, + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(l10n.common_cancel), + ), + TextButton(onPressed: _save, child: Text(l10n.common_save)), + ], + ); + } + + void _selectGateway(String? value) { + if (value == null) return; + setState(() { + _selectedGateway = value; + final preset = _gatewayValue(value); + if (preset != null) _publicController.text = preset; + }); + } + + void _selectUploadProvider(String? value) { + if (value == null) return; + setState(() { + _selectedUploadProvider = value; + final preset = _uploadPreset(value); + if (preset != null) { + _uploadGatewayController.text = preset.gateway; + _endpointController.text = preset.endpoint; + if (value == 'deactivated') _apiKeyController.clear(); + } + }); + } + + void _markCustomUploadProvider() { + if (_selectedUploadProvider != 'custom') { + setState(() => _selectedUploadProvider = 'custom'); + } + } + + Future _save() async { + final deactivated = _selectedUploadProvider == 'deactivated'; + await widget.settingsService.setIpfsImageSettings( + publicGateway: _publicController.text, + uploadGateway: deactivated ? '' : _uploadGatewayController.text, + uploadEndpoint: deactivated ? '' : _endpointController.text, + uploadApiKey: deactivated + ? '' + : _apiKeyChanged + ? _apiKeyController.text + : _currentApiKey, + ); + if (mounted) Navigator.pop(context); + } + + String _gatewayPreset(String value) { + if (value.isEmpty) return 'deactivated'; + if (value == 'https://gateway.pinata.cloud/ipfs/' || + value == 'https://gateway.pinata.cloud/ipfs') { + return 'pinata'; + } + if (value == 'https://ipfs.filebase.io/ipfs/' || + value == 'https://ipfs.filebase.io/ipfs') { + return 'filebase'; + } + return 'custom'; + } + + String? _gatewayValue(String preset) { + switch (preset) { + case 'deactivated': + return ''; + case 'pinata': + return 'https://gateway.pinata.cloud/ipfs/'; + case 'filebase': + return 'https://ipfs.filebase.io/ipfs/'; + case 'custom': + return 'http://127.0.0.1:8080/ipfs/'; + default: + return null; + } + } + + String _uploadProvider(String gateway, String endpoint, String apiKey) { + if (gateway.isEmpty && endpoint.isEmpty && apiKey.isEmpty) { + return 'deactivated'; + } + if (gateway == 'https://gateway.pinata.cloud/ipfs/' && + endpoint == 'https://api.pinata.cloud/pinning/pinFileToIPFS') { + return 'pinata'; + } + if (gateway == 'https://ipfs.filebase.io/ipfs/' && + endpoint == 'https://rpc.filebase.io/api/v0/add') { + return 'filebase'; + } + return 'custom'; + } + + ({String gateway, String endpoint})? _uploadPreset(String preset) { + switch (preset) { + case 'pinata': + return ( + gateway: 'https://gateway.pinata.cloud/ipfs/', + endpoint: 'https://api.pinata.cloud/pinning/pinFileToIPFS', + ); + case 'filebase': + return ( + gateway: 'https://ipfs.filebase.io/ipfs/', + endpoint: 'https://rpc.filebase.io/api/v0/add', + ); + case 'custom': + return ( + gateway: 'http://127.0.0.1:8080/ipfs/', + endpoint: 'http://127.0.0.1:5001/api/v0/add', + ); + case 'deactivated': + return (gateway: '', endpoint: ''); + default: + return null; + } + } + + String _maskApiKey(String value) { + if (value.length <= 8) return '********'; + return '${value.substring(0, 4)}...${value.substring(value.length - 4)}'; + } +} + /// Owns the [TextEditingController] for the manual model URL field so it /// survives rebuilds of the parent [Consumer3]. class _TranslationUrlField extends StatefulWidget { diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 7f592dd5..3ec9a4bd 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -6,6 +6,7 @@ import 'dart:ui' as ui; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; +import 'package:file_selector/file_selector.dart' as file_selector; import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; @@ -18,6 +19,7 @@ import '../helpers/chat_scroll_controller.dart'; import '../connector/meshcore_protocol.dart'; import '../helpers/cyr2lat.dart'; import '../helpers/gif_helper.dart'; +import '../helpers/ipfs_upload_helper.dart'; import '../helpers/message_url_image_helper.dart'; import '../helpers/path_helper.dart'; import '../helpers/reaction_helper.dart'; @@ -40,7 +42,6 @@ import '../widgets/received_image_message.dart'; import '../widgets/byte_count_input.dart'; import '../widgets/chat_day_separator.dart'; import '../widgets/empty_state.dart'; - import '../widgets/chat_zoom_wrapper.dart'; import '../widgets/emoji_picker.dart'; import '../widgets/gif_message.dart'; @@ -613,6 +614,7 @@ class _ChannelChatScreenState extends State { bool urlImagesEnabled, ) { final settingsService = context.watch(); + final publicIpfsGateway = settingsService.settings.publicIpfsGateway; final enableTracing = settingsService.settings.enableMessageTracing; final regionOnHopsLine = settingsService.settings.regionOnHopsLine; final isOutgoing = message.isOutgoing; @@ -788,6 +790,7 @@ class _ChannelChatScreenState extends State { MessageUrlImageFutureBuilder( messageId: message.messageId, text: message.text, + publicGateway: publicIpfsGateway, builder: (context, snapshot) { final imageAttachment = snapshot.data; @@ -1360,6 +1363,113 @@ class _ChannelChatScreenState extends State { ); } + Future _sendImageViaIpfs() async { + final l10n = context.l10n; + final settings = context.read().settings; + if (settings.uploadIpfsEndpoint.trim().isEmpty) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadNotConfigured), + ); + return; + } + + final file_selector.XFile? file; + try { + file = await file_selector.openFile(); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (file == null) return; + if (!mounted) return; + + final Uint8List bytes; + try { + bytes = await file.readAsBytes(); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (!mounted) return; + if (bytes.isEmpty) { + showDismissibleSnackBar( + context, + content: Text( + l10n.chat_ipfsUploadFailed('The selected file is empty.'), + ), + ); + return; + } + + final String messageUrl; + try { + messageUrl = await IpfsUploadHelper.uploadImageWithSettings( + settings: settings, + bytes: bytes, + fileName: file.name, + mimeType: IpfsUploadHelper.mimeTypeForFileName(file.name), + ); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (!mounted) return; + + final connector = context.read(); + final existingText = _textController.text.trim(); + final combinedText = existingText.isEmpty + ? '$messageUrl ' + : '$messageUrl\n$existingText'; + final maxBytes = maxChannelMessageBytes(connector.selfName); + var messageText = combinedText; + var outboundText = connector.prepareChannelOutboundText( + widget.channel.index, + messageText, + ); + if (utf8.encode(outboundText).length > maxBytes && + existingText.isNotEmpty) { + final originalCharacters = existingText.characters.toList(); + for (var count = originalCharacters.length - 1; count >= 0; count--) { + final shortened = originalCharacters.take(count).join(); + final candidate = '$messageUrl\n$shortened'; + final encoded = connector.prepareChannelOutboundText( + widget.channel.index, + candidate, + ); + if (utf8.encode(encoded).length <= maxBytes) { + messageText = candidate; + outboundText = encoded; + break; + } + } + } + if (utf8.encode(outboundText).length > maxBytes) { + showDismissibleSnackBar( + context, + content: Text(context.l10n.chat_messageTooLong(maxBytes)), + ); + return; + } + _textController.value = TextEditingValue( + text: messageText, + selection: TextSelection.collapsed(offset: messageText.length), + ); + _textFieldFocusNode.requestFocus(); + } + /// Takes no [BuildContext]: it uses the [State]'s own, so the `mounted` /// checks around each `await` are the ones that actually govern it. Future _showImageSendPreview() async { @@ -2110,6 +2220,20 @@ class _ChannelChatScreenState extends State { ), ); } + if (settings.uploadIpfsEndpoint.trim().isNotEmpty) { + items.add( + PopupMenuItem( + value: 'ipfs-image', + child: Row( + children: [ + const Icon(Icons.cloud_upload_outlined), + const SizedBox(width: 12), + Text(context.l10n.chat_sendImageIpfs), + ], + ), + ), + ); + } final selfConnector = context .read(); if (hasShareableLocation( @@ -2159,6 +2283,9 @@ class _ChannelChatScreenState extends State { case 'meshcore-image': _showImageSendPreview(); break; + case 'ipfs-image': + _sendImageViaIpfs(); + break; case 'send-my-location': await _shareMyLocation( context.read(), diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index e5d71c3f..348c61fc 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; +import 'package:file_selector/file_selector.dart' as file_selector; import 'package:provider/provider.dart'; import '../utils/app_logger.dart'; @@ -20,6 +21,7 @@ import '../widgets/message_status_icon.dart'; import '../widgets/empty_state.dart'; import '../helpers/chat_scroll_controller.dart'; import '../helpers/gif_helper.dart'; +import '../helpers/ipfs_upload_helper.dart'; import '../models/channel_message.dart'; import '../models/contact.dart'; import '../l10n/contact_localization.dart'; @@ -507,7 +509,46 @@ class _ChatScreenState extends State { Offset.zero, ancestor: overlay, ); - const menuHeight = 2 * kMinInteractiveDimension + 16; + final items = >[ + PopupMenuItem( + value: 'gif', + child: Row( + children: [ + const Icon(Icons.gif_box), + const SizedBox(width: 12), + Text(context.l10n.chat_sendGif), + ], + ), + ), + ]; + if (settings.uploadIpfsEndpoint.trim().isNotEmpty) { + items.add( + PopupMenuItem( + value: 'ipfs-image', + child: Row( + children: [ + const Icon(Icons.cloud_upload_outlined), + const SizedBox(width: 12), + Text(context.l10n.chat_sendImageIpfs), + ], + ), + ), + ); + } + items.add( + PopupMenuItem( + value: 'send-my-location', + child: Row( + children: [ + const Icon(Icons.my_location), + const SizedBox(width: 12), + Text(context.l10n.chat_shareMyLocation), + ], + ), + ), + ); + final menuHeight = + items.length * kMinInteractiveDimension + 16; final menuTop = (buttonOffset.dy - menuHeight).clamp( 8.0, overlay.size.height, @@ -524,28 +565,7 @@ class _ChatScreenState extends State { final selected = await showMenu( context: menuContext, position: position, - items: [ - PopupMenuItem( - value: 'gif', - child: Row( - children: [ - const Icon(Icons.gif_box), - const SizedBox(width: 12), - Text(context.l10n.chat_sendGif), - ], - ), - ), - PopupMenuItem( - value: 'send-my-location', - child: Row( - children: [ - const Icon(Icons.my_location), - const SizedBox(width: 12), - Text(context.l10n.chat_shareMyLocation), - ], - ), - ), - ], + items: items, ); if (!mounted || !menuContext.mounted) return; if (selected == null) return; @@ -553,6 +573,9 @@ class _ChatScreenState extends State { case 'gif': _showGifPicker(context); break; + case 'ipfs-image': + _sendImageViaIpfs(); + break; case 'send-my-location': await _shareMyLocation( context.read(), @@ -572,6 +595,7 @@ class _ChatScreenState extends State { // No image button here: the image wire format is GRP_DATA, a // channel primitive with no DM equivalent (see the note at the // top of this file). + // IPFS shares a URL as ordinary text instead. Expanded( child: ValueListenableBuilder( valueListenable: _textController, @@ -722,6 +746,112 @@ class _ChatScreenState extends State { ); } + Future _sendImageViaIpfs() async { + final l10n = context.l10n; + final settings = context.read().settings; + if (settings.uploadIpfsEndpoint.trim().isEmpty) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadNotConfigured), + ); + return; + } + + final file_selector.XFile? file; + try { + file = await file_selector.openFile(); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (file == null || !mounted) return; + + final Uint8List bytes; + try { + bytes = await file.readAsBytes(); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (!mounted) return; + if (bytes.isEmpty) { + showDismissibleSnackBar( + context, + content: Text( + l10n.chat_ipfsUploadFailed('The selected file is empty.'), + ), + ); + return; + } + + final String messageUrl; + try { + messageUrl = await IpfsUploadHelper.uploadImageWithSettings( + settings: settings, + bytes: bytes, + fileName: file.name, + mimeType: IpfsUploadHelper.mimeTypeForFileName(file.name), + ); + } on Exception catch (error) { + if (!mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + return; + } + if (!mounted) return; + + final connector = context.read(); + final contact = _resolveContact(connector); + final existingText = _textController.text.trim(); + var messageText = existingText.isEmpty + ? '$messageUrl ' + : '$messageUrl\n$existingText'; + final maxBytes = maxContactMessageBytes(); + var encodedText = connector.prepareContactOutboundText( + contact, + messageText, + ); + if (utf8.encode(encodedText).length > maxBytes && existingText.isNotEmpty) { + final originalCharacters = existingText.characters.toList(); + for (var count = originalCharacters.length - 1; count >= 0; count--) { + final shortened = originalCharacters.take(count).join(); + final candidate = '$messageUrl\n$shortened'; + final candidateEncoded = connector.prepareContactOutboundText( + contact, + candidate, + ); + if (utf8.encode(candidateEncoded).length <= maxBytes) { + messageText = candidate; + encodedText = candidateEncoded; + break; + } + } + } + if (utf8.encode(encodedText).length > maxBytes) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_messageTooLong(maxBytes)), + ); + return; + } + + _textController.value = TextEditingValue( + text: messageText, + selection: TextSelection.collapsed(offset: messageText.length), + ); + _textFieldFocusNode.requestFocus(); + } + Future _showTranslationOptions() async { final settingsService = context.read(); final settings = settingsService.settings; @@ -1502,6 +1632,7 @@ class _MessageBubble extends StatelessWidget { final urlImagesEnabled = context.select( (connector) => connector.isContactUrlImagesEnabled(sourceId), ); + final publicIpfsGateway = settingsService.settings.publicIpfsGateway; // Bubble colors — outgoing uses MeshPalette.me / meBorder / meInk. final bubbleColor = isFailed @@ -1664,6 +1795,7 @@ class _MessageBubble extends StatelessWidget { MessageUrlImageFutureBuilder( messageId: message.messageId, text: message.text, + publicGateway: publicIpfsGateway, builder: (context, snapshot) { final imageAttachment = snapshot.data; diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 5a810588..42f4d33a 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -317,6 +317,24 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(imageMessagesEnabled: value)); } + Future setIpfsImageSettings({ + required String publicGateway, + required String uploadGateway, + required String uploadEndpoint, + required String uploadApiKey, + }) async { + final normalizedPublicGateway = normalizeIpfsGateway(publicGateway); + final normalizedUploadGateway = normalizeIpfsGateway(uploadGateway); + await updateSettings( + _settings.copyWith( + publicIpfsGateway: normalizedPublicGateway, + uploadIpfsGateway: normalizedUploadGateway, + uploadIpfsEndpoint: uploadEndpoint.trim(), + uploadIpfsApiKey: uploadApiKey.trim(), + ), + ); + } + /// See [AppSettings.imageProcessAutomatically]. `main.dart` mirrors this into /// `ReceivedImageStore.processAutomatically` on every settings change; the /// store applies it to future arrivals only, so flipping it does not diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 66963a39..3e457138 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -11,6 +11,7 @@ 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 '../models/app_settings.dart'; import '../storage/prefs_manager.dart'; import '../utils/platform_info.dart'; import 'notification_reply.dart'; @@ -26,6 +27,11 @@ class NotificationService { // Locale for localized notification strings Locale _locale = const Locale('en'); + String _publicIpfsGateway = AppSettings.defaultPublicIpfsGateway; + + void setPublicIpfsGateway(String gateway) { + _publicIpfsGateway = gateway.trim(); + } /// Set the locale for notification strings (call when app locale changes) void setLocale(Locale locale) { @@ -297,7 +303,10 @@ class NotificationService { }) async { if (!urlImagesEnabled) return null; - final imageUrl = await MessageUrlImageHelper.parseVerified(text); + final imageUrl = await MessageUrlImageHelper.parseVerified( + text, + publicGateway: _publicIpfsGateway, + ); if (imageUrl == null) return null; try { diff --git a/test/helpers/message_url_image_helper_test.dart b/test/helpers/message_url_image_helper_test.dart index 11e1b022..35f9a6a2 100644 --- a/test/helpers/message_url_image_helper_test.dart +++ b/test/helpers/message_url_image_helper_test.dart @@ -1,3 +1,5 @@ +import 'dart:typed_data'; + import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; @@ -48,29 +50,94 @@ void main() { ); }); - test('parses direct ipfs cid urls', () async { - final attachment = await MessageUrlImageHelper.parse( - 'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', - ); + test( + 'does not resolve ipfs cid links with the default gateway deactivated', + () async { + expect( + await MessageUrlImageHelper.parse( + 'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ), + isNull, + ); + expect( + await MessageUrlImageHelper.parse( + 'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ), + isNull, + ); + }, + ); - expect(attachment, isNotNull); - expect( - attachment, - 'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', - ); - }); - - test('parses direct ipfs cid urls without double slashes', () async { + test('uses the configured public gateway for direct ipfs cid urls', () async { final attachment = await MessageUrlImageHelper.parse( - 'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + 'ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + publicGateway: 'https://gateway.example.com', ); expect( attachment, - 'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + 'https://gateway.example.com/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', ); }); + test( + 'does not resolve ipfs cid links when the download gateway is empty', + () async { + final attachment = await MessageUrlImageHelper.parse( + 'ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + publicGateway: '', + ); + + expect(attachment, isNull); + }, + ); + + test('does not upload when the upload endpoint is empty', () async { + var requestCount = 0; + MessageUrlImageHelper.httpClient = MockClient((request) async { + requestCount++; + return http.Response('{}', 200); + }); + + await expectLater( + MessageUrlImageHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: '', + uploadApiKey: '', + ), + throwsArgumentError, + ); + expect(requestCount, 0); + }); + + test( + 'uploads and returns an ipfs scheme when upload gateway is empty', + () async { + MessageUrlImageHelper.httpClient = MockClient((request) async { + expect(request.method, 'POST'); + return http.Response( + '{"Hash":"bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly"}', + 200, + ); + }); + + final message = await MessageUrlImageHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: 'http://127.0.0.1:5001/api/v0/add', + uploadApiKey: '', + ); + + expect( + message, + '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', diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index b96666e3..6cd5dc04 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -443,6 +443,23 @@ void main() { expect(settings.evictDiscoveredContactsEnabled, isFalse); }); + test('public IPFS gateway defaults to deactivated and preserves empty', () { + expect(AppSettings.fromJson({}).publicIpfsGateway, isEmpty); + expect( + AppSettings.fromJson({'public_ipfs_gateway': ''}).publicIpfsGateway, + isEmpty, + ); + }); + + test('empty upload gateway does not fall back to the download gateway', () { + final settings = AppSettings( + publicIpfsGateway: 'https://gateway.example.com/ipfs/', + uploadIpfsGateway: '', + ); + + expect(settings.effectiveUploadIpfsGateway, isEmpty); + }); + test( 'fromJson with missing new fields uses defaults (backward compat)', () { diff --git a/test/services/tcp_transport_service_native_test.dart b/test/services/tcp_transport_service_native_test.dart index 3cb9629c..72edf22e 100644 --- a/test/services/tcp_transport_service_native_test.dart +++ b/test/services/tcp_transport_service_native_test.dart @@ -61,34 +61,30 @@ int _readIntOption(Socket socket, int level, int option) { } void main() { - test( - 'connect enables TCP keepalive with short probe timings', - () async { - final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); - final overrides = _CapturingConnectOverrides(); - final service = TcpTransportService(); - try { - await IOOverrides.runZoned( - () => service.connect( - host: InternetAddress.loopbackIPv4.address, - port: server.port, - ), - socketConnect: overrides.socketConnect, - ); - final socket = overrides.socket!; - // Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5, - // TCP_KEEPCNT 6. - expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10); - expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3); - } finally { - await service.disconnect(); - await server.close(); - } - }, - skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones', - ); + test('connect enables TCP keepalive with short probe timings', () async { + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final overrides = _CapturingConnectOverrides(); + final service = TcpTransportService(); + try { + await IOOverrides.runZoned( + () => service.connect( + host: InternetAddress.loopbackIPv4.address, + port: server.port, + ), + socketConnect: overrides.socketConnect, + ); + final socket = overrides.socket!; + // Linux values: SO_KEEPALIVE 9, TCP_KEEPIDLE 4, TCP_KEEPINTVL 5, + // TCP_KEEPCNT 6. + expect(_readIntOption(socket, RawSocketOption.levelSocket, 9), 1); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 4), 30); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 5), 10); + expect(_readIntOption(socket, RawSocketOption.levelTcp, 6), 3); + } finally { + await service.disconnect(); + await server.close(); + } + }, skip: Platform.isLinux ? false : 'Option numbers checked are Linux ones'); test('connect/disconnect updates TCP transport state', () async { final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); diff --git a/untranslated.json b/untranslated.json index 9e26dfee..c4c655a3 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,341 @@ -{} \ No newline at end of file +{ + "bg": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "de": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "es": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "fr": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "hu": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "it": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "ja": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "ko": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "nl": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "pl": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "pt": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "ru": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "sk": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "sl": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "sv": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "uk": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ], + + "zh": [ + "appSettings_ipfsImageLinks", + "appSettings_ipfsImageLinksSubtitle", + "appSettings_publicIpfsGateway", + "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayPinata", + "appSettings_ipfsGatewayFilebase", + "appSettings_ipfsGatewayCustom", + "appSettings_uploadIpfsProvider", + "appSettings_uploadIpfsGateway", + "appSettings_uploadIpfsGatewaySubtitle", + "appSettings_uploadIpfsEndpoint", + "appSettings_uploadIpfsEndpointSubtitle", + "appSettings_uploadIpfsApiKey", + "appSettings_ipfsImageLinksDescription", + "chat_sendImageIpfs", + "chat_ipfsUploadFailed", + "chat_ipfsUploadNotConfigured" + ] +} From de6632d70ecb69abe4eef46bbb2c81075c1d88a0 Mon Sep 17 00:00:00 2001 From: ZIER Date: Tue, 13 Oct 2026 11:19:29 +0200 Subject: [PATCH 02/15] fix crash in chat_screen.dart, try to resolve test error. --- lib/connector/meshcore_connector.dart | 16 +++++----- lib/screens/app_settings_screen.dart | 21 +++++++------ lib/screens/chat_screen.dart | 43 +++++++++++++++------------ 3 files changed, 43 insertions(+), 37 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 03b03944..57ef9fc1 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -3794,6 +3794,9 @@ class MeshCoreConnector extends ChangeNotifier { if (pendingAck != null) { _pendingGenericAckQueue.remove(pendingAck); } + if (_activeTransport == MeshCoreTransportType.tcp) { + unawaited(disconnect(manual: false)); + } rethrow; } @@ -5846,17 +5849,16 @@ class MeshCoreConnector extends ChangeNotifier { _findChannelByIndex(index)?.storageId ?? _slotChannelIds[index]; // Delete by setting empty name and zero PSK await sendFrame(buildSetChannelFrame(index, '', Uint8List(16))); + _channelMessages.remove(index); + _processedChannelReactions.remove(index); + // Refresh before clearing history so messages from an in-flight queue sync + // cannot recreate the channel's stored history after it has been deleted. + await getChannels(force: true); // Another slot holding the same PSK keeps the shared history. - final stillHeld = _channels.any( - (channel) => channel.index != index && channel.storageId == channelId, - ); + final stillHeld = _slotChannelIds.containsValue(channelId); if (channelId != null && !stillHeld) { await _clearChannelStorage(channelId); } - _channelMessages.remove(index); - _processedChannelReactions.remove(index); - // Refresh channels after deleting - await getChannels(force: true); } /// Removes everything persisted for [channelId]: messages, settings, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index fd5065e8..16a21dc1 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -675,7 +675,16 @@ class AppSettingsScreen extends StatelessWidget { onChanged: settingsService.setChannelMinHopsCountRepeaters, ), ], - const Divider(height: 1, indent: 16), + ], + ); + } + + Widget _buildImageMessagesContent( + BuildContext context, + AppSettingsService settingsService, + ) { + return Column( + children: [ ListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, @@ -688,16 +697,6 @@ class AppSettingsScreen extends StatelessWidget { onTap: () => _showIpfsImageLinksDialog(context, settingsService), ), const Divider(height: 1, indent: 16), - ], - ); - } - - Widget _buildImageMessagesContent( - BuildContext context, - AppSettingsService settingsService, - ) { - return Column( - children: [ _ScrollIntoViewOnce( enabled: focusImageMessages, child: SwitchListTile( diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index d0c6e9c0..5456ea55 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -507,9 +507,6 @@ class _ChatScreenState extends State { final useEncoder = connector.isContactSmazEnabled(keyHex) || connector.isContactCyr2LatEnabled(keyHex); - final showIpfsAction = context.select( - (s) => s.settings.uploadIpfsEndpoint.trim().isNotEmpty, - ); return ChatComposer( controller: _textController, focusNode: _textFieldFocusNode, @@ -525,24 +522,32 @@ class _ChatScreenState extends State { sendTooltip: context.l10n.chat_sendMessageTo( _resolveContact(connector).name, ), - actionsBuilder: () => [ - ChatComposerAction( - id: 'gif', - icon: Icons.gif_box, - label: context.l10n.chat_sendGif, - ), - if (showIpfsAction) + actionsBuilder: () { + final showIpfsAction = context + .read() + .settings + .uploadIpfsEndpoint + .trim() + .isNotEmpty; + return [ ChatComposerAction( - id: 'ipfs-image', - icon: Icons.cloud_upload_outlined, - label: context.l10n.chat_sendImageIpfs, + id: 'gif', + icon: Icons.gif_box, + label: context.l10n.chat_sendGif, ), - ChatComposerAction( - id: 'send-my-location', - icon: Icons.my_location, - label: context.l10n.chat_shareMyLocation, - ), - ], + if (showIpfsAction) + ChatComposerAction( + id: 'ipfs-image', + icon: Icons.cloud_upload_outlined, + label: context.l10n.chat_sendImageIpfs, + ), + ChatComposerAction( + id: 'send-my-location', + icon: Icons.my_location, + label: context.l10n.chat_shareMyLocation, + ), + ]; + }, onAction: (action) { if (!mounted) return; switch (action) { From 050016f599da89edd0ea83db67c68f38eec43728 Mon Sep 17 00:00:00 2001 From: ericz Date: Sat, 24 Oct 2026 16:46:32 +0200 Subject: [PATCH 03/15] ai fix tcp reconnect test fail --- test/connector/tcp_auto_reconnect_test.dart | 46 ++++++++++----------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/test/connector/tcp_auto_reconnect_test.dart b/test/connector/tcp_auto_reconnect_test.dart index 5c258cfe..9d63ab17 100644 --- a/test/connector/tcp_auto_reconnect_test.dart +++ b/test/connector/tcp_auto_reconnect_test.dart @@ -12,11 +12,15 @@ import 'package:meshcore_open/services/usb_serial_frame_codec.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; -Future _waitFor(bool Function() condition, {int seconds = 10}) async { +Future _waitFor( + bool Function() condition, { + int seconds = 10, + Duration pollInterval = const Duration(milliseconds: 25), +}) async { final end = DateTime.now().add(Duration(seconds: seconds)); while (!condition()) { if (DateTime.now().isAfter(end)) fail('Timed out waiting for condition'); - await Future.delayed(const Duration(milliseconds: 25)); + await Future.delayed(pollInterval); } } @@ -198,27 +202,23 @@ void main() { expect(_connector.isTcpTransportConnected, isTrue); // The companion goes away entirely: attempts fail and are rescheduled. - var sawRetryAttempt = false; - void observeRetryAttempt() { - if (_connector.state == MeshCoreConnectionState.connecting) { - sawRetryAttempt = true; - } - } - - _connector.addListener(observeRetryAttempt); - try { - await companion.close(); - // Wait for a retry to start and fail, then verify another backoff is - // scheduled. A fixed delay can observe the connector mid-attempt. - await _waitFor( - () => - sawRetryAttempt && - _connector.state == MeshCoreConnectionState.disconnected && - _connector.isAutoReconnectScheduled, - ); - } finally { - _connector.removeListener(observeRetryAttempt); - } + await companion.close(); + await _waitFor( + () => + _connector.state == MeshCoreConnectionState.disconnected && + _connector.isAutoReconnectScheduled, + ); + await _waitFor( + () => !_connector.isAutoReconnectScheduled, + pollInterval: const Duration(milliseconds: 1), + ); + // The timer firing proves an attempt started; wait for its failure to + // finish and the next backoff to become active. + await _waitFor( + () => + _connector.state == MeshCoreConnectionState.disconnected && + _connector.isAutoReconnectScheduled, + ); expect(_connector.isTcpTransportConnected, isFalse); }, ); From c2d18b431e9978784c9bddd3d07deea80cccc831 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:52:03 -0700 Subject: [PATCH 04/15] Test IpfsUploadHelper directly and build the upload request once Drop the test-only upload facade on MessageUrlImageHelper that overwrote the shared HTTP client, move its tests to IpfsUploadHelper, and build the multipart request with the final upload URI instead of cloning it. --- lib/helpers/ipfs_upload_helper.dart | 42 +++++---- lib/helpers/message_url_image_helper.dart | 37 -------- test/helpers/ipfs_upload_helper_test.dart | 89 +++++++++++++++++++ .../message_url_image_helper_test.dart | 48 ---------- 4 files changed, 109 insertions(+), 107 deletions(-) create mode 100644 test/helpers/ipfs_upload_helper_test.dart diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart index 8d294568..42c2dc91 100644 --- a/lib/helpers/ipfs_upload_helper.dart +++ b/lib/helpers/ipfs_upload_helper.dart @@ -6,6 +6,7 @@ import 'package:http/http.dart' as http; import '../models/app_settings.dart'; class IpfsUploadHelper { + @visibleForTesting static http.Client? httpClient; static String mimeTypeForFileName(String fileName) { @@ -69,40 +70,37 @@ class IpfsUploadHelper { } final Uri uploadUri; - final request = http.MultipartRequest('POST', endpointUri) - ..files.add( - http.MultipartFile.fromBytes('file', bytes, filename: safeFileName), - ); - if (isPinata) { if (token.isEmpty) { throw ArgumentError('Pinata requires an API key or JWT.'); } - request.headers['Authorization'] = 'Bearer $token'; - request.fields['pinataOptions'] = jsonEncode({'cidVersion': 1}); - request.fields['pinataMetadata'] = jsonEncode({'name': safeFileName}); uploadUri = endpointUri; } else { - final parameters = {'cid-version': '1'}; - if (isKubo) parameters['pin'] = 'true'; uploadUri = endpointUri.replace( - queryParameters: {...endpointUri.queryParameters, ...parameters}, + queryParameters: { + ...endpointUri.queryParameters, + 'cid-version': '1', + if (isKubo) 'pin': 'true', + }, ); - if (token.isNotEmpty) { - request.headers['Authorization'] = 'Bearer $token'; - } } - final finalRequest = request.url == uploadUri - ? request - : (http.MultipartRequest('POST', uploadUri) - ..headers.addAll(request.headers) - ..fields.addAll(request.fields) - ..files.addAll(request.files)); + final request = http.MultipartRequest('POST', uploadUri) + ..files.add( + http.MultipartFile.fromBytes('file', bytes, filename: safeFileName), + ); + if (token.isNotEmpty) { + request.headers['Authorization'] = 'Bearer $token'; + } + if (isPinata) { + request.fields['pinataOptions'] = jsonEncode({'cidVersion': 1}); + request.fields['pinataMetadata'] = jsonEncode({'name': safeFileName}); + } + final client = httpClient; final response = await (client == null - ? finalRequest.send() - : client.send(finalRequest)); + ? request.send() + : client.send(request)); final body = await response.stream.bytesToString(); if (response.statusCode < 200 || response.statusCode >= 300) { throw Exception('IPFS upload failed (${response.statusCode}): $body'); diff --git a/lib/helpers/message_url_image_helper.dart b/lib/helpers/message_url_image_helper.dart index 30eb4e2f..2f3e0756 100644 --- a/lib/helpers/message_url_image_helper.dart +++ b/lib/helpers/message_url_image_helper.dart @@ -1,12 +1,10 @@ import 'dart:async'; import 'dart:collection'; -import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:http/http.dart' as http; -import 'ipfs_upload_helper.dart'; import '../models/app_settings.dart'; /// Finds and renders image URLs embedded in ordinary text messages. @@ -26,41 +24,6 @@ class MessageUrlImageHelper { @visibleForTesting static http.Client? httpClient; - /// Compatibility facade for the dedicated IPFS upload helper. - static Future uploadImageWithSettings({ - required AppSettings settings, - required Uint8List bytes, - required String fileName, - required String mimeType, - }) { - IpfsUploadHelper.httpClient = httpClient; - return IpfsUploadHelper.uploadImageWithSettings( - settings: settings, - bytes: bytes, - fileName: fileName, - mimeType: mimeType, - ); - } - - static Future uploadImage({ - required Uint8List bytes, - required String fileName, - required String mimeType, - required String uploadEndpoint, - required String uploadApiKey, - String uploadGateway = '', - }) async { - IpfsUploadHelper.httpClient = httpClient; - return IpfsUploadHelper.uploadImage( - bytes: bytes, - fileName: fileName, - mimeType: mimeType, - uploadEndpoint: uploadEndpoint, - uploadApiKey: uploadApiKey, - uploadGateway: uploadGateway, - ); - } - static final RegExp _pyxPattern = RegExp( r'''https?://pyx\.li/\?i=([A-Za-z0-9_-]+)''', caseSensitive: false, diff --git a/test/helpers/ipfs_upload_helper_test.dart b/test/helpers/ipfs_upload_helper_test.dart new file mode 100644 index 00000000..f49a5d5c --- /dev/null +++ b/test/helpers/ipfs_upload_helper_test.dart @@ -0,0 +1,89 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:meshcore_open/helpers/ipfs_upload_helper.dart'; + +void main() { + group('IpfsUploadHelper', () { + tearDown(() => IpfsUploadHelper.httpClient = null); + + test('does not upload when the upload endpoint is empty', () async { + var requestCount = 0; + IpfsUploadHelper.httpClient = MockClient((request) async { + requestCount++; + return http.Response('{}', 200); + }); + + await expectLater( + IpfsUploadHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: '', + uploadApiKey: '', + ), + throwsArgumentError, + ); + expect(requestCount, 0); + }); + + test( + 'uploads and returns an ipfs scheme when upload gateway is empty', + () async { + final requests = []; + IpfsUploadHelper.httpClient = MockClient((request) async { + requests.add(request); + expect(request.method, 'POST'); + return http.Response( + '{"Hash":"bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly"}', + 200, + ); + }); + + final message = await IpfsUploadHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: 'http://127.0.0.1:5001/api/v0/add', + uploadApiKey: '', + ); + + expect( + message, + 'ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + ); + expect(requests.first.url.path, '/api/v0/add'); + expect(requests.first.url.queryParameters, { + 'cid-version': '1', + 'pin': 'true', + }); + }, + ); + + test('sends the Pinata request to the endpoint unchanged', () async { + late http.BaseRequest upload; + IpfsUploadHelper.httpClient = MockClient((request) async { + upload = request; + return http.Response('{"IpfsHash":"bafytest"}', 200); + }); + + final message = await IpfsUploadHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: 'https://api.pinata.cloud/pinning/pinFileToIPFS', + uploadApiKey: 'jwt', + uploadGateway: 'https://gateway.example.com', + ); + + expect( + upload.url.toString(), + 'https://api.pinata.cloud/pinning/pinFileToIPFS', + ); + expect(upload.headers['Authorization'], 'Bearer jwt'); + expect(message, 'https://gateway.example.com/ipfs/bafytest'); + }); + }); +} diff --git a/test/helpers/message_url_image_helper_test.dart b/test/helpers/message_url_image_helper_test.dart index 35f9a6a2..c9cce83b 100644 --- a/test/helpers/message_url_image_helper_test.dart +++ b/test/helpers/message_url_image_helper_test.dart @@ -1,5 +1,3 @@ -import 'dart:typed_data'; - import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; @@ -92,52 +90,6 @@ void main() { }, ); - test('does not upload when the upload endpoint is empty', () async { - var requestCount = 0; - MessageUrlImageHelper.httpClient = MockClient((request) async { - requestCount++; - return http.Response('{}', 200); - }); - - await expectLater( - MessageUrlImageHelper.uploadImage( - bytes: Uint8List.fromList([1, 2, 3]), - fileName: 'image.png', - mimeType: 'image/png', - uploadEndpoint: '', - uploadApiKey: '', - ), - throwsArgumentError, - ); - expect(requestCount, 0); - }); - - test( - 'uploads and returns an ipfs scheme when upload gateway is empty', - () async { - MessageUrlImageHelper.httpClient = MockClient((request) async { - expect(request.method, 'POST'); - return http.Response( - '{"Hash":"bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly"}', - 200, - ); - }); - - final message = await MessageUrlImageHelper.uploadImage( - bytes: Uint8List.fromList([1, 2, 3]), - fileName: 'image.png', - mimeType: 'image/png', - uploadEndpoint: 'http://127.0.0.1:5001/api/v0/add', - uploadApiKey: '', - ); - - expect( - message, - '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', From abcf6c2eae57c4058b58076efcd43c1ea2cb3af5 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:52:43 -0700 Subject: [PATCH 05/15] Treat an existing Kubo MFS entry as a successful share The MFS name includes the CID, so 'already has entry' means the same content is already there; re-sharing a file no longer fails. --- lib/helpers/ipfs_upload_helper.dart | 4 +- test/helpers/ipfs_upload_helper_test.dart | 48 +++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart index 42c2dc91..3011fe3a 100644 --- a/lib/helpers/ipfs_upload_helper.dart +++ b/lib/helpers/ipfs_upload_helper.dart @@ -153,7 +153,9 @@ class IpfsUploadHelper { final response = await (client == null ? http.post(copyUri, headers: headers) : client.post(copyUri, headers: headers)); - if (response.statusCode < 200 || response.statusCode >= 300) { + final alreadyCopied = response.body.contains('already has entry'); + if ((response.statusCode < 200 || response.statusCode >= 300) && + !alreadyCopied) { throw Exception( 'Kubo MFS import failed (${response.statusCode}): ${response.body}', ); diff --git a/test/helpers/ipfs_upload_helper_test.dart b/test/helpers/ipfs_upload_helper_test.dart index f49a5d5c..a5987d18 100644 --- a/test/helpers/ipfs_upload_helper_test.dart +++ b/test/helpers/ipfs_upload_helper_test.dart @@ -62,6 +62,54 @@ void main() { }, ); + test( + 're-sharing a file already in Kubo MFS still returns the link', + () async { + final paths = []; + IpfsUploadHelper.httpClient = MockClient((request) async { + paths.add(request.url.path); + if (request.url.path.endsWith('/files/cp')) { + return http.Response( + '{"Message":"cp: cannot put node in path /meshcore_uploads/bafytest-image.png: directory already has entry by that name","Code":0,"Type":"error"}', + 500, + ); + } + return http.Response('{"Hash":"bafytest"}', 200); + }); + + final message = await IpfsUploadHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: 'http://127.0.0.1:5001/api/v0/add', + uploadApiKey: '', + ); + + expect(message, 'ipfs://bafytest'); + expect(paths, ['/api/v0/add', '/api/v0/files/cp']); + }, + ); + + test('other Kubo MFS errors still fail the upload', () async { + IpfsUploadHelper.httpClient = MockClient((request) async { + if (request.url.path.endsWith('/files/cp')) { + return http.Response('{"Message":"permission denied"}', 500); + } + return http.Response('{"Hash":"bafytest"}', 200); + }); + + await expectLater( + IpfsUploadHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: 'http://127.0.0.1:5001/api/v0/add', + uploadApiKey: '', + ), + throwsException, + ); + }); + test('sends the Pinata request to the endpoint unchanged', () async { late http.BaseRequest upload; IpfsUploadHelper.httpClient = MockClient((request) async { From 3ed88a0fc08f3a18b0b50b460d31e051a4f19b9c Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:54:00 -0700 Subject: [PATCH 06/15] Validate the IPFS upload endpoint before uploading Reject an empty or non-http(s) endpoint, missing Pinata/Filebase tokens, and a custom (Kubo) endpoint that doesn't end in /api/v0/add before any data is sent, and derive the files/cp URL from the add URL so Kubo behind a proxy path works. --- lib/helpers/ipfs_upload_helper.dart | 63 ++++++++++++----------- test/helpers/ipfs_upload_helper_test.dart | 55 +++++++++++++++++++- 2 files changed, 86 insertions(+), 32 deletions(-) diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart index 3011fe3a..44da8b16 100644 --- a/lib/helpers/ipfs_upload_helper.dart +++ b/lib/helpers/ipfs_upload_helper.dart @@ -9,6 +9,8 @@ class IpfsUploadHelper { @visibleForTesting static http.Client? httpClient; + static final _kuboAddPath = RegExp(r'/api/v0/add/?$'); + static String mimeTypeForFileName(String fileName) { switch (fileName.toLowerCase().split('.').last) { case 'jpg': @@ -53,11 +55,17 @@ class IpfsUploadHelper { }) async { final endpoint = uploadEndpoint.trim(); if (endpoint.isEmpty) { - throw ArgumentError('Configure an IPFS upload endpoint first.'); + throw Exception('Configure an IPFS upload endpoint first.'); + } + + final endpointUri = Uri.tryParse(endpoint); + if (endpointUri == null || + !(endpointUri.isScheme('http') || endpointUri.isScheme('https')) || + endpointUri.host.isEmpty) { + throw Exception('The IPFS upload endpoint must be an http(s) URL.'); } final token = uploadApiKey.trim(); - final endpointUri = Uri.parse(endpoint); final endpointHost = endpointUri.host.toLowerCase(); final isPinata = endpointHost.contains('pinata') || @@ -65,26 +73,28 @@ class IpfsUploadHelper { final isFilebase = endpointHost.contains('filebase'); final isKubo = !isPinata && !isFilebase; final safeFileName = _sanitizeUploadFileName(fileName); - if (isFilebase && token.isEmpty) { - throw ArgumentError('Filebase RPC requires an API token.'); + if (isPinata && token.isEmpty) { + throw Exception('Pinata requires an API key or JWT.'); } - - final Uri uploadUri; - if (isPinata) { - if (token.isEmpty) { - throw ArgumentError('Pinata requires an API key or JWT.'); - } - uploadUri = endpointUri; - } else { - uploadUri = endpointUri.replace( - queryParameters: { - ...endpointUri.queryParameters, - 'cid-version': '1', - if (isKubo) 'pin': 'true', - }, + if (isFilebase && token.isEmpty) { + throw Exception('Filebase RPC requires an API token.'); + } + if (isKubo && !_kuboAddPath.hasMatch(endpointUri.path)) { + throw Exception( + 'Custom (Kubo) upload endpoint must end with /api/v0/add.', ); } + final uploadUri = isPinata + ? endpointUri + : endpointUri.replace( + queryParameters: { + ...endpointUri.queryParameters, + 'cid-version': '1', + if (isKubo) 'pin': 'true', + }, + ); + final request = http.MultipartRequest('POST', uploadUri) ..files.add( http.MultipartFile.fromBytes('file', bytes, filename: safeFileName), @@ -113,7 +123,7 @@ class IpfsUploadHelper { if (isKubo) { await _copyKuboFileToMfs( - endpoint: endpoint, + addUri: endpointUri, cid: cid, fileName: safeFileName, authorization: token.isEmpty ? null : 'Bearer $token', @@ -125,23 +135,14 @@ class IpfsUploadHelper { } static Future _copyKuboFileToMfs({ - required String endpoint, + required Uri addUri, required String cid, required String fileName, required String? authorization, }) async { - final uploadUri = Uri.parse(endpoint); - final copyPath = uploadUri.path.replaceFirst( - RegExp(r'/add/?$'), - '/files/cp', - ); - if (copyPath == uploadUri.path) { - throw ArgumentError('Kubo upload endpoint must end with /add.'); - } - final mfsPath = '/meshcore_uploads/$cid-$fileName'; - final copyUri = uploadUri.replace( - path: copyPath, + final copyUri = addUri.replace( + path: addUri.path.replaceFirst(_kuboAddPath, '/api/v0/files/cp'), query: 'arg=${Uri.encodeQueryComponent('/ipfs/$cid')}' '&arg=${Uri.encodeQueryComponent(mfsPath)}&parents=true', diff --git a/test/helpers/ipfs_upload_helper_test.dart b/test/helpers/ipfs_upload_helper_test.dart index a5987d18..e9cb4cc4 100644 --- a/test/helpers/ipfs_upload_helper_test.dart +++ b/test/helpers/ipfs_upload_helper_test.dart @@ -24,11 +24,64 @@ void main() { uploadEndpoint: '', uploadApiKey: '', ), - throwsArgumentError, + throwsException, ); expect(requestCount, 0); }); + for (final endpoint in [ + 'not a url', + 'ftp://host/api/v0/add', + 'https://host/ipfs-upload', + 'https://uploads.example.com/v1/files', + ]) { + test('rejects $endpoint before uploading', () async { + var requestCount = 0; + IpfsUploadHelper.httpClient = MockClient((request) async { + requestCount++; + return http.Response('{"Hash":"bafytest"}', 200); + }); + + await expectLater( + IpfsUploadHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: endpoint, + uploadApiKey: 'token', + ), + throwsA(isA()), + ); + expect(requestCount, 0); + }); + } + + test('copies to MFS through a proxied Kubo endpoint', () async { + final urls = []; + IpfsUploadHelper.httpClient = MockClient((request) async { + urls.add(request.url); + return http.Response('{"Hash":"bafytest"}', 200); + }); + + final message = await IpfsUploadHelper.uploadImage( + bytes: Uint8List.fromList([1, 2, 3]), + fileName: 'image.png', + mimeType: 'image/png', + uploadEndpoint: 'https://host/ipfs-upload/api/v0/add', + uploadApiKey: '', + ); + + expect(message, 'ipfs://bafytest'); + expect(urls.map((url) => url.path), [ + '/ipfs-upload/api/v0/add', + '/ipfs-upload/api/v0/files/cp', + ]); + expect(urls.last.queryParametersAll['arg'], [ + '/ipfs/bafytest', + '/meshcore_uploads/bafytest-image.png', + ]); + }); + test( 'uploads and returns an ipfs scheme when upload gateway is empty', () async { From 0620e8f27a42bb8aee83f8fa910845d36edfb117 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:53:10 -0700 Subject: [PATCH 07/15] Always clear a deleted channel's storage when no other slot holds it Keep refreshing channels before clearing so in-flight queue messages can't write the history back, but decide whether the channel is still held while ignoring the deleted slot, and clear even if the refresh fails or is incomplete. --- lib/connector/meshcore_connector.dart | 21 +++++++++----- test/connector/channel_slot_map_test.dart | 34 +++++++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index f535ed25..a706e715 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -5902,13 +5902,20 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildSetChannelFrame(index, '', Uint8List(16))); _channelMessages.remove(index); _processedChannelReactions.remove(index); - // Refresh before clearing history so messages from an in-flight queue sync - // cannot recreate the channel's stored history after it has been deleted. - await getChannels(force: true); - // Another slot holding the same PSK keeps the shared history. - final stillHeld = _slotChannelIds.containsValue(channelId); - if (channelId != null && !stillHeld) { - await _clearChannelStorage(channelId); + try { + // Refresh before clearing history so messages from an in-flight queue + // sync cannot recreate the channel's stored history after it is deleted. + await getChannels(force: true); + } finally { + // Another slot holding the same PSK keeps the shared history. The + // deleted slot is skipped: a failed or partial refresh can leave it in + // the map. + final stillHeld = _slotChannelIds.entries.any( + (entry) => entry.key != index && entry.value == channelId, + ); + if (channelId != null && !stillHeld) { + await _clearChannelStorage(channelId); + } } } diff --git a/test/connector/channel_slot_map_test.dart b/test/connector/channel_slot_map_test.dart index 65097f67..d2f217ce 100644 --- a/test/connector/channel_slot_map_test.dart +++ b/test/connector/channel_slot_map_test.dart @@ -243,6 +243,40 @@ void main() { expect(_storedTexts(hikingId), isEmpty); }); + test('deleting a channel clears its history when the refresh cannot read ' + 'the slot', () async { + _connector.channelSyncTimeoutMs = 30; + var deleted = false; + final radio = _TestRadio( + swallow: (frame) { + if (frame[0] == cmdSetChannel && frame[1] == 1) deleted = true; + return deleted && frame[0] == cmdGetChannel && frame[1] == 1; + }, + ); + await _connect(radio); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + + await _connector.deleteChannel(1); + expect(_connector.channelIdForSlot(1), hikingId); + expect(_storedTexts(hikingId), isEmpty); + }); + + test( + 'deleting one of two slots with the same PSK keeps the history', + () async { + final radio = _TestRadio(); + await _connect( + radio, + seed: () => + radio.handle(buildSetChannelFrame(5, 'Hiking Twin', _psk(1))), + ); + await _waitFor(() => _texts(1).contains(_queuedHikingText)); + + await _connector.deleteChannel(1); + expect(_storedTexts(hikingId), contains(_queuedHikingText)); + }, + ); + test('a channel frame that arrives before the slot map is held, then filed ' 'by the confirmed map', () async { final radio = _TestRadio( From cc33595f13a2ad88fb587c90e55e45d71b3a1602 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:52:24 -0700 Subject: [PATCH 08/15] Share the IPFS link attach flow between the chat screens Move the pick/read/upload/insert flow that was copied into both chat screens into helpers/ipfs_link_attach_flow.dart; each screen passes only its byte limit and outbound encoder. --- lib/helpers/ipfs_link_attach_flow.dart | 127 +++++++++++++++++++ lib/screens/channel_chat_screen.dart | 114 ++--------------- lib/screens/chat_screen.dart | 112 ++-------------- test/helpers/ipfs_link_attach_flow_test.dart | 76 +++++++++++ 4 files changed, 221 insertions(+), 208 deletions(-) create mode 100644 lib/helpers/ipfs_link_attach_flow.dart create mode 100644 test/helpers/ipfs_link_attach_flow_test.dart diff --git a/lib/helpers/ipfs_link_attach_flow.dart b/lib/helpers/ipfs_link_attach_flow.dart new file mode 100644 index 00000000..99a3175a --- /dev/null +++ b/lib/helpers/ipfs_link_attach_flow.dart @@ -0,0 +1,127 @@ +import 'dart:convert'; + +import 'package:file_selector/file_selector.dart' as file_selector; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../l10n/l10n.dart'; +import '../services/app_settings_service.dart'; +import 'ipfs_upload_helper.dart'; +import 'snack_bar_builder.dart'; + +/// Shared "send image via IPFS" flow for the direct-message and channel chat +/// screens: picks a file, uploads it with the configured IPFS settings and +/// puts the resulting link at the start of the composer draft. +/// +/// [maxBytes] is the screen's outbound byte limit and [encodeOutbound] turns +/// draft text into what the radio would actually send, so the limit is +/// checked against the encoded form. +Future attachIpfsLinkToDraft({ + required BuildContext context, + required TextEditingController controller, + required FocusNode focusNode, + required int maxBytes, + required String Function(String text) encodeOutbound, +}) async { + final l10n = context.l10n; + final settings = context.read().settings; + if (settings.uploadIpfsEndpoint.trim().isEmpty) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadNotConfigured), + ); + return; + } + + void showFailure(Object error) { + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsUploadFailed('$error')), + ); + } + + final file_selector.XFile? file; + try { + file = await file_selector.openFile(); + } on Exception catch (error) { + showFailure(error); + return; + } + if (file == null || !context.mounted) return; + + final Uint8List bytes; + try { + bytes = await file.readAsBytes(); + } on Exception catch (error) { + showFailure(error); + return; + } + if (!context.mounted) return; + if (bytes.isEmpty) { + showFailure('The selected file is empty.'); + return; + } + + final String messageUrl; + try { + messageUrl = await IpfsUploadHelper.uploadImageWithSettings( + settings: settings, + bytes: bytes, + fileName: file.name, + mimeType: IpfsUploadHelper.mimeTypeForFileName(file.name), + ); + } on Exception catch (error) { + showFailure(error); + return; + } + if (!context.mounted) return; + + final messageText = composeIpfsLinkDraft( + messageUrl: messageUrl, + existingText: controller.text.trim(), + maxBytes: maxBytes, + encodeOutbound: encodeOutbound, + ); + if (messageText == null) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_messageTooLong(maxBytes)), + ); + return; + } + + controller.value = TextEditingValue( + text: messageText, + selection: TextSelection.collapsed(offset: messageText.length), + ); + focusNode.requestFocus(); +} + +/// Builds the draft with [messageUrl] in front of [existingText], trimming +/// [existingText] from the end until the encoded result fits [maxBytes]. +/// Returns null when even the link alone does not fit. +@visibleForTesting +String? composeIpfsLinkDraft({ + required String messageUrl, + required String existingText, + required int maxBytes, + required String Function(String text) encodeOutbound, +}) { + bool fits(String text) => + utf8.encode(encodeOutbound(text)).length <= maxBytes; + + final messageText = existingText.isEmpty + ? '$messageUrl ' + : '$messageUrl\n$existingText'; + if (fits(messageText)) return messageText; + if (existingText.isEmpty) return null; + + final originalCharacters = existingText.characters.toList(); + for (var count = originalCharacters.length - 1; count >= 0; count--) { + final candidate = '$messageUrl\n${originalCharacters.take(count).join()}'; + if (fits(candidate)) return candidate; + } + return null; +} diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 34a6bd90..ea3cce16 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -7,7 +7,6 @@ import 'package:flutter/foundation.dart' show mergeSort; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; -import 'package:file_selector/file_selector.dart' as file_selector; import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; @@ -19,7 +18,7 @@ import '../helpers/chat_scroll_controller.dart'; import '../connector/meshcore_protocol.dart'; import '../helpers/cyr2lat.dart'; import '../helpers/gif_helper.dart'; -import '../helpers/ipfs_upload_helper.dart'; +import '../helpers/ipfs_link_attach_flow.dart'; import '../helpers/marker_message.dart'; import '../helpers/message_url_image_helper.dart'; import '../helpers/path_helper.dart'; @@ -1313,111 +1312,16 @@ class _ChannelChatScreenState extends State { ); } - Future _sendImageViaIpfs() async { - final l10n = context.l10n; - final settings = context.read().settings; - if (settings.uploadIpfsEndpoint.trim().isEmpty) { - showDismissibleSnackBar( - context, - content: Text(l10n.chat_ipfsUploadNotConfigured), - ); - return; - } - - final file_selector.XFile? file; - try { - file = await file_selector.openFile(); - } on Exception catch (error) { - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.chat_ipfsUploadFailed('$error')), - ); - return; - } - if (file == null) return; - if (!mounted) return; - - final Uint8List bytes; - try { - bytes = await file.readAsBytes(); - } on Exception catch (error) { - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.chat_ipfsUploadFailed('$error')), - ); - return; - } - if (!mounted) return; - if (bytes.isEmpty) { - showDismissibleSnackBar( - context, - content: Text( - l10n.chat_ipfsUploadFailed('The selected file is empty.'), - ), - ); - return; - } - - final String messageUrl; - try { - messageUrl = await IpfsUploadHelper.uploadImageWithSettings( - settings: settings, - bytes: bytes, - fileName: file.name, - mimeType: IpfsUploadHelper.mimeTypeForFileName(file.name), - ); - } on Exception catch (error) { - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.chat_ipfsUploadFailed('$error')), - ); - return; - } - if (!mounted) return; - + Future _sendImageViaIpfs() { final connector = context.read(); - final existingText = _textController.text.trim(); - final combinedText = existingText.isEmpty - ? '$messageUrl ' - : '$messageUrl\n$existingText'; - final maxBytes = maxChannelMessageBytes(connector.selfName); - var messageText = combinedText; - var outboundText = connector.prepareChannelOutboundText( - widget.channel.index, - messageText, + return attachIpfsLinkToDraft( + context: context, + controller: _textController, + focusNode: _textFieldFocusNode, + maxBytes: maxChannelMessageBytes(connector.selfName), + encodeOutbound: (text) => + connector.prepareChannelOutboundText(widget.channel.index, text), ); - if (utf8.encode(outboundText).length > maxBytes && - existingText.isNotEmpty) { - final originalCharacters = existingText.characters.toList(); - for (var count = originalCharacters.length - 1; count >= 0; count--) { - final shortened = originalCharacters.take(count).join(); - final candidate = '$messageUrl\n$shortened'; - final encoded = connector.prepareChannelOutboundText( - widget.channel.index, - candidate, - ); - if (utf8.encode(encoded).length <= maxBytes) { - messageText = candidate; - outboundText = encoded; - break; - } - } - } - if (utf8.encode(outboundText).length > maxBytes) { - showDismissibleSnackBar( - context, - content: Text(context.l10n.chat_messageTooLong(maxBytes)), - ); - return; - } - _textController.value = TextEditingValue( - text: messageText, - selection: TextSelection.collapsed(offset: messageText.length), - ); - _textFieldFocusNode.requestFocus(); } /// Takes no [BuildContext]: it uses the [State]'s own, so the `mounted` diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 9275bc0f..81ea6577 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -5,7 +5,6 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; -import 'package:file_selector/file_selector.dart' as file_selector; import 'package:provider/provider.dart'; import '../utils/app_logger.dart'; @@ -21,7 +20,7 @@ import '../widgets/message_status_icon.dart'; import '../widgets/empty_state.dart'; import '../helpers/chat_scroll_controller.dart'; import '../helpers/gif_helper.dart'; -import '../helpers/ipfs_upload_helper.dart'; +import '../helpers/ipfs_link_attach_flow.dart'; import '../helpers/marker_message.dart'; import '../models/channel_message.dart'; import '../models/contact.dart'; @@ -563,110 +562,17 @@ class _ChatScreenState extends State { ); } - Future _sendImageViaIpfs() async { - final l10n = context.l10n; - final settings = context.read().settings; - if (settings.uploadIpfsEndpoint.trim().isEmpty) { - showDismissibleSnackBar( - context, - content: Text(l10n.chat_ipfsUploadNotConfigured), - ); - return; - } - - final file_selector.XFile? file; - try { - file = await file_selector.openFile(); - } on Exception catch (error) { - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.chat_ipfsUploadFailed('$error')), - ); - return; - } - if (file == null || !mounted) return; - - final Uint8List bytes; - try { - bytes = await file.readAsBytes(); - } on Exception catch (error) { - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.chat_ipfsUploadFailed('$error')), - ); - return; - } - if (!mounted) return; - if (bytes.isEmpty) { - showDismissibleSnackBar( - context, - content: Text( - l10n.chat_ipfsUploadFailed('The selected file is empty.'), - ), - ); - return; - } - - final String messageUrl; - try { - messageUrl = await IpfsUploadHelper.uploadImageWithSettings( - settings: settings, - bytes: bytes, - fileName: file.name, - mimeType: IpfsUploadHelper.mimeTypeForFileName(file.name), - ); - } on Exception catch (error) { - if (!mounted) return; - showDismissibleSnackBar( - context, - content: Text(l10n.chat_ipfsUploadFailed('$error')), - ); - return; - } - if (!mounted) return; - + Future _sendImageViaIpfs() { final connector = context.read(); final contact = _resolveContact(connector); - final existingText = _textController.text.trim(); - var messageText = existingText.isEmpty - ? '$messageUrl ' - : '$messageUrl\n$existingText'; - final maxBytes = maxContactMessageBytes(); - var encodedText = connector.prepareContactOutboundText( - contact, - messageText, + return attachIpfsLinkToDraft( + context: context, + controller: _textController, + focusNode: _textFieldFocusNode, + maxBytes: maxContactMessageBytes(), + encodeOutbound: (text) => + connector.prepareContactOutboundText(contact, text), ); - if (utf8.encode(encodedText).length > maxBytes && existingText.isNotEmpty) { - final originalCharacters = existingText.characters.toList(); - for (var count = originalCharacters.length - 1; count >= 0; count--) { - final shortened = originalCharacters.take(count).join(); - final candidate = '$messageUrl\n$shortened'; - final candidateEncoded = connector.prepareContactOutboundText( - contact, - candidate, - ); - if (utf8.encode(candidateEncoded).length <= maxBytes) { - messageText = candidate; - encodedText = candidateEncoded; - break; - } - } - } - if (utf8.encode(encodedText).length > maxBytes) { - showDismissibleSnackBar( - context, - content: Text(l10n.chat_messageTooLong(maxBytes)), - ); - return; - } - - _textController.value = TextEditingValue( - text: messageText, - selection: TextSelection.collapsed(offset: messageText.length), - ); - _textFieldFocusNode.requestFocus(); } /// Shares the radio's own position as a map marker. Shares the text send diff --git a/test/helpers/ipfs_link_attach_flow_test.dart b/test/helpers/ipfs_link_attach_flow_test.dart new file mode 100644 index 00000000..6c8603f1 --- /dev/null +++ b/test/helpers/ipfs_link_attach_flow_test.dart @@ -0,0 +1,76 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/ipfs_link_attach_flow.dart'; + +void main() { + const url = 'ipfs://cid'; + String identity(String text) => text; + + test('puts the link before an empty draft with a trailing space', () { + expect( + composeIpfsLinkDraft( + messageUrl: url, + existingText: '', + maxBytes: 100, + encodeOutbound: identity, + ), + '$url ', + ); + }); + + test('keeps a draft that fits after the link', () { + expect( + composeIpfsLinkDraft( + messageUrl: url, + existingText: 'hello', + maxBytes: 100, + encodeOutbound: identity, + ), + '$url\nhello', + ); + }); + + test('trims the draft until the encoded text fits', () { + expect( + composeIpfsLinkDraft( + messageUrl: url, + existingText: 'hello', + maxBytes: url.length + 3, + encodeOutbound: identity, + ), + '$url\nhe', + ); + }); + + test('measures the encoded form', () { + expect( + composeIpfsLinkDraft( + messageUrl: url, + existingText: 'hello', + maxBytes: url.length + 3, + encodeOutbound: (text) => 'x$text', + ), + '$url\nh', + ); + }); + + test('returns null when the link alone does not fit', () { + expect( + composeIpfsLinkDraft( + messageUrl: url, + existingText: 'hello', + maxBytes: 4, + encodeOutbound: identity, + ), + isNull, + ); + expect( + composeIpfsLinkDraft( + messageUrl: url, + existingText: '', + maxBytes: 4, + encodeOutbound: identity, + ), + isNull, + ); + }); +} From 084a8fb98bca17a7ea093a55452c0cf5dfe85028 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:53:47 -0700 Subject: [PATCH 09/15] Show IPFS upload configuration errors instead of failing silently Throw IpfsUploadConfigException for upload configuration problems, and route every failure in the attach flow to the user, so a missing key or bad endpoint no longer escapes as an unhandled ArgumentError. --- lib/helpers/ipfs_link_attach_flow.dart | 41 +++++++++++--------------- lib/helpers/ipfs_upload_helper.dart | 29 ++++++++++++++---- 2 files changed, 42 insertions(+), 28 deletions(-) diff --git a/lib/helpers/ipfs_link_attach_flow.dart b/lib/helpers/ipfs_link_attach_flow.dart index 99a3175a..a63c2534 100644 --- a/lib/helpers/ipfs_link_attach_flow.dart +++ b/lib/helpers/ipfs_link_attach_flow.dart @@ -1,7 +1,6 @@ import 'dart:convert'; import 'package:file_selector/file_selector.dart' as file_selector; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; @@ -42,30 +41,16 @@ Future attachIpfsLinkToDraft({ ); } - final file_selector.XFile? file; - try { - file = await file_selector.openFile(); - } on Exception catch (error) { - showFailure(error); - return; - } - if (file == null || !context.mounted) return; - - final Uint8List bytes; - try { - bytes = await file.readAsBytes(); - } on Exception catch (error) { - showFailure(error); - return; - } - if (!context.mounted) return; - if (bytes.isEmpty) { - showFailure('The selected file is empty.'); - return; - } - final String messageUrl; try { + final file = await file_selector.openFile(); + if (file == null || !context.mounted) return; + final bytes = await file.readAsBytes(); + if (!context.mounted) return; + if (bytes.isEmpty) { + showFailure('The selected file is empty.'); + return; + } messageUrl = await IpfsUploadHelper.uploadImageWithSettings( settings: settings, bytes: bytes, @@ -75,6 +60,16 @@ Future attachIpfsLinkToDraft({ } on Exception catch (error) { showFailure(error); return; + } catch (error, stackTrace) { + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stackTrace, + library: 'ipfs link attach', + ), + ); + showFailure(error); + return; } if (!context.mounted) return; diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart index 44da8b16..3a1c95dd 100644 --- a/lib/helpers/ipfs_upload_helper.dart +++ b/lib/helpers/ipfs_upload_helper.dart @@ -5,6 +5,17 @@ import 'package:http/http.dart' as http; import '../models/app_settings.dart'; +/// Thrown when the IPFS upload settings can't be used, before or instead of +/// a network failure. +class IpfsUploadConfigException implements Exception { + const IpfsUploadConfigException(this.message); + + final String message; + + @override + String toString() => message; +} + class IpfsUploadHelper { @visibleForTesting static http.Client? httpClient; @@ -55,14 +66,18 @@ class IpfsUploadHelper { }) async { final endpoint = uploadEndpoint.trim(); if (endpoint.isEmpty) { - throw Exception('Configure an IPFS upload endpoint first.'); + throw const IpfsUploadConfigException( + 'Configure an IPFS upload endpoint first.', + ); } final endpointUri = Uri.tryParse(endpoint); if (endpointUri == null || !(endpointUri.isScheme('http') || endpointUri.isScheme('https')) || endpointUri.host.isEmpty) { - throw Exception('The IPFS upload endpoint must be an http(s) URL.'); + throw const IpfsUploadConfigException( + 'The IPFS upload endpoint must be an http(s) URL.', + ); } final token = uploadApiKey.trim(); @@ -74,13 +89,17 @@ class IpfsUploadHelper { final isKubo = !isPinata && !isFilebase; final safeFileName = _sanitizeUploadFileName(fileName); if (isPinata && token.isEmpty) { - throw Exception('Pinata requires an API key or JWT.'); + throw const IpfsUploadConfigException( + 'Pinata requires an API key or JWT.', + ); } if (isFilebase && token.isEmpty) { - throw Exception('Filebase RPC requires an API token.'); + throw const IpfsUploadConfigException( + 'Filebase RPC requires an API token.', + ); } if (isKubo && !_kuboAddPath.hasMatch(endpointUri.path)) { - throw Exception( + throw const IpfsUploadConfigException( 'Custom (Kubo) upload endpoint must end with /api/v0/add.', ); } From 34db64d7af627e1dca761a397a0c9becbfbd3a62 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:55:57 -0700 Subject: [PATCH 10/15] Never silently truncate the draft when attaching an IPFS link Check before uploading that the link (from the gateway and a CIDv1-sized placeholder) fits with the draft and the reply prefix, and tell the user when it doesn't instead of cutting their text. The channel limit now counts the @[name] reply prefix like the send path. --- lib/helpers/ipfs_link_attach_flow.dart | 76 ++++++------ lib/helpers/ipfs_upload_helper.dart | 16 ++- lib/l10n/app_en.arb | 8 ++ lib/l10n/app_localizations.dart | 12 ++ lib/l10n/app_localizations_bg.dart | 8 ++ lib/l10n/app_localizations_de.dart | 8 ++ lib/l10n/app_localizations_en.dart | 8 ++ lib/l10n/app_localizations_es.dart | 8 ++ lib/l10n/app_localizations_fr.dart | 8 ++ lib/l10n/app_localizations_hu.dart | 8 ++ lib/l10n/app_localizations_it.dart | 8 ++ lib/l10n/app_localizations_ja.dart | 8 ++ lib/l10n/app_localizations_ko.dart | 8 ++ lib/l10n/app_localizations_nl.dart | 8 ++ lib/l10n/app_localizations_pl.dart | 8 ++ lib/l10n/app_localizations_pt.dart | 8 ++ lib/l10n/app_localizations_ru.dart | 8 ++ lib/l10n/app_localizations_sk.dart | 8 ++ lib/l10n/app_localizations_sl.dart | 8 ++ lib/l10n/app_localizations_sv.dart | 8 ++ lib/l10n/app_localizations_uk.dart | 8 ++ lib/l10n/app_localizations_zh.dart | 8 ++ lib/screens/channel_chat_screen.dart | 9 +- test/helpers/ipfs_link_attach_flow_test.dart | 119 +++++++++---------- untranslated.json | 34 ++++++ 25 files changed, 315 insertions(+), 103 deletions(-) diff --git a/lib/helpers/ipfs_link_attach_flow.dart b/lib/helpers/ipfs_link_attach_flow.dart index a63c2534..98bfa828 100644 --- a/lib/helpers/ipfs_link_attach_flow.dart +++ b/lib/helpers/ipfs_link_attach_flow.dart @@ -14,8 +14,10 @@ import 'snack_bar_builder.dart'; /// puts the resulting link at the start of the composer draft. /// /// [maxBytes] is the screen's outbound byte limit and [encodeOutbound] turns -/// draft text into what the radio would actually send, so the limit is -/// checked against the encoded form. +/// draft text into exactly what the send path measures (including any reply +/// prefix), so the limit is checked against that form. The draft is never +/// shortened: if the link won't fit, nothing is uploaded and the user is told +/// to shorten the message. Future attachIpfsLinkToDraft({ required BuildContext context, required TextEditingController controller, @@ -33,6 +35,25 @@ Future attachIpfsLinkToDraft({ return; } + String draftWithLink(String messageUrl) => composeIpfsLinkDraft( + messageUrl: messageUrl, + existingText: controller.text.trim(), + ); + bool fits(String draft) => ipfsLinkDraftFits( + draft, + maxBytes: maxBytes, + encodeOutbound: encodeOutbound, + ); + + final sampleLink = IpfsUploadHelper.linkForCid( + uploadGateway: settings.uploadIpfsGateway, + cid: IpfsUploadHelper.sampleCid, + ); + if (!fits(draftWithLink(sampleLink))) { + showDismissibleSnackBar(context, content: Text(l10n.chat_ipfsLinkNoRoom)); + return; + } + void showFailure(Object error) { if (!context.mounted) return; showDismissibleSnackBar( @@ -73,50 +94,31 @@ Future attachIpfsLinkToDraft({ } if (!context.mounted) return; - final messageText = composeIpfsLinkDraft( - messageUrl: messageUrl, - existingText: controller.text.trim(), - maxBytes: maxBytes, - encodeOutbound: encodeOutbound, - ); - if (messageText == null) { - showDismissibleSnackBar( - context, - content: Text(l10n.chat_messageTooLong(maxBytes)), - ); - return; - } - + final messageText = draftWithLink(messageUrl); controller.value = TextEditingValue( text: messageText, selection: TextSelection.collapsed(offset: messageText.length), ); focusNode.requestFocus(); + if (!fits(messageText)) { + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsLinkOverLimit), + ); + } } -/// Builds the draft with [messageUrl] in front of [existingText], trimming -/// [existingText] from the end until the encoded result fits [maxBytes]. -/// Returns null when even the link alone does not fit. +/// Puts [messageUrl] in front of [existingText], leaving the text intact. @visibleForTesting -String? composeIpfsLinkDraft({ +String composeIpfsLinkDraft({ required String messageUrl, required String existingText, +}) => existingText.isEmpty ? '$messageUrl ' : '$messageUrl\n$existingText'; + +/// Whether [draft], encoded the way the send path encodes it, fits [maxBytes]. +@visibleForTesting +bool ipfsLinkDraftFits( + String draft, { required int maxBytes, required String Function(String text) encodeOutbound, -}) { - bool fits(String text) => - utf8.encode(encodeOutbound(text)).length <= maxBytes; - - final messageText = existingText.isEmpty - ? '$messageUrl ' - : '$messageUrl\n$existingText'; - if (fits(messageText)) return messageText; - if (existingText.isEmpty) return null; - - final originalCharacters = existingText.characters.toList(); - for (var count = originalCharacters.length - 1; count >= 0; count--) { - final candidate = '$messageUrl\n${originalCharacters.take(count).join()}'; - if (fits(candidate)) return candidate; - } - return null; -} +}) => utf8.encode(encodeOutbound(draft.trim())).length <= maxBytes; diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart index 3a1c95dd..84c32e9d 100644 --- a/lib/helpers/ipfs_upload_helper.dart +++ b/lib/helpers/ipfs_upload_helper.dart @@ -22,6 +22,19 @@ class IpfsUploadHelper { static final _kuboAddPath = RegExp(r'/api/v0/add/?$'); + /// A CIDv1 (base32, sha2-256) as long as the CID of every upload, used to + /// size the link before uploading. + static const sampleCid = + 'bafkreihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'; + + static String linkForCid({ + required String uploadGateway, + required String cid, + }) { + final gateway = normalizeIpfsGateway(uploadGateway); + return gateway.isEmpty ? 'ipfs://$cid' : '$gateway$cid'; + } + static String mimeTypeForFileName(String fileName) { switch (fileName.toLowerCase().split('.').last) { case 'jpg': @@ -149,8 +162,7 @@ class IpfsUploadHelper { ); } - final gateway = normalizeIpfsGateway(uploadGateway); - return gateway.isEmpty ? 'ipfs://$cid' : '$gateway$cid'; + return linkForCid(uploadGateway: uploadGateway, cid: cid); } static Future _copyKuboFileToMfs({ diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 90f4b2a8..dc636bb3 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -953,6 +953,14 @@ } }, "chat_ipfsUploadNotConfigured": "Configure an IPFS upload provider in App Settings first.", + "chat_ipfsLinkNoRoom": "Not enough room for the image link. Shorten your message, then try again.", + "@chat_ipfsLinkNoRoom": { + "description": "Shown before an IPFS upload when the link would push the draft over the message size limit" + }, + "chat_ipfsLinkOverLimit": "Image link added, but the message is now too long. Shorten it before sending.", + "@chat_ipfsLinkOverLimit": { + "description": "Shown after an IPFS upload when the link plus the draft no longer fits the message size limit" + }, "chat_imagePickFailed": "Couldn't open that image", "@chat_imagePickFailed": { "description": "Shown when picking or reading a photo to send fails" diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 5c373c88..f0ef56b2 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3286,6 +3286,18 @@ abstract class AppLocalizations { /// **'Configure an IPFS upload provider in App Settings first.'** String get chat_ipfsUploadNotConfigured; + /// Shown before an IPFS upload when the link would push the draft over the message size limit + /// + /// In en, this message translates to: + /// **'Not enough room for the image link. Shorten your message, then try again.'** + String get chat_ipfsLinkNoRoom; + + /// Shown after an IPFS upload when the link plus the draft no longer fits the message size limit + /// + /// In en, this message translates to: + /// **'Image link added, but the message is now too long. Shorten it before sending.'** + String get chat_ipfsLinkOverLimit; + /// Shown when picking or reading a photo to send fails /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 3c2da765..8d8f2062 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1850,6 +1850,14 @@ class AppLocalizationsBg extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Не мог да откривам та изображин'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 1702dc5f..66d31e7c 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1849,6 +1849,14 @@ class AppLocalizationsDe extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Konnte dieses Bild nicht öffnen.'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 6a0d515e..eec87fe4 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1818,6 +1818,14 @@ class AppLocalizationsEn extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Couldn\'t open that image'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 84d219d6..a5941d81 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1845,6 +1845,14 @@ class AppLocalizationsEs extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'No pude abrir esa imagen'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index a6ec3d92..116726ec 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1849,6 +1849,14 @@ class AppLocalizationsFr extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Je n\'ai pas pu ouvrir cette image'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 3bca928f..2ffb5823 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1839,6 +1839,14 @@ class AppLocalizationsHu extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Nem tudtam ezt a fenti fényre kapni'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index f42acccf..50025be5 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1849,6 +1849,14 @@ class AppLocalizationsIt extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Non sono riuscito ad aprire quell\'immagine'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index c92b8eea..e62ca29b 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1762,6 +1762,14 @@ class AppLocalizationsJa extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'その画像を開けませんでした'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 98d004f4..e2968f56 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1767,6 +1767,14 @@ class AppLocalizationsKo extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => '그 이미지를 열 수 없었어요.'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 8e4c5505..4b64c5f5 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1835,6 +1835,14 @@ class AppLocalizationsNl extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Kon die afbeelding niet openen'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index c189c51f..6fc4644f 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1864,6 +1864,14 @@ class AppLocalizationsPl extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Nie mogłem otworzyć tego obrazu'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 4311bb90..bc7b746e 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1845,6 +1845,14 @@ class AppLocalizationsPt extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Não consegui abrir essa imagem'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 06aae2bd..0793eafe 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1849,6 +1849,14 @@ class AppLocalizationsRu extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Не удалось открыть это изображение'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 614f1129..efa338ae 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1837,6 +1837,14 @@ class AppLocalizationsSk extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Nesmiela jsem otvoriť tento obrázok'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index b413cb72..87154737 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1836,6 +1836,14 @@ class AppLocalizationsSl extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Nispeval sem tega ta slik'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index b5901e64..acbc7b41 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1824,6 +1824,14 @@ class AppLocalizationsSv extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Kunde inte öppna bilden'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 1c899a8b..65e1df41 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1839,6 +1839,14 @@ class AppLocalizationsUk extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => 'Неможливо відкрити це изображення'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index b731f733..43354856 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1742,6 +1742,14 @@ class AppLocalizationsZh extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsLinkNoRoom => + 'Not enough room for the image link. Shorten your message, then try again.'; + + @override + String get chat_ipfsLinkOverLimit => + 'Image link added, but the message is now too long. Shorten it before sending.'; + @override String get chat_imagePickFailed => '无法打开该图片'; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index ea3cce16..f0cbcc19 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1319,8 +1319,13 @@ class _ChannelChatScreenState extends State { controller: _textController, focusNode: _textFieldFocusNode, maxBytes: maxChannelMessageBytes(connector.selfName), - encodeOutbound: (text) => - connector.prepareChannelOutboundText(widget.channel.index, text), + encodeOutbound: (text) { + final replyTo = _replyingToMessage; + return connector.prepareChannelOutboundText( + widget.channel.index, + replyTo == null ? text : '${_replyPrefix(replyTo)}$text', + ); + }, ); } diff --git a/test/helpers/ipfs_link_attach_flow_test.dart b/test/helpers/ipfs_link_attach_flow_test.dart index 6c8603f1..b07d537d 100644 --- a/test/helpers/ipfs_link_attach_flow_test.dart +++ b/test/helpers/ipfs_link_attach_flow_test.dart @@ -1,76 +1,71 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/helpers/ipfs_link_attach_flow.dart'; +import 'package:meshcore_open/helpers/ipfs_upload_helper.dart'; void main() { const url = 'ipfs://cid'; String identity(String text) => text; - test('puts the link before an empty draft with a trailing space', () { - expect( - composeIpfsLinkDraft( - messageUrl: url, - existingText: '', - maxBytes: 100, - encodeOutbound: identity, - ), - '$url ', - ); + group('composeIpfsLinkDraft', () { + test('puts the link before an empty draft with a trailing space', () { + expect(composeIpfsLinkDraft(messageUrl: url, existingText: ''), '$url '); + }); + + test('keeps the whole draft after the link', () { + final draft = 'x' * 500; + expect( + composeIpfsLinkDraft(messageUrl: url, existingText: draft), + '$url\n$draft', + ); + }); }); - test('keeps a draft that fits after the link', () { - expect( - composeIpfsLinkDraft( - messageUrl: url, - existingText: 'hello', - maxBytes: 100, - encodeOutbound: identity, - ), - '$url\nhello', - ); + group('ipfsLinkDraftFits', () { + test('accepts a draft at the limit and rejects one byte over', () { + expect( + ipfsLinkDraftFits('$url\nhi', maxBytes: 13, encodeOutbound: identity), + isTrue, + ); + expect( + ipfsLinkDraftFits('$url\nhi', maxBytes: 12, encodeOutbound: identity), + isFalse, + ); + }); + + test('measures the encoded form, including a reply prefix', () { + String withReply(String text) => '@[Alice] $text'; + expect( + ipfsLinkDraftFits('$url\nhi', maxBytes: 13, encodeOutbound: withReply), + isFalse, + ); + expect( + ipfsLinkDraftFits('$url\nhi', maxBytes: 22, encodeOutbound: withReply), + isTrue, + ); + }); + + test('ignores the trailing space the send path trims', () { + expect( + ipfsLinkDraftFits( + '$url ', + maxBytes: url.length, + encodeOutbound: identity, + ), + isTrue, + ); + }); }); - test('trims the draft until the encoded text fits', () { - expect( - composeIpfsLinkDraft( - messageUrl: url, - existingText: 'hello', - maxBytes: url.length + 3, - encodeOutbound: identity, - ), - '$url\nhe', - ); - }); + group('IpfsUploadHelper.linkForCid', () { + test('uses ipfs:// without a gateway', () { + expect( + IpfsUploadHelper.linkForCid(uploadGateway: '', cid: 'abc'), + 'ipfs://abc', + ); + }); - test('measures the encoded form', () { - expect( - composeIpfsLinkDraft( - messageUrl: url, - existingText: 'hello', - maxBytes: url.length + 3, - encodeOutbound: (text) => 'x$text', - ), - '$url\nh', - ); - }); - - test('returns null when the link alone does not fit', () { - expect( - composeIpfsLinkDraft( - messageUrl: url, - existingText: 'hello', - maxBytes: 4, - encodeOutbound: identity, - ), - isNull, - ); - expect( - composeIpfsLinkDraft( - messageUrl: url, - existingText: '', - maxBytes: 4, - encodeOutbound: identity, - ), - isNull, - ); + test('sample CID is CIDv1 base32 length', () { + expect(IpfsUploadHelper.sampleCid.length, 59); + }); }); } diff --git a/untranslated.json b/untranslated.json index 337d70f9..bf46ed3d 100644 --- a/untranslated.json +++ b/untranslated.json @@ -21,6 +21,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -64,6 +66,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -107,6 +111,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -150,6 +156,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -193,6 +201,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -236,6 +246,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -279,6 +291,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -322,6 +336,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -365,6 +381,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -408,6 +426,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -451,6 +471,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -494,6 +516,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -537,6 +561,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -580,6 +606,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -623,6 +651,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -666,6 +696,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", @@ -709,6 +741,8 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsLinkNoRoom", + "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", "map_pathTraceModeRoundTrip", "map_pathTraceModeRoundTripHint", From c111835bd0c45978580860fd26b307752449fccd Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:57:12 -0700 Subject: [PATCH 11/15] Localize IPFS upload and attach messages Give IpfsUploadConfigException a reason enum mapped to l10n strings in the attach flow, and show a localized empty-file message and generic upload-failed message instead of raw English exception text. --- lib/helpers/ipfs_link_attach_flow.dart | 27 ++++++- lib/helpers/ipfs_upload_helper.dart | 31 ++++--- lib/l10n/app_en.arb | 5 ++ lib/l10n/app_localizations.dart | 30 +++++++ lib/l10n/app_localizations_bg.dart | 19 +++++ lib/l10n/app_localizations_de.dart | 19 +++++ lib/l10n/app_localizations_en.dart | 19 +++++ lib/l10n/app_localizations_es.dart | 19 +++++ lib/l10n/app_localizations_fr.dart | 19 +++++ lib/l10n/app_localizations_hu.dart | 19 +++++ lib/l10n/app_localizations_it.dart | 19 +++++ lib/l10n/app_localizations_ja.dart | 19 +++++ lib/l10n/app_localizations_ko.dart | 19 +++++ lib/l10n/app_localizations_nl.dart | 19 +++++ lib/l10n/app_localizations_pl.dart | 19 +++++ lib/l10n/app_localizations_pt.dart | 19 +++++ lib/l10n/app_localizations_ru.dart | 19 +++++ lib/l10n/app_localizations_sk.dart | 19 +++++ lib/l10n/app_localizations_sl.dart | 19 +++++ lib/l10n/app_localizations_sv.dart | 19 +++++ lib/l10n/app_localizations_uk.dart | 19 +++++ lib/l10n/app_localizations_zh.dart | 19 +++++ test/helpers/ipfs_link_attach_flow_test.dart | 29 +++++++ untranslated.json | 85 ++++++++++++++++++++ 24 files changed, 536 insertions(+), 13 deletions(-) diff --git a/lib/helpers/ipfs_link_attach_flow.dart b/lib/helpers/ipfs_link_attach_flow.dart index 98bfa828..e1cb6530 100644 --- a/lib/helpers/ipfs_link_attach_flow.dart +++ b/lib/helpers/ipfs_link_attach_flow.dart @@ -4,6 +4,7 @@ import 'package:file_selector/file_selector.dart' as file_selector; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; +import '../l10n/app_localizations.dart'; import '../l10n/l10n.dart'; import '../services/app_settings_service.dart'; import 'ipfs_upload_helper.dart'; @@ -58,7 +59,7 @@ Future attachIpfsLinkToDraft({ if (!context.mounted) return; showDismissibleSnackBar( context, - content: Text(l10n.chat_ipfsUploadFailed('$error')), + content: Text(ipfsUploadErrorText(l10n, error)), ); } @@ -69,7 +70,10 @@ Future attachIpfsLinkToDraft({ final bytes = await file.readAsBytes(); if (!context.mounted) return; if (bytes.isEmpty) { - showFailure('The selected file is empty.'); + showDismissibleSnackBar( + context, + content: Text(l10n.chat_ipfsSelectedFileEmpty), + ); return; } messageUrl = await IpfsUploadHelper.uploadImageWithSettings( @@ -108,6 +112,25 @@ Future attachIpfsLinkToDraft({ } } +/// The localized snackbar text for an upload [error]: config problems get a +/// specific message, anything else a generic one with technical details. +@visibleForTesting +String ipfsUploadErrorText(AppLocalizations l10n, Object error) { + if (error is IpfsUploadConfigException) { + return switch (error.reason) { + IpfsUploadConfigError.emptyEndpoint => l10n.chat_ipfsUploadNotConfigured, + IpfsUploadConfigError.invalidEndpoint => l10n.chat_ipfsEndpointInvalid, + IpfsUploadConfigError.pinataTokenMissing => + l10n.chat_ipfsPinataTokenMissing, + IpfsUploadConfigError.filebaseTokenMissing => + l10n.chat_ipfsFilebaseTokenMissing, + IpfsUploadConfigError.kuboPathInvalid => l10n.chat_ipfsKuboPathInvalid, + }; + } + final details = '$error'.replaceFirst(RegExp(r'^Exception: '), ''); + return l10n.chat_ipfsUploadFailed(details); +} + /// Puts [messageUrl] in front of [existingText], leaving the text intact. @visibleForTesting String composeIpfsLinkDraft({ diff --git a/lib/helpers/ipfs_upload_helper.dart b/lib/helpers/ipfs_upload_helper.dart index 84c32e9d..7f6e36e1 100644 --- a/lib/helpers/ipfs_upload_helper.dart +++ b/lib/helpers/ipfs_upload_helper.dart @@ -5,15 +5,24 @@ import 'package:http/http.dart' as http; import '../models/app_settings.dart'; -/// Thrown when the IPFS upload settings can't be used, before or instead of -/// a network failure. -class IpfsUploadConfigException implements Exception { - const IpfsUploadConfigException(this.message); +/// Why the IPFS upload settings can't be used. +enum IpfsUploadConfigError { + emptyEndpoint, + invalidEndpoint, + pinataTokenMissing, + filebaseTokenMissing, + kuboPathInvalid, +} - final String message; +/// Thrown when the IPFS upload settings can't be used, before or instead of +/// a network failure. The UI maps [reason] to a localized message. +class IpfsUploadConfigException implements Exception { + const IpfsUploadConfigException(this.reason); + + final IpfsUploadConfigError reason; @override - String toString() => message; + String toString() => 'IpfsUploadConfigException(${reason.name})'; } class IpfsUploadHelper { @@ -80,7 +89,7 @@ class IpfsUploadHelper { final endpoint = uploadEndpoint.trim(); if (endpoint.isEmpty) { throw const IpfsUploadConfigException( - 'Configure an IPFS upload endpoint first.', + IpfsUploadConfigError.emptyEndpoint, ); } @@ -89,7 +98,7 @@ class IpfsUploadHelper { !(endpointUri.isScheme('http') || endpointUri.isScheme('https')) || endpointUri.host.isEmpty) { throw const IpfsUploadConfigException( - 'The IPFS upload endpoint must be an http(s) URL.', + IpfsUploadConfigError.invalidEndpoint, ); } @@ -103,17 +112,17 @@ class IpfsUploadHelper { final safeFileName = _sanitizeUploadFileName(fileName); if (isPinata && token.isEmpty) { throw const IpfsUploadConfigException( - 'Pinata requires an API key or JWT.', + IpfsUploadConfigError.pinataTokenMissing, ); } if (isFilebase && token.isEmpty) { throw const IpfsUploadConfigException( - 'Filebase RPC requires an API token.', + IpfsUploadConfigError.filebaseTokenMissing, ); } if (isKubo && !_kuboAddPath.hasMatch(endpointUri.path)) { throw const IpfsUploadConfigException( - 'Custom (Kubo) upload endpoint must end with /api/v0/add.', + IpfsUploadConfigError.kuboPathInvalid, ); } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index dc636bb3..a983cd68 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -953,6 +953,11 @@ } }, "chat_ipfsUploadNotConfigured": "Configure an IPFS upload provider in App Settings first.", + "chat_ipfsSelectedFileEmpty": "The selected file is empty.", + "chat_ipfsEndpointInvalid": "The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.", + "chat_ipfsPinataTokenMissing": "Pinata needs an API key or JWT. Add it in App Settings.", + "chat_ipfsFilebaseTokenMissing": "Filebase needs an API token. Add it in App Settings.", + "chat_ipfsKuboPathInvalid": "The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.", "chat_ipfsLinkNoRoom": "Not enough room for the image link. Shorten your message, then try again.", "@chat_ipfsLinkNoRoom": { "description": "Shown before an IPFS upload when the link would push the draft over the message size limit" diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index f0ef56b2..ddf5d278 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3286,6 +3286,36 @@ abstract class AppLocalizations { /// **'Configure an IPFS upload provider in App Settings first.'** String get chat_ipfsUploadNotConfigured; + /// No description provided for @chat_ipfsSelectedFileEmpty. + /// + /// In en, this message translates to: + /// **'The selected file is empty.'** + String get chat_ipfsSelectedFileEmpty; + + /// No description provided for @chat_ipfsEndpointInvalid. + /// + /// In en, this message translates to: + /// **'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'** + String get chat_ipfsEndpointInvalid; + + /// No description provided for @chat_ipfsPinataTokenMissing. + /// + /// In en, this message translates to: + /// **'Pinata needs an API key or JWT. Add it in App Settings.'** + String get chat_ipfsPinataTokenMissing; + + /// No description provided for @chat_ipfsFilebaseTokenMissing. + /// + /// In en, this message translates to: + /// **'Filebase needs an API token. Add it in App Settings.'** + String get chat_ipfsFilebaseTokenMissing; + + /// No description provided for @chat_ipfsKuboPathInvalid. + /// + /// In en, this message translates to: + /// **'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'** + String get chat_ipfsKuboPathInvalid; + /// Shown before an IPFS upload when the link would push the draft over the message size limit /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 8d8f2062..07d5a4b4 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1850,6 +1850,25 @@ class AppLocalizationsBg extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 66d31e7c..029d73b0 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1849,6 +1849,25 @@ class AppLocalizationsDe extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index eec87fe4..9a3ad0e1 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1818,6 +1818,25 @@ class AppLocalizationsEn extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index a5941d81..224bcffb 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1845,6 +1845,25 @@ class AppLocalizationsEs extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 116726ec..dbf6d032 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1849,6 +1849,25 @@ class AppLocalizationsFr extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 2ffb5823..99c64638 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1839,6 +1839,25 @@ class AppLocalizationsHu extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 50025be5..664fcfeb 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1849,6 +1849,25 @@ class AppLocalizationsIt extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index e62ca29b..a13697ac 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1762,6 +1762,25 @@ class AppLocalizationsJa extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index e2968f56..877eef52 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1767,6 +1767,25 @@ class AppLocalizationsKo extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 4b64c5f5..a976169b 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1835,6 +1835,25 @@ class AppLocalizationsNl extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 6fc4644f..86a88110 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1864,6 +1864,25 @@ class AppLocalizationsPl extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index bc7b746e..3eab9ac0 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1845,6 +1845,25 @@ class AppLocalizationsPt extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 0793eafe..3c296bfc 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1849,6 +1849,25 @@ class AppLocalizationsRu extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index efa338ae..db844a58 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1837,6 +1837,25 @@ class AppLocalizationsSk extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 87154737..2cdd59bf 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1836,6 +1836,25 @@ class AppLocalizationsSl extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index acbc7b41..436bdb62 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1824,6 +1824,25 @@ class AppLocalizationsSv extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 65e1df41..02b3bc27 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1839,6 +1839,25 @@ class AppLocalizationsUk extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 43354856..4dd1ee28 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1742,6 +1742,25 @@ class AppLocalizationsZh extends AppLocalizations { String get chat_ipfsUploadNotConfigured => 'Configure an IPFS upload provider in App Settings first.'; + @override + String get chat_ipfsSelectedFileEmpty => 'The selected file is empty.'; + + @override + String get chat_ipfsEndpointInvalid => + 'The IPFS upload endpoint must be a full http:// or https:// address. Check it in App Settings.'; + + @override + String get chat_ipfsPinataTokenMissing => + 'Pinata needs an API key or JWT. Add it in App Settings.'; + + @override + String get chat_ipfsFilebaseTokenMissing => + 'Filebase needs an API token. Add it in App Settings.'; + + @override + String get chat_ipfsKuboPathInvalid => + 'The Kubo upload endpoint must end with /api/v0/add. Check it in App Settings.'; + @override String get chat_ipfsLinkNoRoom => 'Not enough room for the image link. Shorten your message, then try again.'; diff --git a/test/helpers/ipfs_link_attach_flow_test.dart b/test/helpers/ipfs_link_attach_flow_test.dart index b07d537d..2859752e 100644 --- a/test/helpers/ipfs_link_attach_flow_test.dart +++ b/test/helpers/ipfs_link_attach_flow_test.dart @@ -1,6 +1,8 @@ +import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/helpers/ipfs_link_attach_flow.dart'; import 'package:meshcore_open/helpers/ipfs_upload_helper.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; void main() { const url = 'ipfs://cid'; @@ -68,4 +70,31 @@ void main() { expect(IpfsUploadHelper.sampleCid.length, 59); }); }); + + group('ipfsUploadErrorText', () { + final l10n = lookupAppLocalizations(const Locale('en')); + + test('gives every config reason its own localized message', () { + final texts = { + for (final reason in IpfsUploadConfigError.values) + reason: ipfsUploadErrorText(l10n, IpfsUploadConfigException(reason)), + }; + expect( + texts[IpfsUploadConfigError.emptyEndpoint], + l10n.chat_ipfsUploadNotConfigured, + ); + expect( + texts[IpfsUploadConfigError.kuboPathInvalid], + l10n.chat_ipfsKuboPathInvalid, + ); + expect(texts.values.toSet(), hasLength(texts.length)); + }); + + test('wraps other errors in the generic message without the prefix', () { + expect( + ipfsUploadErrorText(l10n, Exception('IPFS upload failed (500): x')), + l10n.chat_ipfsUploadFailed('IPFS upload failed (500): x'), + ); + }); + }); } diff --git a/untranslated.json b/untranslated.json index bf46ed3d..370fa376 100644 --- a/untranslated.json +++ b/untranslated.json @@ -21,6 +21,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -66,6 +71,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -111,6 +121,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -156,6 +171,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -201,6 +221,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -246,6 +271,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -291,6 +321,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -336,6 +371,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -381,6 +421,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -426,6 +471,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -471,6 +521,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -516,6 +571,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -561,6 +621,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -606,6 +671,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -651,6 +721,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -696,6 +771,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", @@ -741,6 +821,11 @@ "chat_sendImageIpfs", "chat_ipfsUploadFailed", "chat_ipfsUploadNotConfigured", + "chat_ipfsSelectedFileEmpty", + "chat_ipfsEndpointInvalid", + "chat_ipfsPinataTokenMissing", + "chat_ipfsFilebaseTokenMissing", + "chat_ipfsKuboPathInvalid", "chat_ipfsLinkNoRoom", "chat_ipfsLinkOverLimit", "map_pathTraceAddMoreHint", From ee302f647b0dfd0d2f4c5e02c21567136749c831 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:51:55 -0700 Subject: [PATCH 12/15] Keep the public IPFS gateway the user chose Default to https://ipfs.io/ipfs/ like dev, keep saved gateways as they are, and keep an explicitly cleared gateway deactivated across restarts instead of rewriting public gateways to empty on every load. --- lib/models/app_settings.dart | 19 ++---------- .../message_url_image_helper_test.dart | 31 +++++++++---------- test/models/model_changes_test.dart | 24 +++++++++++--- 3 files changed, 37 insertions(+), 37 deletions(-) diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index f8efacec..64ccbfad 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -17,18 +17,6 @@ String normalizeIpfsGateway(String value) { return gateway; } -String migratePublicIpfsGateway(String? value) { - final gateway = value?.trim(); - if (gateway == null || - gateway == 'https://ipfs.io/ipfs/' || - gateway == 'https://ipfs.io/ipfs' || - gateway == 'https://dweb.link/ipfs/' || - gateway == 'https://dweb.link/ipfs') { - return AppSettings.defaultPublicIpfsGateway; - } - return gateway; -} - enum ChannelNotificationMode { all, mentionsOnly, muted } extension UnitSystemValue on UnitSystem { @@ -106,7 +94,7 @@ class Cyr2LatProfile { class AppSettings { static const Object _unset = Object(); static const String stadiaDemo = '51bd0381-4685-4666-bae8-48940f6d77c0'; - static const String defaultPublicIpfsGateway = ''; + static const String defaultPublicIpfsGateway = 'https://ipfs.io/ipfs/'; final bool clearPathOnMaxRetry; final bool mapShowRepeaters; @@ -517,9 +505,8 @@ class AppSettings { networkMapUploadEnabled: json['network_map_upload_enabled'] as bool? ?? false, networkMapPromptShown: json['network_map_prompt_shown'] as bool? ?? false, - publicIpfsGateway: migratePublicIpfsGateway( - json['public_ipfs_gateway'] as String?, - ), + publicIpfsGateway: + json['public_ipfs_gateway'] as String? ?? defaultPublicIpfsGateway, uploadIpfsGateway: json['upload_ipfs_gateway'] as String? ?? '', uploadIpfsEndpoint: json['upload_ipfs_endpoint'] as String? ?? '', uploadIpfsApiKey: json['upload_ipfs_api_key'] as String? ?? '', diff --git a/test/helpers/message_url_image_helper_test.dart b/test/helpers/message_url_image_helper_test.dart index c9cce83b..900b0a01 100644 --- a/test/helpers/message_url_image_helper_test.dart +++ b/test/helpers/message_url_image_helper_test.dart @@ -48,23 +48,20 @@ void main() { ); }); - test( - 'does not resolve ipfs cid links with the default gateway deactivated', - () async { - expect( - await MessageUrlImageHelper.parse( - 'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', - ), - isNull, - ); - expect( - await MessageUrlImageHelper.parse( - 'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', - ), - isNull, - ); - }, - ); + test('resolves ipfs cid links with the default ipfs.io gateway', () async { + expect( + await MessageUrlImageHelper.parse( + 'my picture: ipfs://bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ), + 'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + ); + expect( + await MessageUrlImageHelper.parse( + 'my picture: ipfs:bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly text', + ), + 'https://ipfs.io/ipfs/bafybeibq75ws6nwk6wi473dch42wwy6woyj4dwdfy7nfz3buqx2caieoly', + ); + }); test('uses the configured public gateway for direct ipfs cid urls', () async { final attachment = await MessageUrlImageHelper.parse( diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index 078aa2b3..94a7eb2a 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -443,12 +443,28 @@ void main() { expect(settings.evictDiscoveredContactsEnabled, isFalse); }); - test('public IPFS gateway defaults to deactivated and preserves empty', () { - expect(AppSettings.fromJson({}).publicIpfsGateway, isEmpty); + test('public IPFS gateway defaults to ipfs.io when never set', () { expect( - AppSettings.fromJson({'public_ipfs_gateway': ''}).publicIpfsGateway, - isEmpty, + AppSettings.fromJson({}).publicIpfsGateway, + 'https://ipfs.io/ipfs/', ); + expect(AppSettings().publicIpfsGateway, 'https://ipfs.io/ipfs/'); + }); + + test('public IPFS gateway keeps a saved empty value as deactivated', () { + final saved = AppSettings(publicIpfsGateway: '').toJson(); + expect(AppSettings.fromJson(saved).publicIpfsGateway, isEmpty); + }); + + test('public IPFS gateway keeps saved ipfs.io and dweb.link values', () { + for (final gateway in [ + 'https://ipfs.io/ipfs/', + 'https://dweb.link/ipfs/', + 'https://gateway.example.com/ipfs/', + ]) { + final saved = AppSettings(publicIpfsGateway: gateway).toJson(); + expect(AppSettings.fromJson(saved).publicIpfsGateway, gateway); + } }); test('empty upload gateway does not fall back to the download gateway', () { From 7f5f71d0701615711b981d93346ca908670aac9f Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:53:23 -0700 Subject: [PATCH 13/15] Hide the IPFS API key and keep keyboard focus from corrupting it Obscure the key with a show/hide toggle like the map API key dialog, clear and restore the mask on focus changes instead of onTap, and only save a key the user actually edited. Add ipfs.io as a named public gateway preset now that it is the default. --- lib/l10n/app_en.arb | 1 + lib/l10n/app_localizations.dart | 6 ++++ lib/l10n/app_localizations_bg.dart | 3 ++ lib/l10n/app_localizations_de.dart | 3 ++ lib/l10n/app_localizations_en.dart | 3 ++ lib/l10n/app_localizations_es.dart | 3 ++ lib/l10n/app_localizations_fr.dart | 3 ++ lib/l10n/app_localizations_hu.dart | 3 ++ lib/l10n/app_localizations_it.dart | 3 ++ lib/l10n/app_localizations_ja.dart | 3 ++ lib/l10n/app_localizations_ko.dart | 3 ++ lib/l10n/app_localizations_nl.dart | 3 ++ lib/l10n/app_localizations_pl.dart | 3 ++ lib/l10n/app_localizations_pt.dart | 3 ++ lib/l10n/app_localizations_ru.dart | 3 ++ lib/l10n/app_localizations_sk.dart | 3 ++ lib/l10n/app_localizations_sl.dart | 3 ++ lib/l10n/app_localizations_sv.dart | 3 ++ lib/l10n/app_localizations_uk.dart | 3 ++ lib/l10n/app_localizations_zh.dart | 3 ++ lib/screens/app_settings_screen.dart | 49 ++++++++++++++++++++++------ untranslated.json | 17 ++++++++++ 22 files changed, 117 insertions(+), 10 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index a983cd68..1849de8e 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -457,6 +457,7 @@ "appSettings_ipfsImageLinksSubtitle": "Upload for url Images (or Files) via IPFS provider and default gateway to receive", "appSettings_publicIpfsGateway": "Public gateway", "appSettings_ipfsGatewayDeactivated": "Deactivated", + "appSettings_ipfsGatewayIpfsIo": "ipfs.io", "appSettings_ipfsGatewayPinata": "Pinata", "appSettings_ipfsGatewayFilebase": "Filebase", "appSettings_ipfsGatewayCustom": "Custom (Kubo)", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index ddf5d278..78a0b15e 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -1978,6 +1978,12 @@ abstract class AppLocalizations { /// **'Deactivated'** String get appSettings_ipfsGatewayDeactivated; + /// No description provided for @appSettings_ipfsGatewayIpfsIo. + /// + /// In en, this message translates to: + /// **'ipfs.io'** + String get appSettings_ipfsGatewayIpfsIo; + /// No description provided for @appSettings_ipfsGatewayPinata. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 07d5a4b4..b40cbd33 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1089,6 +1089,9 @@ class AppLocalizationsBg extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 029d73b0..232197ba 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1084,6 +1084,9 @@ class AppLocalizationsDe extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 9a3ad0e1..25256f93 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1068,6 +1068,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 224bcffb..a5ed0764 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1081,6 +1081,9 @@ class AppLocalizationsEs extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index dbf6d032..4b9bfcde 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1087,6 +1087,9 @@ class AppLocalizationsFr extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 99c64638..79c968e1 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1076,6 +1076,9 @@ class AppLocalizationsHu extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 664fcfeb..4768156b 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1087,6 +1087,9 @@ class AppLocalizationsIt extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index a13697ac..9057572a 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1024,6 +1024,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 877eef52..75e8cc06 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1028,6 +1028,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index a976169b..4b99bcfd 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1077,6 +1077,9 @@ class AppLocalizationsNl extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 86a88110..500eadcb 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1093,6 +1093,9 @@ class AppLocalizationsPl extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 3eab9ac0..af1d3ca4 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1085,6 +1085,9 @@ class AppLocalizationsPt extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 3c296bfc..13d4ac7f 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1090,6 +1090,9 @@ class AppLocalizationsRu extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index db844a58..7e429e7d 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1076,6 +1076,9 @@ class AppLocalizationsSk extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 2cdd59bf..d04579ac 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1078,6 +1078,9 @@ class AppLocalizationsSl extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 436bdb62..b0e614da 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1067,6 +1067,9 @@ class AppLocalizationsSv extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 02b3bc27..83d6424a 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1080,6 +1080,9 @@ class AppLocalizationsUk extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 4dd1ee28..714864c6 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1008,6 +1008,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get appSettings_ipfsGatewayDeactivated => 'Deactivated'; + @override + String get appSettings_ipfsGatewayIpfsIo => 'ipfs.io'; + @override String get appSettings_ipfsGatewayPinata => 'Pinata'; diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 16a21dc1..5feadfcc 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -1526,12 +1526,13 @@ class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { late final TextEditingController _uploadGatewayController; late final TextEditingController _endpointController; late final TextEditingController _apiKeyController; + final FocusNode _apiKeyFocus = FocusNode(); late final String _currentApiKey; late final String _maskedApiKey; late String _selectedGateway; late String _selectedUploadProvider; - bool _apiKeyEditing = false; bool _apiKeyChanged = false; + bool _apiKeyObscured = true; @override void initState() { @@ -1549,6 +1550,7 @@ class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { _currentApiKey = settings.uploadIpfsApiKey.trim(); _maskedApiKey = _currentApiKey.isEmpty ? '' : _maskApiKey(_currentApiKey); _apiKeyController = TextEditingController(text: _maskedApiKey); + _apiKeyFocus.addListener(_onApiKeyFocusChanged); _selectedGateway = _gatewayPreset(_publicController.text); _selectedUploadProvider = _uploadProvider( _uploadGatewayController.text, @@ -1563,9 +1565,18 @@ class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { _uploadGatewayController.dispose(); _endpointController.dispose(); _apiKeyController.dispose(); + _apiKeyFocus.dispose(); super.dispose(); } + /// Swaps the masked key out while the field has focus (by tap, Tab or + /// keyboard) so typing never appends to the mask, and puts it back if the + /// user leaves without editing. + void _onApiKeyFocusChanged() { + if (_apiKeyChanged) return; + _apiKeyController.text = _apiKeyFocus.hasFocus ? '' : _maskedApiKey; + } + @override Widget build(BuildContext context) { final l10n = context.l10n; @@ -1588,6 +1599,10 @@ class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { value: 'deactivated', child: Text(l10n.appSettings_ipfsGatewayDeactivated), ), + DropdownMenuItem( + value: 'ipfsio', + child: Text(l10n.appSettings_ipfsGatewayIpfsIo), + ), DropdownMenuItem( value: 'pinata', child: Text(l10n.appSettings_ipfsGatewayPinata), @@ -1671,18 +1686,25 @@ class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { const SizedBox(height: 10), TextField( controller: _apiKeyController, + focusNode: _apiKeyFocus, decoration: InputDecoration( labelText: l10n.appSettings_uploadIpfsApiKey, + suffixIcon: IconButton( + tooltip: _apiKeyObscured + ? l10n.appSettings_showApiKey + : l10n.appSettings_hideApiKey, + icon: Icon( + _apiKeyObscured + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + ), + onPressed: () => + setState(() => _apiKeyObscured = !_apiKeyObscured), + ), ), autocorrect: false, enableSuggestions: false, - onTap: () { - if (_apiKeyEditing) return; - setState(() { - _apiKeyEditing = true; - _apiKeyController.clear(); - }); - }, + obscureText: _apiKeyObscured, onChanged: (_) { _apiKeyChanged = true; _markCustomUploadProvider(); @@ -1731,14 +1753,15 @@ class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { Future _save() async { final deactivated = _selectedUploadProvider == 'deactivated'; + final apiKey = _apiKeyController.text.trim(); await widget.settingsService.setIpfsImageSettings( publicGateway: _publicController.text, uploadGateway: deactivated ? '' : _uploadGatewayController.text, uploadEndpoint: deactivated ? '' : _endpointController.text, uploadApiKey: deactivated ? '' - : _apiKeyChanged - ? _apiKeyController.text + : _apiKeyChanged && apiKey != _maskedApiKey + ? apiKey : _currentApiKey, ); if (mounted) Navigator.pop(context); @@ -1746,6 +1769,10 @@ class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { String _gatewayPreset(String value) { if (value.isEmpty) return 'deactivated'; + if (value == AppSettings.defaultPublicIpfsGateway || + value == 'https://ipfs.io/ipfs') { + return 'ipfsio'; + } if (value == 'https://gateway.pinata.cloud/ipfs/' || value == 'https://gateway.pinata.cloud/ipfs') { return 'pinata'; @@ -1761,6 +1788,8 @@ class _IpfsImageLinksDialogState extends State<_IpfsImageLinksDialog> { switch (preset) { case 'deactivated': return ''; + case 'ipfsio': + return AppSettings.defaultPublicIpfsGateway; case 'pinata': return 'https://gateway.pinata.cloud/ipfs/'; case 'filebase': diff --git a/untranslated.json b/untranslated.json index 370fa376..73747889 100644 --- a/untranslated.json +++ b/untranslated.json @@ -5,6 +5,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -55,6 +56,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -105,6 +107,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -155,6 +158,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -205,6 +209,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -255,6 +260,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -305,6 +311,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -355,6 +362,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -405,6 +413,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -455,6 +464,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -505,6 +515,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -555,6 +566,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -605,6 +617,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -655,6 +668,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -705,6 +719,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -755,6 +770,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", @@ -805,6 +821,7 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", + "appSettings_ipfsGatewayIpfsIo", "appSettings_ipfsGatewayPinata", "appSettings_ipfsGatewayFilebase", "appSettings_ipfsGatewayCustom", From 79e3668c18f92026831ba8764b1a8b97e44a68a4 Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 21:58:09 -0700 Subject: [PATCH 14/15] Add a global switch to stop loading images from links 'Load images from links' (default on) gates every link image fetch in MessageUrlImageHelper: chat previews, notification images, ipfs:// resolution and pyx/ibb scraping. Per-chat toggles keep their values but are disabled while it is off. IPFS uploads are unaffected. --- lib/helpers/message_url_image_helper.dart | 48 ++++++++++------- lib/l10n/app_en.arb | 3 ++ lib/l10n/app_localizations.dart | 18 +++++++ lib/l10n/app_localizations_bg.dart | 10 ++++ lib/l10n/app_localizations_de.dart | 10 ++++ lib/l10n/app_localizations_en.dart | 10 ++++ lib/l10n/app_localizations_es.dart | 10 ++++ lib/l10n/app_localizations_fr.dart | 10 ++++ lib/l10n/app_localizations_hu.dart | 10 ++++ lib/l10n/app_localizations_it.dart | 10 ++++ lib/l10n/app_localizations_ja.dart | 10 ++++ lib/l10n/app_localizations_ko.dart | 10 ++++ lib/l10n/app_localizations_nl.dart | 10 ++++ lib/l10n/app_localizations_pl.dart | 10 ++++ lib/l10n/app_localizations_pt.dart | 10 ++++ lib/l10n/app_localizations_ru.dart | 10 ++++ lib/l10n/app_localizations_sk.dart | 10 ++++ lib/l10n/app_localizations_sl.dart | 10 ++++ lib/l10n/app_localizations_sv.dart | 10 ++++ lib/l10n/app_localizations_uk.dart | 10 ++++ lib/l10n/app_localizations_zh.dart | 10 ++++ lib/main.dart | 5 ++ lib/models/app_settings.dart | 8 +++ lib/screens/app_settings_screen.dart | 12 +++++ lib/screens/channel_chat_screen.dart | 7 +-- lib/screens/channels_screen.dart | 15 +++++- lib/screens/chat_screen.dart | 30 +++++++---- lib/services/app_settings_service.dart | 4 ++ .../message_url_image_helper_test.dart | 26 +++++++++- test/models/model_changes_test.dart | 7 +++ untranslated.json | 51 +++++++++++++++++++ 31 files changed, 381 insertions(+), 33 deletions(-) diff --git a/lib/helpers/message_url_image_helper.dart b/lib/helpers/message_url_image_helper.dart index 2f3e0756..6e85351a 100644 --- a/lib/helpers/message_url_image_helper.dart +++ b/lib/helpers/message_url_image_helper.dart @@ -24,6 +24,10 @@ class MessageUrlImageHelper { @visibleForTesting static http.Client? httpClient; + /// Mirrors [AppSettings.loadLinkImages]. When false, nothing is fetched + /// for link images and every parse returns null. + static final ValueNotifier loadLinkImages = ValueNotifier(true); + static final RegExp _pyxPattern = RegExp( r'''https?://pyx\.li/\?i=([A-Za-z0-9_-]+)''', caseSensitive: false, @@ -63,6 +67,7 @@ class MessageUrlImageHelper { String text, { String publicGateway = AppSettings.defaultPublicIpfsGateway, }) async { + if (!loadLinkImages.value) return null; final trimmed = text.trim(); if (trimmed.isEmpty) return null; @@ -123,6 +128,7 @@ class MessageUrlImageHelper { String text, { String publicGateway = AppSettings.defaultPublicIpfsGateway, }) { + if (!loadLinkImages.value) return Future.value(); final cacheKey = '$messageId|$publicGateway'; final cached = _messageImageCache.remove(cacheKey); if (cached != null) { @@ -240,29 +246,37 @@ class _MessageUrlImageFutureBuilderState @override void initState() { super.initState(); - _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( + _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 _parse() { + return MessageUrlImageHelper.parseVerifiedForMessage( widget.messageId, widget.text, publicGateway: widget.publicGateway, ); } - @override - void didUpdateWidget(covariant MessageUrlImageFutureBuilder oldWidget) { - super.didUpdateWidget(oldWidget); - if (oldWidget.messageId != widget.messageId) { - _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( - widget.messageId, - widget.text, - publicGateway: widget.publicGateway, - ); - } else if (oldWidget.publicGateway != widget.publicGateway) { - _imageFuture = MessageUrlImageHelper.parseVerifiedForMessage( - widget.messageId, - widget.text, - publicGateway: widget.publicGateway, - ); - } + void _onLoadLinkImagesChanged() { + setState(() => _imageFuture = _parse()); } @override diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 1849de8e..edf1fd10 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -69,6 +69,7 @@ }, "urlImage_enable": "Enable URL images", "urlImage_possible": "Possible URL image; enable it in Settings.", + "urlImage_disabledInAppSettings": "Turned off in app settings", "common_reboot": "Reboot", "common_loading": "Loading...", "common_notAvailable": "—", @@ -455,6 +456,8 @@ "appSettings_maxMessageRetriesSubtitle": "Number of retry attempts before marking a message as failed", "appSettings_ipfsImageLinks": "IPFS provider configuration", "appSettings_ipfsImageLinksSubtitle": "Upload for url Images (or Files) via IPFS provider and default gateway to receive", + "appSettings_loadLinkImages": "Load images from links", + "appSettings_loadLinkImagesSubtitle": "Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.", "appSettings_publicIpfsGateway": "Public gateway", "appSettings_ipfsGatewayDeactivated": "Deactivated", "appSettings_ipfsGatewayIpfsIo": "ipfs.io", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 78a0b15e..a494e526 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -382,6 +382,12 @@ abstract class AppLocalizations { /// **'Possible URL image; enable it in Settings.'** String get urlImage_possible; + /// No description provided for @urlImage_disabledInAppSettings. + /// + /// In en, this message translates to: + /// **'Turned off in app settings'** + String get urlImage_disabledInAppSettings; + /// No description provided for @common_reboot. /// /// In en, this message translates to: @@ -1966,6 +1972,18 @@ abstract class AppLocalizations { /// **'Upload for url Images (or Files) via IPFS provider and default gateway to receive'** String get appSettings_ipfsImageLinksSubtitle; + /// No description provided for @appSettings_loadLinkImages. + /// + /// In en, this message translates to: + /// **'Load images from links'** + String get appSettings_loadLinkImages; + + /// No description provided for @appSettings_loadLinkImagesSubtitle. + /// + /// In en, this message translates to: + /// **'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'** + String get appSettings_loadLinkImagesSubtitle; + /// No description provided for @appSettings_publicIpfsGateway. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index b40cbd33..acfebbcb 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -150,6 +150,9 @@ class AppLocalizationsBg extends AppLocalizations { String get urlImage_possible => 'Възможно изображение от URL; активирайте го в Настройки.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Рестартирай'; @@ -1083,6 +1086,13 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 232197ba..44ab330e 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -150,6 +150,9 @@ class AppLocalizationsDe extends AppLocalizations { String get urlImage_possible => 'Mögliches URL-Bild; in den Einstellungen aktivieren.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Neustart'; @@ -1078,6 +1081,13 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 25256f93..104199aa 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -150,6 +150,9 @@ class AppLocalizationsEn extends AppLocalizations { @override String get urlImage_possible => 'Possible URL image; enable it in Settings.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Reboot'; @@ -1062,6 +1065,13 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index a5ed0764..7e8dfab0 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -150,6 +150,9 @@ class AppLocalizationsEs extends AppLocalizations { String get urlImage_possible => 'Posible imagen de URL; actívala en Configuración.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Reiniciar'; @@ -1075,6 +1078,13 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 4b9bfcde..a809a3c7 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -150,6 +150,9 @@ class AppLocalizationsFr extends AppLocalizations { String get urlImage_possible => 'Image URL possible ; activez-la dans les Paramètres.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Redémarrer'; @@ -1081,6 +1084,13 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 79c968e1..af28f6a5 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -150,6 +150,9 @@ class AppLocalizationsHu extends AppLocalizations { String get urlImage_possible => 'Lehetséges URL-kép; engedélyezze a Beállításokban.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Indítsa újra'; @@ -1070,6 +1073,13 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 4768156b..67e124de 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -150,6 +150,9 @@ class AppLocalizationsIt extends AppLocalizations { String get urlImage_possible => 'Possibile immagine URL; abilitala nelle Impostazioni.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Riavvia'; @@ -1081,6 +1084,13 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 9057572a..d04f31c8 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -147,6 +147,9 @@ class AppLocalizationsJa extends AppLocalizations { @override String get urlImage_possible => 'URL画像の可能性があります。設定で有効にしてください。'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => '再起動'; @@ -1018,6 +1021,13 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 75e8cc06..9e893675 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -147,6 +147,9 @@ class AppLocalizationsKo extends AppLocalizations { @override String get urlImage_possible => 'URL 이미지일 수 있습니다. 설정에서 활성화하세요.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => '재부팅'; @@ -1022,6 +1025,13 @@ class AppLocalizationsKo extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 4b99bcfd..824a142c 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -151,6 +151,9 @@ class AppLocalizationsNl extends AppLocalizations { String get urlImage_possible => 'Mogelijke URL-afbeelding; schakel dit in bij Instellingen.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Herstarten'; @@ -1071,6 +1074,13 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 500eadcb..b88b5ee6 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -152,6 +152,9 @@ class AppLocalizationsPl extends AppLocalizations { String get urlImage_possible => 'Możliwy obraz z URL; włącz go w Ustawieniach.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Uruchom ponownie'; @@ -1087,6 +1090,13 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index af1d3ca4..4392cc30 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -150,6 +150,9 @@ class AppLocalizationsPt extends AppLocalizations { String get urlImage_possible => 'Possível imagem de URL; ative-a em Configurações.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Reiniciar'; @@ -1079,6 +1082,13 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 13d4ac7f..e35d7dce 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -150,6 +150,9 @@ class AppLocalizationsRu extends AppLocalizations { String get urlImage_possible => 'Возможно изображение по URL; включите это в настройках.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Перезагрузить'; @@ -1084,6 +1087,13 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 7e429e7d..34592fcd 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -151,6 +151,9 @@ class AppLocalizationsSk extends AppLocalizations { String get urlImage_possible => 'Možný obrázok z URL; povoľte ho v Nastaveniach.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Restartovať'; @@ -1070,6 +1073,13 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index d04579ac..c04c23ea 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -152,6 +152,9 @@ class AppLocalizationsSl extends AppLocalizations { String get urlImage_possible => 'Mogoča slika iz URL; omogočite jo v Nastavitvah.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Ponoviti'; @@ -1072,6 +1075,13 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index b0e614da..e47b7b4e 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -150,6 +150,9 @@ class AppLocalizationsSv extends AppLocalizations { String get urlImage_possible => 'Möjlig URL-bild; aktivera den i Inställningar.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Starta om'; @@ -1061,6 +1064,13 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 83d6424a..6407a997 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -150,6 +150,9 @@ class AppLocalizationsUk extends AppLocalizations { String get urlImage_possible => 'Можливе зображення за URL; увімкніть це в Налаштуваннях.'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => 'Перезавантажити'; @@ -1074,6 +1077,13 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 714864c6..40a0c6c6 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -146,6 +146,9 @@ class AppLocalizationsZh extends AppLocalizations { @override String get urlImage_possible => '可能是URL图片,请在设置中启用。'; + @override + String get urlImage_disabledInAppSettings => 'Turned off in app settings'; + @override String get common_reboot => '重启'; @@ -1002,6 +1005,13 @@ class AppLocalizationsZh extends AppLocalizations { String get appSettings_ipfsImageLinksSubtitle => 'Upload for url Images (or Files) via IPFS provider and default gateway to receive'; + @override + String get appSettings_loadLinkImages => 'Load images from links'; + + @override + String get appSettings_loadLinkImagesSubtitle => + 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/main.dart b/lib/main.dart index eecb4132..db10b0fb 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -12,6 +12,7 @@ import 'screens/chrome_required_screen.dart'; import 'utils/platform_info.dart'; import 'connector/meshcore_connector.dart'; +import 'helpers/message_url_image_helper.dart'; import 'models/image_codec_support.dart'; import 'screens/scanner_screen.dart'; import 'services/image_chunk_transport.dart'; @@ -139,10 +140,14 @@ void main() async { notificationService.setPublicIpfsGateway( appSettingsService.settings.publicIpfsGateway, ); + MessageUrlImageHelper.loadLinkImages.value = + appSettingsService.settings.loadLinkImages; appSettingsService.addListener(() { notificationService.setPublicIpfsGateway( appSettingsService.settings.publicIpfsGateway, ); + MessageUrlImageHelper.loadLinkImages.value = + appSettingsService.settings.loadLinkImages; }); await notificationService.initialize(); await backgroundService.initialize(); diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 64ccbfad..337e8fbd 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -147,6 +147,9 @@ class AppSettings { final int tcpServerPort; final bool jumpToOldestUnread; final bool imageMessagesEnabled; + + /// Master switch for fetching images behind links in messages. + final bool loadLinkImages; final String publicIpfsGateway; final String uploadIpfsGateway; final String uploadIpfsEndpoint; @@ -271,6 +274,7 @@ class AppSettings { this.jumpToOldestUnread = false, this.networkMapUploadEnabled = false, this.networkMapPromptShown = false, + this.loadLinkImages = true, this.publicIpfsGateway = defaultPublicIpfsGateway, this.uploadIpfsGateway = '', this.uploadIpfsEndpoint = '', @@ -366,6 +370,7 @@ class AppSettings { 'jump_to_oldest_unread': jumpToOldestUnread, 'network_map_upload_enabled': networkMapUploadEnabled, 'network_map_prompt_shown': networkMapPromptShown, + 'load_link_images': loadLinkImages, 'public_ipfs_gateway': publicIpfsGateway, 'upload_ipfs_gateway': uploadIpfsGateway, 'upload_ipfs_endpoint': uploadIpfsEndpoint, @@ -505,6 +510,7 @@ class AppSettings { networkMapUploadEnabled: json['network_map_upload_enabled'] as bool? ?? false, networkMapPromptShown: json['network_map_prompt_shown'] as bool? ?? false, + loadLinkImages: json['load_link_images'] as bool? ?? true, publicIpfsGateway: json['public_ipfs_gateway'] as String? ?? defaultPublicIpfsGateway, uploadIpfsGateway: json['upload_ipfs_gateway'] as String? ?? '', @@ -632,6 +638,7 @@ class AppSettings { bool? jumpToOldestUnread, bool? networkMapUploadEnabled, bool? networkMapPromptShown, + bool? loadLinkImages, String? publicIpfsGateway, String? uploadIpfsGateway, String? uploadIpfsEndpoint, @@ -726,6 +733,7 @@ class AppSettings { networkMapUploadEnabled ?? this.networkMapUploadEnabled, networkMapPromptShown: networkMapPromptShown ?? this.networkMapPromptShown, + loadLinkImages: loadLinkImages ?? this.loadLinkImages, publicIpfsGateway: publicIpfsGateway ?? this.publicIpfsGateway, uploadIpfsGateway: uploadIpfsGateway ?? this.uploadIpfsGateway, uploadIpfsEndpoint: uploadIpfsEndpoint ?? this.uploadIpfsEndpoint, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 5feadfcc..407c8f3f 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -685,6 +685,18 @@ class AppSettingsScreen extends StatelessWidget { ) { return Column( children: [ + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.image_search_outlined, size: 24), + title: Text(context.l10n.appSettings_loadLinkImages), + subtitle: Text(context.l10n.appSettings_loadLinkImagesSubtitle), + value: settingsService.settings.loadLinkImages, + onChanged: settingsService.setLoadLinkImages, + ), + const Divider(height: 1, indent: 16), ListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index f0cbcc19..06805668 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -815,9 +815,10 @@ class _ChannelChatScreenState extends State { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (MessageUrlImageHelper.hasPotentialImageUrl( - message.text, - )) + if (settingsService.settings.loadLinkImages && + MessageUrlImageHelper.hasPotentialImageUrl( + message.text, + )) Padding( padding: const EdgeInsets.only(bottom: 4), child: Text( diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 53d561ac..f743efc6 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -1650,6 +1650,7 @@ class _ChannelsScreenState extends State bool smazEnabled = connector.isChannelSmazEnabled(channel.index); bool cyr2latEnabled = connector.isChannelCyr2LatEnabled(channel.index); bool urlImagesEnabled = connector.isChannelUrlImagesEnabled(channel.index); + final loadLinkImages = appSettingsService.settings.loadLinkImages; String? selectedCyr2LatProfileId = connector.getChannelCyr2LatProfileId( channel.index, ); @@ -1769,9 +1770,19 @@ class _ChannelsScreenState extends State SwitchListTile( contentPadding: EdgeInsets.zero, title: Text(sheetContext.l10n.urlImage_enable), + subtitle: loadLinkImages + ? null + : Text( + sheetContext + .l10n + .urlImage_disabledInAppSettings, + ), value: urlImagesEnabled, - onChanged: (value) => - setSheetState(() => urlImagesEnabled = value), + onChanged: loadLinkImages + ? (value) => setSheetState( + () => urlImagesEnabled = value, + ) + : null, ), const SizedBox(height: 24), ], diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 81ea6577..43d30804 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -782,6 +782,10 @@ class _ChatScreenState extends State { bool urlImagesEnabled = connector.isContactUrlImagesEnabled( contact.publicKeyHex, ); + final loadLinkImages = context + .read() + .settings + .loadLinkImages; String? selectedCyr2LatProfileId = connector.getContactCyr2LatProfileId( contact.publicKeyHex, ); @@ -896,14 +900,19 @@ class _ChatScreenState extends State { SwitchListTile( contentPadding: EdgeInsets.zero, title: Text(context.l10n.urlImage_enable), + subtitle: loadLinkImages + ? null + : Text(context.l10n.urlImage_disabledInAppSettings), value: urlImagesEnabled, - onChanged: (value) { - connector.setContactUrlImagesEnabled( - contact.publicKeyHex, - value, - ); - setDialogState(() => urlImagesEnabled = value); - }, + onChanged: loadLinkImages + ? (value) { + connector.setContactUrlImagesEnabled( + contact.publicKeyHex, + value, + ); + setDialogState(() => urlImagesEnabled = value); + } + : null, ), const Divider(height: 8), SwitchListTile( @@ -1432,9 +1441,10 @@ class _MessageBubble extends StatelessWidget { Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (MessageUrlImageHelper.hasPotentialImageUrl( - message.text, - )) + if (settingsService.settings.loadLinkImages && + MessageUrlImageHelper.hasPotentialImageUrl( + message.text, + )) Padding( padding: const EdgeInsets.only(bottom: 4), child: Text( diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 7bd5ba65..7bd1fbf2 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -328,6 +328,10 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(networkMapPromptShown: value)); } + Future setLoadLinkImages(bool value) async { + await updateSettings(_settings.copyWith(loadLinkImages: value)); + } + Future setIpfsImageSettings({ required String publicGateway, required String uploadGateway, diff --git a/test/helpers/message_url_image_helper_test.dart b/test/helpers/message_url_image_helper_test.dart index 900b0a01..a8a21a2e 100644 --- a/test/helpers/message_url_image_helper_test.dart +++ b/test/helpers/message_url_image_helper_test.dart @@ -5,7 +5,10 @@ import 'package:meshcore_open/helpers/message_url_image_helper.dart'; void main() { group('MessageUrlImageHelper', () { - tearDown(() => MessageUrlImageHelper.httpClient = null); + tearDown(() { + MessageUrlImageHelper.httpClient = null; + MessageUrlImageHelper.loadLinkImages.value = true; + }); void mockPyxPage(String id) { MessageUrlImageHelper.httpClient = MockClient((request) async { @@ -120,5 +123,26 @@ void main() { expect(attachment, isNull); }); + + test('fetches nothing when loading link images is off', () async { + MessageUrlImageHelper.loadLinkImages.value = false; + MessageUrlImageHelper.httpClient = MockClient((request) async { + fail('Unexpected request to ${request.url}'); + }); + + for (final text in [ + 'https://pyx.li/?i=RzmdkTsE', + 'https://ibb.co/abc123', + 'ipfs://bafybeigdyrzt5sfp7udm7hu76uh7y26nf3efuylqabf3oclgtqy55fbzdi', + 'https://example.com/photo.png', + ]) { + expect(await MessageUrlImageHelper.parse(text), isNull); + expect(await MessageUrlImageHelper.parseVerified(text), isNull); + expect( + await MessageUrlImageHelper.parseVerifiedForMessage('m1', text), + isNull, + ); + } + }); }); } diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index 94a7eb2a..9c46be93 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -443,6 +443,13 @@ void main() { expect(settings.evictDiscoveredContactsEnabled, isFalse); }); + test('load link images defaults on and round-trips through JSON', () { + expect(AppSettings().loadLinkImages, isTrue); + expect(AppSettings.fromJson({}).loadLinkImages, isTrue); + final saved = AppSettings(loadLinkImages: false).toJson(); + expect(AppSettings.fromJson(saved).loadLinkImages, isFalse); + }); + test('public IPFS gateway defaults to ipfs.io when never set', () { expect( AppSettings.fromJson({}).publicIpfsGateway, diff --git a/untranslated.json b/untranslated.json index 73747889..07b30a44 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1,8 +1,11 @@ { "bg": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -51,9 +54,12 @@ ], "de": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -102,9 +108,12 @@ ], "es": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -153,9 +162,12 @@ ], "fr": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -204,9 +216,12 @@ ], "hu": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -255,9 +270,12 @@ ], "it": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -306,9 +324,12 @@ ], "ja": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -357,9 +378,12 @@ ], "ko": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -408,9 +432,12 @@ ], "nl": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -459,9 +486,12 @@ ], "pl": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -510,9 +540,12 @@ ], "pt": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -561,9 +594,12 @@ ], "ru": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -612,9 +648,12 @@ ], "sk": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -663,9 +702,12 @@ ], "sl": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -714,9 +756,12 @@ ], "sv": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -765,9 +810,12 @@ ], "uk": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -816,9 +864,12 @@ ], "zh": [ + "urlImage_disabledInAppSettings", "settings_pathHashModeNotApplied", "appSettings_ipfsImageLinks", "appSettings_ipfsImageLinksSubtitle", + "appSettings_loadLinkImages", + "appSettings_loadLinkImagesSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", From a4670a9275a8a846d363928e53b09997b1b74e8b Mon Sep 17 00:00:00 2001 From: zjs81 Date: Sat, 24 Oct 2026 22:01:11 -0700 Subject: [PATCH 15/15] Add a setting to show link images in all chats by default 'Show link images in all chats by default' (default off) applies to every channel and contact without an explicit per-chat choice: the per-chat setting is now unset/on/off and resolves to perChat ?? default. The 'Load images from links' master switch still overrides it. --- lib/connector/meshcore_connector.dart | 25 ++++++-- lib/l10n/app_en.arb | 2 + lib/l10n/app_localizations.dart | 12 ++++ lib/l10n/app_localizations_bg.dart | 8 +++ lib/l10n/app_localizations_de.dart | 8 +++ lib/l10n/app_localizations_en.dart | 8 +++ lib/l10n/app_localizations_es.dart | 8 +++ lib/l10n/app_localizations_fr.dart | 8 +++ lib/l10n/app_localizations_hu.dart | 8 +++ lib/l10n/app_localizations_it.dart | 8 +++ lib/l10n/app_localizations_ja.dart | 8 +++ lib/l10n/app_localizations_ko.dart | 8 +++ lib/l10n/app_localizations_nl.dart | 8 +++ lib/l10n/app_localizations_pl.dart | 8 +++ lib/l10n/app_localizations_pt.dart | 8 +++ lib/l10n/app_localizations_ru.dart | 8 +++ lib/l10n/app_localizations_sk.dart | 8 +++ lib/l10n/app_localizations_sl.dart | 8 +++ lib/l10n/app_localizations_sv.dart | 8 +++ lib/l10n/app_localizations_uk.dart | 8 +++ lib/l10n/app_localizations_zh.dart | 8 +++ lib/models/app_settings.dart | 10 +++ lib/screens/app_settings_screen.dart | 16 +++++ lib/screens/channels_screen.dart | 16 +++-- lib/services/app_settings_service.dart | 4 ++ lib/storage/channel_settings_store.dart | 6 +- lib/storage/contact_settings_store.dart | 6 +- test/connector/link_images_default_test.dart | 64 ++++++++++++++++++++ test/models/model_changes_test.dart | 7 +++ untranslated.json | 34 +++++++++++ 30 files changed, 330 insertions(+), 16 deletions(-) create mode 100644 test/connector/link_images_default_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index a706e715..b1eaeda7 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -491,7 +491,7 @@ class MeshCoreConnector extends ChangeNotifier { List _cachedChannels = []; final Map _channelSmazEnabled = {}; final Map _channelCyr2LatEnabled = {}; - final Map _channelUrlImagesEnabled = {}; + final Map _channelUrlImagesEnabled = {}; final Map _channelCyr2LatProfileId = {}; final Map _channelRegions = {}; Region _defaultRegion = ''; @@ -501,7 +501,7 @@ class MeshCoreConnector extends ChangeNotifier { Uint8List? _defaultFloodScopeKey; final Map _contactSmazEnabled = {}; final Map _contactCyr2LatEnabled = {}; - final Map _contactUrlImagesEnabled = {}; + final Map _contactUrlImagesEnabled = {}; final Map _contactCyr2LatProfileId = {}; final Set _knownContactKeys = {}; final Map _contactUnreadCount = {}; @@ -1059,13 +1059,25 @@ class MeshCoreConnector extends ChangeNotifier { return _contactSmazEnabled[contactKeyHex] ?? false; } + bool _lastShowLinkImagesByDefault = false; + + void _onAppSettingsChanged() { + final showByDefault = _showLinkImagesByDefault; + if (showByDefault == _lastShowLinkImagesByDefault) return; + _lastShowLinkImagesByDefault = showByDefault; + notifyListeners(); + } + + bool get _showLinkImagesByDefault => + _appSettingsService?.settings.showLinkImagesByDefault ?? false; + bool isChannelUrlImagesEnabled(int channelIndex) { - return _channelUrlImagesEnabled[channelIndex] ?? false; + return _channelUrlImagesEnabled[channelIndex] ?? _showLinkImagesByDefault; } bool isContactUrlImagesEnabled(String contactKeyHex) { _ensureContactUrlImagesSettingLoaded(contactKeyHex); - return _contactUrlImagesEnabled[contactKeyHex] ?? false; + return _contactUrlImagesEnabled[contactKeyHex] ?? _showLinkImagesByDefault; } /// True when the channel has its own (real) region assigned. @@ -1621,6 +1633,8 @@ class MeshCoreConnector extends ChangeNotifier { _retryService = retryService; _pathHistoryService = pathHistoryService; _appSettingsService = appSettingsService; + _lastShowLinkImagesByDefault = _showLinkImagesByDefault; + appSettingsService?.addListener(_onAppSettingsChanged); _translationService = translationService; _imageCodecService = imageCodecService; _imageTransport = imageTransport; @@ -7320,7 +7334,7 @@ class MeshCoreConnector extends ChangeNotifier { void _ensureContactUrlImagesSettingLoaded(String contactKeyHex) { if (_contactUrlImagesEnabled.containsKey(contactKeyHex)) return; _contactSettingsStore.loadUrlImagesEnabled(contactKeyHex).then((enabled) { - if (_contactUrlImagesEnabled[contactKeyHex] == enabled) return; + if (_contactUrlImagesEnabled.containsKey(contactKeyHex)) return; _contactUrlImagesEnabled[contactKeyHex] = enabled; notifyListeners(); }); @@ -8874,6 +8888,7 @@ class MeshCoreConnector extends ChangeNotifier { @override void dispose() { _disposed = true; + _appSettingsService?.removeListener(_onAppSettingsChanged); _scanSubscription?.cancel(); _isScanningSubscription?.cancel(); _connectionSubscription?.cancel(); diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index edf1fd10..9f8a6b78 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -458,6 +458,8 @@ "appSettings_ipfsImageLinksSubtitle": "Upload for url Images (or Files) via IPFS provider and default gateway to receive", "appSettings_loadLinkImages": "Load images from links", "appSettings_loadLinkImagesSubtitle": "Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.", + "appSettings_showLinkImagesByDefault": "Show link images in all chats by default", + "appSettings_showLinkImagesByDefaultSubtitle": "Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.", "appSettings_publicIpfsGateway": "Public gateway", "appSettings_ipfsGatewayDeactivated": "Deactivated", "appSettings_ipfsGatewayIpfsIo": "ipfs.io", diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index a494e526..64853f11 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -1984,6 +1984,18 @@ abstract class AppLocalizations { /// **'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'** String get appSettings_loadLinkImagesSubtitle; + /// No description provided for @appSettings_showLinkImagesByDefault. + /// + /// In en, this message translates to: + /// **'Show link images in all chats by default'** + String get appSettings_showLinkImagesByDefault; + + /// No description provided for @appSettings_showLinkImagesByDefaultSubtitle. + /// + /// In en, this message translates to: + /// **'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'** + String get appSettings_showLinkImagesByDefaultSubtitle; + /// No description provided for @appSettings_publicIpfsGateway. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index acfebbcb..7aee19b5 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1093,6 +1093,14 @@ class AppLocalizationsBg extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 44ab330e..5486f6d3 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1088,6 +1088,14 @@ class AppLocalizationsDe extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 104199aa..77fbf68f 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1072,6 +1072,14 @@ class AppLocalizationsEn extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 7e8dfab0..2570b832 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1085,6 +1085,14 @@ class AppLocalizationsEs extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index a809a3c7..c5836961 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1091,6 +1091,14 @@ class AppLocalizationsFr extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index af28f6a5..a13f5fdb 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1080,6 +1080,14 @@ class AppLocalizationsHu extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 67e124de..af088381 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1091,6 +1091,14 @@ class AppLocalizationsIt extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index d04f31c8..fa585b1e 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1028,6 +1028,14 @@ class AppLocalizationsJa extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 9e893675..e6286bdc 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1032,6 +1032,14 @@ class AppLocalizationsKo extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 824a142c..9c6301cb 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1081,6 +1081,14 @@ class AppLocalizationsNl extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index b88b5ee6..88abdc15 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1097,6 +1097,14 @@ class AppLocalizationsPl extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 4392cc30..b19c71ae 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1089,6 +1089,14 @@ class AppLocalizationsPt extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index e35d7dce..166e17a6 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1094,6 +1094,14 @@ class AppLocalizationsRu extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 34592fcd..cbe7c713 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1080,6 +1080,14 @@ class AppLocalizationsSk extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index c04c23ea..8744afcb 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1082,6 +1082,14 @@ class AppLocalizationsSl extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index e47b7b4e..321b1cfe 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1071,6 +1071,14 @@ class AppLocalizationsSv extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 6407a997..97352355 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1084,6 +1084,14 @@ class AppLocalizationsUk extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 40a0c6c6..eafad225 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1012,6 +1012,14 @@ class AppLocalizationsZh extends AppLocalizations { String get appSettings_loadLinkImagesSubtitle => 'Show pictures from links in messages. Loading an image shares your IP address with the site that hosts it.'; + @override + String get appSettings_showLinkImagesByDefault => + 'Show link images in all chats by default'; + + @override + String get appSettings_showLinkImagesByDefaultSubtitle => + 'Load link images in every chat unless you turned them off there. This shares your IP address with image hosts in every chat.'; + @override String get appSettings_publicIpfsGateway => 'Public gateway'; diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 337e8fbd..facc4fb5 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -150,6 +150,9 @@ class AppSettings { /// Master switch for fetching images behind links in messages. final bool loadLinkImages; + + /// Chats with no saved link-image choice load link images when true. + final bool showLinkImagesByDefault; final String publicIpfsGateway; final String uploadIpfsGateway; final String uploadIpfsEndpoint; @@ -275,6 +278,7 @@ class AppSettings { this.networkMapUploadEnabled = false, this.networkMapPromptShown = false, this.loadLinkImages = true, + this.showLinkImagesByDefault = false, this.publicIpfsGateway = defaultPublicIpfsGateway, this.uploadIpfsGateway = '', this.uploadIpfsEndpoint = '', @@ -371,6 +375,7 @@ class AppSettings { 'network_map_upload_enabled': networkMapUploadEnabled, 'network_map_prompt_shown': networkMapPromptShown, 'load_link_images': loadLinkImages, + 'show_link_images_by_default': showLinkImagesByDefault, 'public_ipfs_gateway': publicIpfsGateway, 'upload_ipfs_gateway': uploadIpfsGateway, 'upload_ipfs_endpoint': uploadIpfsEndpoint, @@ -511,6 +516,8 @@ class AppSettings { json['network_map_upload_enabled'] as bool? ?? false, networkMapPromptShown: json['network_map_prompt_shown'] as bool? ?? false, loadLinkImages: json['load_link_images'] as bool? ?? true, + showLinkImagesByDefault: + json['show_link_images_by_default'] as bool? ?? false, publicIpfsGateway: json['public_ipfs_gateway'] as String? ?? defaultPublicIpfsGateway, uploadIpfsGateway: json['upload_ipfs_gateway'] as String? ?? '', @@ -639,6 +646,7 @@ class AppSettings { bool? networkMapUploadEnabled, bool? networkMapPromptShown, bool? loadLinkImages, + bool? showLinkImagesByDefault, String? publicIpfsGateway, String? uploadIpfsGateway, String? uploadIpfsEndpoint, @@ -734,6 +742,8 @@ class AppSettings { networkMapPromptShown: networkMapPromptShown ?? this.networkMapPromptShown, loadLinkImages: loadLinkImages ?? this.loadLinkImages, + showLinkImagesByDefault: + showLinkImagesByDefault ?? this.showLinkImagesByDefault, publicIpfsGateway: publicIpfsGateway ?? this.publicIpfsGateway, uploadIpfsGateway: uploadIpfsGateway ?? this.uploadIpfsGateway, uploadIpfsEndpoint: uploadIpfsEndpoint ?? this.uploadIpfsEndpoint, diff --git a/lib/screens/app_settings_screen.dart b/lib/screens/app_settings_screen.dart index 407c8f3f..75b556d4 100644 --- a/lib/screens/app_settings_screen.dart +++ b/lib/screens/app_settings_screen.dart @@ -697,6 +697,22 @@ class AppSettingsScreen extends StatelessWidget { onChanged: settingsService.setLoadLinkImages, ), const Divider(height: 1, indent: 16), + SwitchListTile( + contentPadding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 4, + ), + secondary: const Icon(Icons.collections_outlined, size: 24), + title: Text(context.l10n.appSettings_showLinkImagesByDefault), + subtitle: Text( + context.l10n.appSettings_showLinkImagesByDefaultSubtitle, + ), + value: settingsService.settings.showLinkImagesByDefault, + onChanged: settingsService.settings.loadLinkImages + ? settingsService.setShowLinkImagesByDefault + : null, + ), + const Divider(height: 1, indent: 16), ListTile( contentPadding: const EdgeInsets.symmetric( horizontal: 16, diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index f743efc6..d4dab875 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -1649,7 +1649,10 @@ class _ChannelsScreenState extends State ); bool smazEnabled = connector.isChannelSmazEnabled(channel.index); bool cyr2latEnabled = connector.isChannelCyr2LatEnabled(channel.index); - bool urlImagesEnabled = connector.isChannelUrlImagesEnabled(channel.index); + final initialUrlImagesEnabled = connector.isChannelUrlImagesEnabled( + channel.index, + ); + bool urlImagesEnabled = initialUrlImagesEnabled; final loadLinkImages = appSettingsService.settings.loadLinkImages; String? selectedCyr2LatProfileId = connector.getChannelCyr2LatProfileId( channel.index, @@ -1842,10 +1845,13 @@ class _ChannelsScreenState extends State channel.index, cyr2latEnabled, ); - await connector.setChannelUrlImagesEnabled( - channel.index, - urlImagesEnabled, - ); + if (urlImagesEnabled != + initialUrlImagesEnabled) { + await connector.setChannelUrlImagesEnabled( + channel.index, + urlImagesEnabled, + ); + } await connector.setChannelCyr2LatProfileId( channel.index, selectedCyr2LatProfileId, diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 7bd1fbf2..2e9061d6 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -332,6 +332,10 @@ class AppSettingsService extends ChangeNotifier { await updateSettings(_settings.copyWith(loadLinkImages: value)); } + Future setShowLinkImagesByDefault(bool value) async { + await updateSettings(_settings.copyWith(showLinkImagesByDefault: value)); + } + Future setIpfsImageSettings({ required String publicGateway, required String uploadGateway, diff --git a/lib/storage/channel_settings_store.dart b/lib/storage/channel_settings_store.dart index c02e142e..be4986e7 100644 --- a/lib/storage/channel_settings_store.dart +++ b/lib/storage/channel_settings_store.dart @@ -60,14 +60,14 @@ class ChannelSettingsStore { await PrefsManager.instance.setBool(_cyr2LatKey(channelId), enabled); } - Future loadUrlImagesEnabled(String channelId) async { + Future loadUrlImagesEnabled(String channelId) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot load channel URL image settings.', ); - return false; + return null; } - return PrefsManager.instance.getBool(_urlImagesKey(channelId)) ?? false; + return PrefsManager.instance.getBool(_urlImagesKey(channelId)); } Future saveUrlImagesEnabled(String channelId, bool enabled) async { diff --git a/lib/storage/contact_settings_store.dart b/lib/storage/contact_settings_store.dart index 10ffaaee..49b1faa2 100644 --- a/lib/storage/contact_settings_store.dart +++ b/lib/storage/contact_settings_store.dart @@ -76,16 +76,16 @@ class ContactSettingsStore { await prefs.setBool(key, enabled); } - Future loadUrlImagesEnabled(String contactKeyHex) async { + Future loadUrlImagesEnabled(String contactKeyHex) async { if (publicKeyHex.isEmpty) { appLogger.warn( 'Public key hex is not set. Cannot load contact URL image settings.', ); - return false; + return null; } final prefs = PrefsManager.instance; final key = '$keyForUrlImages$contactKeyHex'; - return prefs.getBool(key) ?? false; + return prefs.getBool(key); } Future saveUrlImagesEnabled(String contactKeyHex, bool enabled) async { diff --git a/test/connector/link_images_default_test.dart b/test/connector/link_images_default_test.dart new file mode 100644 index 00000000..3ec74ece --- /dev/null +++ b/test/connector/link_images_default_test.dart @@ -0,0 +1,64 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/channel_settings_store.dart'; +import 'package:meshcore_open/storage/contact_settings_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test('stores return null for chats that were never set', () async { + final channels = ChannelSettingsStore()..setPublicKeyHex = 'aabbccddeeff'; + final contacts = ContactSettingsStore()..setPublicKeyHex = 'aabbccddeeff'; + expect(await channels.loadUrlImagesEnabled('chan'), isNull); + expect(await contacts.loadUrlImagesEnabled('c1'), isNull); + + await channels.saveUrlImagesEnabled('chan', false); + await contacts.saveUrlImagesEnabled('c1', false); + expect(await channels.loadUrlImagesEnabled('chan'), isFalse); + expect(await contacts.loadUrlImagesEnabled('c1'), isFalse); + }); + + test('effective value is the per-chat choice, else the default', () async { + final settings = AppSettingsService(); + final connector = MeshCoreConnector(); + addTearDown(connector.dispose); + final retryService = MessageRetryService(); + addTearDown(retryService.dispose); + connector.initialize( + retryService: retryService, + pathHistoryService: PathHistoryService(StorageService()), + appSettingsService: settings, + ); + var notified = 0; + connector.addListener(() => notified++); + + expect(connector.isContactUrlImagesEnabled('c1'), isFalse); + expect(connector.isChannelUrlImagesEnabled(0), isFalse); + + await settings.setShowLinkImagesByDefault(true); + await Future.delayed(const Duration(milliseconds: 100)); + expect(notified, greaterThan(0)); + expect(connector.isContactUrlImagesEnabled('c1'), isTrue); + expect(connector.isChannelUrlImagesEnabled(0), isTrue); + + await connector.setContactUrlImagesEnabled('c2', false); + expect(connector.isContactUrlImagesEnabled('c2'), isFalse); + + await settings.setShowLinkImagesByDefault(false); + await connector.setContactUrlImagesEnabled('c3', true); + expect(connector.isContactUrlImagesEnabled('c1'), isFalse); + expect(connector.isContactUrlImagesEnabled('c3'), isTrue); + }); +} diff --git a/test/models/model_changes_test.dart b/test/models/model_changes_test.dart index 9c46be93..874a5d8b 100644 --- a/test/models/model_changes_test.dart +++ b/test/models/model_changes_test.dart @@ -450,6 +450,13 @@ void main() { expect(AppSettings.fromJson(saved).loadLinkImages, isFalse); }); + test('show link images by default is off and round-trips', () { + expect(AppSettings().showLinkImagesByDefault, isFalse); + expect(AppSettings.fromJson({}).showLinkImagesByDefault, isFalse); + final saved = AppSettings(showLinkImagesByDefault: true).toJson(); + expect(AppSettings.fromJson(saved).showLinkImagesByDefault, isTrue); + }); + test('public IPFS gateway defaults to ipfs.io when never set', () { expect( AppSettings.fromJson({}).publicIpfsGateway, diff --git a/untranslated.json b/untranslated.json index 07b30a44..2dac94ff 100644 --- a/untranslated.json +++ b/untranslated.json @@ -6,6 +6,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -60,6 +62,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -114,6 +118,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -168,6 +174,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -222,6 +230,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -276,6 +286,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -330,6 +342,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -384,6 +398,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -438,6 +454,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -492,6 +510,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -546,6 +566,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -600,6 +622,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -654,6 +678,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -708,6 +734,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -762,6 +790,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -816,6 +846,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo", @@ -870,6 +902,8 @@ "appSettings_ipfsImageLinksSubtitle", "appSettings_loadLinkImages", "appSettings_loadLinkImagesSubtitle", + "appSettings_showLinkImagesByDefault", + "appSettings_showLinkImagesByDefaultSubtitle", "appSettings_publicIpfsGateway", "appSettings_ipfsGatewayDeactivated", "appSettings_ipfsGatewayIpfsIo",