upload url image or file to ipfs

This commit is contained in:
ericz committed 2026-10-11 13:14:14 +02:00
1 parent 9609a8231d
commit a4a7e00732
33 files changed
+2594 -81

No files matched your search

+327 -1
View File
@@ -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<String>(
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<String>(
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<void> _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 {
+128 -1
View File
@@ -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<ChannelChatScreen> {
bool urlImagesEnabled,
) {
final settingsService = context.watch<AppSettingsService>();
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<ChannelChatScreen> {
MessageUrlImageFutureBuilder(
messageId: message.messageId,
text: message.text,
publicGateway: publicIpfsGateway,
builder: (context, snapshot) {
final imageAttachment = snapshot.data;
@@ -1360,6 +1363,113 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
);
}
Future<void> _sendImageViaIpfs() async {
final l10n = context.l10n;
final settings = context.read<AppSettingsService>().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<MeshCoreConnector>();
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<void> _showImageSendPreview() async {
@@ -2110,6 +2220,20 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
),
);
}
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<MeshCoreConnector>();
if (hasShareableLocation(
@@ -2159,6 +2283,9 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
case 'meshcore-image':
_showImageSendPreview();
break;
case 'ipfs-image':
_sendImageViaIpfs();
break;
case 'send-my-location':
await _shareMyLocation(
context.read<MeshCoreConnector>(),
+155 -23
View File
@@ -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<ChatScreen> {
Offset.zero,
ancestor: overlay,
);
const menuHeight = 2 * kMinInteractiveDimension + 16;
final items = <PopupMenuEntry<String>>[
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<ChatScreen> {
final selected = await showMenu<String>(
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<ChatScreen> {
case 'gif':
_showGifPicker(context);
break;
case 'ipfs-image':
_sendImageViaIpfs();
break;
case 'send-my-location':
await _shareMyLocation(
context.read<MeshCoreConnector>(),
@@ -572,6 +595,7 @@ class _ChatScreenState extends State<ChatScreen> {
// 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<TextEditingValue>(
valueListenable: _textController,
@@ -722,6 +746,112 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
Future<void> _sendImageViaIpfs() async {
final l10n = context.l10n;
final settings = context.read<AppSettingsService>().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<MeshCoreConnector>();
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<void> _showTranslationOptions() async {
final settingsService = context.read<AppSettingsService>();
final settings = settingsService.settings;
@@ -1502,6 +1632,7 @@ class _MessageBubble extends StatelessWidget {
final urlImagesEnabled = context.select<MeshCoreConnector, bool>(
(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;