upload url image or file to ipfs
This commit is contained in:
1 parent
9609a8231d
commit
a4a7e00732
33 files changed
+2594
-81
No files matched your search
@@ -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<String> 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<String> 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 = <String, String>{'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<void> _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
|
||||
? <String, String>{}
|
||||
: {'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<String, dynamic>) continue;
|
||||
final value = isPinata ? decoded['IpfsHash'] : decoded['Hash'];
|
||||
if (value is String && value.isNotEmpty) return value;
|
||||
} catch (_) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<String> 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<String?> parse(String text) async {
|
||||
static Future<String?> 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<String?> parseVerified(String text) async {
|
||||
final imageUrl = await parse(text);
|
||||
static Future<String?> 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<String?> 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<String?> 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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user