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, + ); + }); +}