upload image to nostr working
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../local/local_storage_service.dart';
|
||||
import '../local/models/item.dart';
|
||||
import 'models/immich_asset.dart';
|
||||
@@ -10,7 +11,7 @@ import 'models/upload_response.dart';
|
||||
class ImmichException implements Exception {
|
||||
/// Error message.
|
||||
final String message;
|
||||
|
||||
|
||||
/// HTTP status code if available.
|
||||
final int? statusCode;
|
||||
|
||||
@@ -27,12 +28,12 @@ class ImmichException implements Exception {
|
||||
}
|
||||
|
||||
/// Service for interacting with Immich API.
|
||||
///
|
||||
///
|
||||
/// This service provides:
|
||||
/// - Upload images to Immich
|
||||
/// - Fetch image lists from Immich
|
||||
/// - Store image metadata locally after uploads
|
||||
///
|
||||
///
|
||||
/// The service is modular and UI-independent, designed for offline-first behavior.
|
||||
class ImmichService {
|
||||
/// HTTP client for API requests.
|
||||
@@ -48,7 +49,7 @@ class ImmichService {
|
||||
final String _apiKey;
|
||||
|
||||
/// Creates an [ImmichService] instance.
|
||||
///
|
||||
///
|
||||
/// [baseUrl] - Immich server base URL (e.g., 'https://immich.example.com').
|
||||
/// [apiKey] - Immich API key for authentication.
|
||||
/// [localStorage] - Local storage service for caching metadata.
|
||||
@@ -64,16 +65,18 @@ class ImmichService {
|
||||
_dio = dio ?? Dio() {
|
||||
_dio.options.baseUrl = baseUrl;
|
||||
_dio.options.headers['x-api-key'] = apiKey;
|
||||
_dio.options.headers['Content-Type'] = 'application/json';
|
||||
// Don't set Content-Type globally - it should be set per request
|
||||
// For JSON requests, it will be set automatically
|
||||
// For multipart uploads, Dio will set it with the correct boundary
|
||||
}
|
||||
|
||||
/// Uploads an image file to Immich.
|
||||
///
|
||||
///
|
||||
/// [imageFile] - The image file to upload.
|
||||
/// [albumId] - Optional album ID to add the image to.
|
||||
///
|
||||
///
|
||||
/// Returns [UploadResponse] containing the uploaded asset ID.
|
||||
///
|
||||
///
|
||||
/// Throws [ImmichException] if upload fails.
|
||||
/// Automatically stores metadata in local storage upon successful upload.
|
||||
Future<UploadResponse> uploadImage(
|
||||
@@ -85,35 +88,183 @@ class ImmichService {
|
||||
throw ImmichException('Image file does not exist: ${imageFile.path}');
|
||||
}
|
||||
|
||||
// Get file metadata
|
||||
final fileName = imageFile.path.split('/').last;
|
||||
final fileStat = await imageFile.stat();
|
||||
final fileCreatedAt = fileStat.changed;
|
||||
final fileModifiedAt = fileStat.modified;
|
||||
|
||||
// Determine MIME type from file extension
|
||||
String mimeType = 'image/jpeg'; // default
|
||||
final extension = fileName.split('.').last.toLowerCase();
|
||||
switch (extension) {
|
||||
case 'png':
|
||||
mimeType = 'image/png';
|
||||
break;
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
mimeType = 'image/jpeg';
|
||||
break;
|
||||
case 'gif':
|
||||
mimeType = 'image/gif';
|
||||
break;
|
||||
case 'webp':
|
||||
mimeType = 'image/webp';
|
||||
break;
|
||||
case 'heic':
|
||||
case 'heif':
|
||||
mimeType = 'image/heic';
|
||||
break;
|
||||
}
|
||||
|
||||
// Generate device IDs (required by Immich API)
|
||||
// Using a consistent device ID based on the app
|
||||
const deviceId = 'flutter-app-boilerplate';
|
||||
final deviceAssetId = 'device-asset-${fileCreatedAt.millisecondsSinceEpoch}';
|
||||
|
||||
// Format dates in ISO 8601 format (UTC)
|
||||
final fileCreatedAtIso = fileCreatedAt.toUtc().toIso8601String();
|
||||
final fileModifiedAtIso = fileModifiedAt.toUtc().toIso8601String();
|
||||
|
||||
// Prepare metadata according to Immich API format
|
||||
// Format: [{"key":"mobile-app","value":{"caption":"...","tags":[]}}]
|
||||
final metadata = [
|
||||
{
|
||||
'key': 'mobile-app',
|
||||
'value': {
|
||||
'caption': fileName,
|
||||
'tags': <String>[],
|
||||
}
|
||||
}
|
||||
];
|
||||
final metadataJson = jsonEncode(metadata);
|
||||
|
||||
// Prepare form data for multipart upload
|
||||
// Based on working curl command:
|
||||
// curl -X POST "https://photos.satoshinakamoto.win/api/assets" \
|
||||
// -H "x-api-key: ..." \
|
||||
// -H "Content-Type: multipart/form-data" \
|
||||
// -F "[email protected];type=image/png" \
|
||||
// -F "deviceAssetId=device-asset-001" \
|
||||
// -F "deviceId=device-123" \
|
||||
// -F "fileCreatedAt=2025-11-06T12:34:56Z" \
|
||||
// -F "fileModifiedAt=2025-11-06T12:34:56Z" \
|
||||
// -F 'metadata=[{"key":"mobile-app","value":{"caption":"Test image","tags":[]}}]'
|
||||
final formData = FormData.fromMap({
|
||||
'assetData': await MultipartFile.fromFile(
|
||||
imageFile.path,
|
||||
filename: imageFile.path.split('/').last,
|
||||
filename: fileName,
|
||||
),
|
||||
'deviceAssetId': deviceAssetId,
|
||||
'deviceId': deviceId,
|
||||
'fileCreatedAt': fileCreatedAtIso,
|
||||
'fileModifiedAt': fileModifiedAtIso,
|
||||
'metadata': metadataJson,
|
||||
if (albumId != null) 'albumId': albumId,
|
||||
});
|
||||
|
||||
// Upload to Immich
|
||||
// According to Immich API documentation: POST /api/assets
|
||||
// Note: Don't set Content-Type header manually for multipart/form-data
|
||||
// Dio will set it automatically with the correct boundary
|
||||
|
||||
// Determine the correct endpoint path
|
||||
// If baseUrl already ends with /api, don't add it again
|
||||
String endpointPath;
|
||||
if (_baseUrl.endsWith('/api')) {
|
||||
endpointPath = '/assets';
|
||||
} else if (_baseUrl.endsWith('/api/')) {
|
||||
endpointPath = 'assets';
|
||||
} else {
|
||||
endpointPath = '/api/assets';
|
||||
}
|
||||
|
||||
final uploadUrl = '$_baseUrl$endpointPath';
|
||||
debugPrint('=== Immich Upload Request ===');
|
||||
debugPrint('URL: $uploadUrl');
|
||||
debugPrint('Base URL: $_baseUrl');
|
||||
debugPrint('File: $fileName, Size: ${await imageFile.length()} bytes');
|
||||
debugPrint('Device ID: $deviceId');
|
||||
debugPrint('Device Asset ID: $deviceAssetId');
|
||||
debugPrint('File Created At: $fileCreatedAtIso');
|
||||
debugPrint('File Modified At: $fileModifiedAtIso');
|
||||
debugPrint('Metadata: $metadataJson');
|
||||
|
||||
final response = await _dio.post(
|
||||
'/api/asset/upload',
|
||||
endpointPath,
|
||||
data: formData,
|
||||
options: Options(
|
||||
headers: {
|
||||
'x-api-key': _apiKey,
|
||||
// Don't set Content-Type - Dio handles it automatically for FormData
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
debugPrint('=== Immich Upload Response ===');
|
||||
debugPrint('Status Code: ${response.statusCode}');
|
||||
debugPrint('Response Data: ${response.data}');
|
||||
debugPrint('Response Headers: ${response.headers}');
|
||||
|
||||
if (response.statusCode != 200 && response.statusCode != 201) {
|
||||
final errorMessage = response.data is Map
|
||||
? (response.data as Map)['message']?.toString() ??
|
||||
response.statusMessage
|
||||
: response.statusMessage;
|
||||
debugPrint('Upload failed with status ${response.statusCode}: $errorMessage');
|
||||
throw ImmichException(
|
||||
'Upload failed: ${response.statusMessage}',
|
||||
'Upload failed: $errorMessage',
|
||||
response.statusCode,
|
||||
);
|
||||
}
|
||||
|
||||
final uploadResponse = UploadResponse.fromJson(response.data);
|
||||
// Log the response data structure
|
||||
if (response.data is Map) {
|
||||
debugPrint('Response is Map with keys: ${(response.data as Map).keys}');
|
||||
debugPrint('Full response map: ${response.data}');
|
||||
} else if (response.data is List) {
|
||||
debugPrint('Response is List with ${(response.data as List).length} items');
|
||||
debugPrint('First item: ${(response.data as List).first}');
|
||||
} else {
|
||||
debugPrint('Response type: ${response.data.runtimeType}');
|
||||
debugPrint('Response value: ${response.data}');
|
||||
}
|
||||
|
||||
// Handle response - it might be a single object or an array
|
||||
Map<String, dynamic> responseData;
|
||||
if (response.data is List && (response.data as List).isNotEmpty) {
|
||||
// If response is an array, take the first item
|
||||
responseData = (response.data as List).first as Map<String, dynamic>;
|
||||
debugPrint('Using first item from array response');
|
||||
} else if (response.data is Map) {
|
||||
responseData = response.data as Map<String, dynamic>;
|
||||
} else {
|
||||
throw ImmichException(
|
||||
'Unexpected response format: ${response.data.runtimeType}',
|
||||
response.statusCode,
|
||||
);
|
||||
}
|
||||
|
||||
final uploadResponse = UploadResponse.fromJson(responseData);
|
||||
debugPrint('Parsed Upload Response:');
|
||||
debugPrint(' ID: ${uploadResponse.id}');
|
||||
debugPrint(' Duplicate: ${uploadResponse.duplicate}');
|
||||
|
||||
// Fetch full asset details to store complete metadata
|
||||
final asset = await _getAssetById(uploadResponse.id);
|
||||
debugPrint('Fetching full asset details for ID: ${uploadResponse.id}');
|
||||
try {
|
||||
final asset = await _getAssetById(uploadResponse.id);
|
||||
debugPrint('Fetched asset: ${asset.id}, ${asset.fileName}');
|
||||
|
||||
// Store metadata in local storage
|
||||
await _storeAssetMetadata(asset);
|
||||
// Store metadata in local storage
|
||||
debugPrint('Storing asset metadata in local storage');
|
||||
await _storeAssetMetadata(asset);
|
||||
debugPrint('Asset metadata stored successfully');
|
||||
} catch (e) {
|
||||
// Log error but don't fail the upload - asset was uploaded successfully
|
||||
debugPrint('Warning: Failed to fetch/store asset metadata: $e');
|
||||
debugPrint('Upload was successful, but metadata caching failed');
|
||||
}
|
||||
|
||||
return uploadResponse;
|
||||
} on DioException catch (e) {
|
||||
@@ -127,15 +278,15 @@ class ImmichService {
|
||||
}
|
||||
|
||||
/// Fetches a list of assets from Immich.
|
||||
///
|
||||
///
|
||||
/// Based on official Immich API documentation: https://api.immich.app/endpoints/search/searchAssets
|
||||
/// Uses POST /api/search/metadata endpoint with search parameters.
|
||||
///
|
||||
///
|
||||
/// [limit] - Maximum number of assets to fetch (default: 100).
|
||||
/// [skip] - Number of assets to skip (for pagination).
|
||||
///
|
||||
///
|
||||
/// Returns a list of [ImmichAsset] instances.
|
||||
///
|
||||
///
|
||||
/// Throws [ImmichException] if fetch fails.
|
||||
/// Automatically stores fetched metadata in local storage.
|
||||
Future<List<ImmichAsset>> fetchAssets({
|
||||
@@ -163,15 +314,17 @@ class ImmichService {
|
||||
|
||||
// Parse response structure: {"assets": {"items": [...], "total": N, "count": N}}
|
||||
final responseData = response.data as Map<String, dynamic>;
|
||||
|
||||
|
||||
if (!responseData.containsKey('assets')) {
|
||||
throw ImmichException('Unexpected response format: missing "assets" field');
|
||||
throw ImmichException(
|
||||
'Unexpected response format: missing "assets" field');
|
||||
}
|
||||
|
||||
final assetsData = responseData['assets'] as Map<String, dynamic>;
|
||||
|
||||
|
||||
if (!assetsData.containsKey('items')) {
|
||||
throw ImmichException('Unexpected response format: missing "items" field in assets');
|
||||
throw ImmichException(
|
||||
'Unexpected response format: missing "items" field in assets');
|
||||
}
|
||||
|
||||
final assetsJson = assetsData['items'] as List<dynamic>;
|
||||
@@ -190,16 +343,13 @@ class ImmichService {
|
||||
final statusCode = e.response?.statusCode;
|
||||
final errorData = e.response?.data;
|
||||
String errorMessage;
|
||||
|
||||
|
||||
if (errorData is Map) {
|
||||
errorMessage = errorData['message']?.toString() ??
|
||||
errorData.toString();
|
||||
errorMessage = errorData['message']?.toString() ?? errorData.toString();
|
||||
} else {
|
||||
errorMessage = errorData?.toString() ??
|
||||
e.message ??
|
||||
'Unknown error';
|
||||
errorMessage = errorData?.toString() ?? e.message ?? 'Unknown error';
|
||||
}
|
||||
|
||||
|
||||
throw ImmichException(
|
||||
'Failed to fetch assets: $errorMessage',
|
||||
statusCode,
|
||||
@@ -213,14 +363,14 @@ class ImmichService {
|
||||
}
|
||||
|
||||
/// Fetches a single asset by ID.
|
||||
///
|
||||
///
|
||||
/// Based on official Immich API documentation: https://api.immich.app/endpoints/assets
|
||||
/// Endpoint: GET /api/assets/{id}
|
||||
///
|
||||
///
|
||||
/// [assetId] - The unique identifier (UUID) of the asset.
|
||||
///
|
||||
///
|
||||
/// Returns [ImmichAsset] if found.
|
||||
///
|
||||
///
|
||||
/// Throws [ImmichException] if fetch fails.
|
||||
Future<ImmichAsset> _getAssetById(String assetId) async {
|
||||
try {
|
||||
@@ -239,16 +389,13 @@ class ImmichService {
|
||||
final statusCode = e.response?.statusCode;
|
||||
final errorData = e.response?.data;
|
||||
String errorMessage;
|
||||
|
||||
|
||||
if (errorData is Map) {
|
||||
errorMessage = errorData['message']?.toString() ??
|
||||
errorData.toString();
|
||||
errorMessage = errorData['message']?.toString() ?? errorData.toString();
|
||||
} else {
|
||||
errorMessage = errorData?.toString() ??
|
||||
e.message ??
|
||||
'Unknown error';
|
||||
errorMessage = errorData?.toString() ?? e.message ?? 'Unknown error';
|
||||
}
|
||||
|
||||
|
||||
throw ImmichException(
|
||||
'Failed to fetch asset: $errorMessage',
|
||||
statusCode,
|
||||
@@ -259,7 +406,7 @@ class ImmichService {
|
||||
}
|
||||
|
||||
/// Stores asset metadata in local storage.
|
||||
///
|
||||
///
|
||||
/// [asset] - The asset to store.
|
||||
Future<void> _storeAssetMetadata(ImmichAsset asset) async {
|
||||
try {
|
||||
@@ -279,9 +426,9 @@ class ImmichService {
|
||||
}
|
||||
|
||||
/// Gets locally cached asset metadata.
|
||||
///
|
||||
///
|
||||
/// [assetId] - The unique identifier of the asset.
|
||||
///
|
||||
///
|
||||
/// Returns [ImmichAsset] if found in local storage, null otherwise.
|
||||
Future<ImmichAsset?> getCachedAsset(String assetId) async {
|
||||
try {
|
||||
@@ -296,7 +443,7 @@ class ImmichService {
|
||||
}
|
||||
|
||||
/// Gets all locally cached assets.
|
||||
///
|
||||
///
|
||||
/// Returns a list of [ImmichAsset] instances from local storage.
|
||||
Future<List<ImmichAsset>> getCachedAssets() async {
|
||||
try {
|
||||
@@ -317,22 +464,22 @@ class ImmichService {
|
||||
}
|
||||
|
||||
/// Gets the thumbnail URL for an asset.
|
||||
///
|
||||
///
|
||||
/// Uses GET /api/assets/{id}/thumbnail endpoint.
|
||||
///
|
||||
///
|
||||
/// [assetId] - The unique identifier of the asset.
|
||||
///
|
||||
///
|
||||
/// Returns the full URL to the thumbnail image.
|
||||
String getThumbnailUrl(String assetId) {
|
||||
return '$_baseUrl/api/assets/$assetId/thumbnail';
|
||||
}
|
||||
|
||||
/// Gets the full image URL for an asset.
|
||||
///
|
||||
///
|
||||
/// Uses GET /api/assets/{id}/original endpoint.
|
||||
///
|
||||
///
|
||||
/// [assetId] - The unique identifier of the asset.
|
||||
///
|
||||
///
|
||||
/// Returns the full URL to the original image file.
|
||||
String getImageUrl(String assetId) {
|
||||
return '$_baseUrl/api/assets/$assetId/original';
|
||||
@@ -342,22 +489,23 @@ class ImmichService {
|
||||
String get baseUrl => _baseUrl;
|
||||
|
||||
/// Fetches image bytes for an asset.
|
||||
///
|
||||
///
|
||||
/// Uses GET /api/assets/{id}/thumbnail for thumbnails or GET /api/assets/{id}/original for full images.
|
||||
///
|
||||
///
|
||||
/// [assetId] - The unique identifier of the asset (from metadata response).
|
||||
/// [isThumbnail] - Whether to fetch thumbnail (true) or original image (false). Default: true.
|
||||
///
|
||||
///
|
||||
/// Returns the image bytes as Uint8List.
|
||||
///
|
||||
///
|
||||
/// Throws [ImmichException] if fetch fails.
|
||||
Future<Uint8List> fetchImageBytes(String assetId, {bool isThumbnail = true}) async {
|
||||
Future<Uint8List> fetchImageBytes(String assetId,
|
||||
{bool isThumbnail = true}) async {
|
||||
try {
|
||||
// Use correct endpoint based on thumbnail vs original
|
||||
final endpoint = isThumbnail
|
||||
final endpoint = isThumbnail
|
||||
? '/api/assets/$assetId/thumbnail'
|
||||
: '/api/assets/$assetId/original';
|
||||
|
||||
|
||||
final response = await _dio.get<List<int>>(
|
||||
endpoint,
|
||||
options: Options(
|
||||
@@ -377,16 +525,13 @@ class ImmichService {
|
||||
final statusCode = e.response?.statusCode;
|
||||
final errorData = e.response?.data;
|
||||
String errorMessage;
|
||||
|
||||
|
||||
if (errorData is Map) {
|
||||
errorMessage = errorData['message']?.toString() ??
|
||||
errorData.toString();
|
||||
errorMessage = errorData['message']?.toString() ?? errorData.toString();
|
||||
} else {
|
||||
errorMessage = errorData?.toString() ??
|
||||
e.message ??
|
||||
'Unknown error';
|
||||
errorMessage = errorData?.toString() ?? e.message ?? 'Unknown error';
|
||||
}
|
||||
|
||||
|
||||
throw ImmichException(
|
||||
'Failed to fetch image: $errorMessage',
|
||||
statusCode,
|
||||
@@ -397,7 +542,7 @@ class ImmichService {
|
||||
}
|
||||
|
||||
/// Gets the headers needed for authenticated image requests.
|
||||
///
|
||||
///
|
||||
/// Returns a map of headers including the API key.
|
||||
Map<String, String> getImageHeaders() {
|
||||
return {
|
||||
@@ -406,9 +551,9 @@ class ImmichService {
|
||||
}
|
||||
|
||||
/// Tests the connection to Immich server by calling the /api/server/about endpoint.
|
||||
///
|
||||
///
|
||||
/// Returns server information including version and status.
|
||||
///
|
||||
///
|
||||
/// Throws [ImmichException] if the request fails.
|
||||
Future<Map<String, dynamic>> getServerInfo() async {
|
||||
try {
|
||||
@@ -426,16 +571,13 @@ class ImmichService {
|
||||
final statusCode = e.response?.statusCode;
|
||||
final errorData = e.response?.data;
|
||||
String errorMessage;
|
||||
|
||||
|
||||
if (errorData is Map) {
|
||||
errorMessage = errorData['message']?.toString() ??
|
||||
errorData.toString();
|
||||
errorMessage = errorData['message']?.toString() ?? errorData.toString();
|
||||
} else {
|
||||
errorMessage = errorData?.toString() ??
|
||||
e.message ??
|
||||
'Unknown error';
|
||||
errorMessage = errorData?.toString() ?? e.message ?? 'Unknown error';
|
||||
}
|
||||
|
||||
|
||||
throw ImmichException(
|
||||
'Failed to get server info: $errorMessage',
|
||||
statusCode,
|
||||
@@ -445,4 +587,3 @@ class ImmichService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,12 +22,12 @@ class NostrException implements Exception {
|
||||
}
|
||||
|
||||
/// Service for interacting with Nostr protocol.
|
||||
///
|
||||
///
|
||||
/// This service provides:
|
||||
/// - Keypair generation
|
||||
/// - Event publishing to relays
|
||||
/// - Metadata synchronization with multiple relays
|
||||
///
|
||||
///
|
||||
/// The service is modular and UI-independent, designed for testing without real relays.
|
||||
class NostrService {
|
||||
/// List of configured relays.
|
||||
@@ -37,20 +37,21 @@ class NostrService {
|
||||
final Map<String, WebSocketChannel?> _connections = {};
|
||||
|
||||
/// Stream controllers for relay messages.
|
||||
final Map<String, StreamController<Map<String, dynamic>>> _messageControllers = {};
|
||||
final Map<String, StreamController<Map<String, dynamic>>>
|
||||
_messageControllers = {};
|
||||
|
||||
/// Creates a [NostrService] instance.
|
||||
NostrService();
|
||||
|
||||
/// Generates a new Nostr keypair.
|
||||
///
|
||||
///
|
||||
/// Returns a [NostrKeyPair] with random private and public keys.
|
||||
NostrKeyPair generateKeyPair() {
|
||||
return NostrKeyPair.generate();
|
||||
}
|
||||
|
||||
/// Adds a relay to the service.
|
||||
///
|
||||
///
|
||||
/// [relayUrl] - The WebSocket URL of the relay (e.g., 'wss://relay.example.com').
|
||||
void addRelay(String relayUrl) {
|
||||
final relay = NostrRelay.fromUrl(relayUrl);
|
||||
@@ -60,7 +61,7 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Removes a relay from the service.
|
||||
///
|
||||
///
|
||||
/// [relayUrl] - The URL of the relay to remove.
|
||||
void removeRelay(String relayUrl) {
|
||||
_relays.removeWhere((r) => r.url == relayUrl);
|
||||
@@ -68,7 +69,7 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Enables or disables a relay.
|
||||
///
|
||||
///
|
||||
/// [relayUrl] - The URL of the relay to enable/disable.
|
||||
/// [enabled] - Whether the relay should be enabled.
|
||||
void setRelayEnabled(String relayUrl, bool enabled) {
|
||||
@@ -77,7 +78,7 @@ class NostrService {
|
||||
orElse: () => throw NostrException('Relay not found: $relayUrl'),
|
||||
);
|
||||
relay.isEnabled = enabled;
|
||||
|
||||
|
||||
// If disabling, also disconnect
|
||||
if (!enabled && relay.isConnected) {
|
||||
disconnectRelay(relayUrl);
|
||||
@@ -85,7 +86,7 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Toggles all relays enabled/disabled.
|
||||
///
|
||||
///
|
||||
/// [enabled] - Whether all relays should be enabled.
|
||||
void setAllRelaysEnabled(bool enabled) {
|
||||
for (final relay in _relays) {
|
||||
@@ -102,11 +103,11 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Connects to a relay.
|
||||
///
|
||||
///
|
||||
/// [relayUrl] - The URL of the relay to connect to.
|
||||
///
|
||||
///
|
||||
/// Returns a [Stream] of messages from the relay.
|
||||
///
|
||||
///
|
||||
/// Throws [NostrException] if connection fails.
|
||||
Future<Stream<Map<String, dynamic>>> connectRelay(String relayUrl) async {
|
||||
try {
|
||||
@@ -119,7 +120,8 @@ class NostrService {
|
||||
throw NostrException('Relay is disabled: $relayUrl');
|
||||
}
|
||||
|
||||
if (_connections.containsKey(relayUrl) && _connections[relayUrl] != null) {
|
||||
if (_connections.containsKey(relayUrl) &&
|
||||
_connections[relayUrl] != null) {
|
||||
// Already connected
|
||||
return _messageControllers[relayUrl]!.stream;
|
||||
}
|
||||
@@ -192,7 +194,7 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Disconnects from a relay.
|
||||
///
|
||||
///
|
||||
/// [relayUrl] - The URL of the relay to disconnect from.
|
||||
void disconnectRelay(String relayUrl) {
|
||||
final channel = _connections[relayUrl];
|
||||
@@ -207,17 +209,18 @@ class NostrService {
|
||||
_messageControllers.remove(relayUrl);
|
||||
}
|
||||
|
||||
final relay = _relays.firstWhere((r) => r.url == relayUrl, orElse: () => NostrRelay.fromUrl(relayUrl));
|
||||
final relay = _relays.firstWhere((r) => r.url == relayUrl,
|
||||
orElse: () => NostrRelay.fromUrl(relayUrl));
|
||||
relay.isConnected = false;
|
||||
}
|
||||
|
||||
/// Publishes an event to a relay.
|
||||
///
|
||||
///
|
||||
/// [event] - The Nostr event to publish.
|
||||
/// [relayUrl] - The URL of the relay to publish to.
|
||||
///
|
||||
///
|
||||
/// Returns a [Future] that completes when the event is published.
|
||||
///
|
||||
///
|
||||
/// Throws [NostrException] if publishing fails.
|
||||
Future<void> publishEvent(NostrEvent event, String relayUrl) async {
|
||||
try {
|
||||
@@ -229,7 +232,7 @@ class NostrService {
|
||||
// Convert to nostr_tools Event and then to JSON
|
||||
final nostrToolsEvent = event.toNostrToolsEvent();
|
||||
final eventJson = nostrToolsEvent.toJson();
|
||||
|
||||
|
||||
// Send event in Nostr format: ["EVENT", <event_json>]
|
||||
final message = jsonEncode(['EVENT', eventJson]);
|
||||
channel.sink.add(message);
|
||||
@@ -239,9 +242,9 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Publishes an event to all enabled relays.
|
||||
///
|
||||
///
|
||||
/// [event] - The Nostr event to publish.
|
||||
///
|
||||
///
|
||||
/// Returns a map of relay URLs to success/failure status.
|
||||
Future<Map<String, bool>> publishEventToAllRelays(NostrEvent event) async {
|
||||
final results = <String, bool>{};
|
||||
@@ -285,13 +288,13 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Syncs metadata by publishing an event with metadata content.
|
||||
///
|
||||
///
|
||||
/// [metadata] - The metadata to sync (as a Map).
|
||||
/// [privateKey] - Private key for signing the event.
|
||||
/// [kind] - Event kind (default: 0 for metadata).
|
||||
///
|
||||
///
|
||||
/// Returns the created and published event.
|
||||
///
|
||||
///
|
||||
/// Throws [NostrException] if sync fails.
|
||||
Future<NostrEvent> syncMetadata({
|
||||
required Map<String, dynamic> metadata,
|
||||
@@ -317,14 +320,15 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Fetches user profile (kind 0 metadata event) from relays.
|
||||
///
|
||||
///
|
||||
/// [publicKey] - The public key (hex format) of the user.
|
||||
/// [timeout] - Timeout for the request (default: 10 seconds).
|
||||
///
|
||||
///
|
||||
/// Returns [NostrProfile] if found, null otherwise.
|
||||
///
|
||||
///
|
||||
/// Throws [NostrException] if fetch fails.
|
||||
Future<NostrProfile?> fetchProfile(String publicKey, {Duration timeout = const Duration(seconds: 10)}) async {
|
||||
Future<NostrProfile?> fetchProfile(String publicKey,
|
||||
{Duration timeout = const Duration(seconds: 10)}) async {
|
||||
if (_relays.isEmpty) {
|
||||
throw NostrException('No relays configured');
|
||||
}
|
||||
@@ -333,7 +337,8 @@ class NostrService {
|
||||
for (final relay in _relays) {
|
||||
if (relay.isConnected) {
|
||||
try {
|
||||
final profile = await _fetchProfileFromRelay(publicKey, relay.url, timeout);
|
||||
final profile =
|
||||
await _fetchProfileFromRelay(publicKey, relay.url, timeout);
|
||||
if (profile != null) {
|
||||
return profile;
|
||||
}
|
||||
@@ -361,7 +366,8 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Fetches profile from a specific relay.
|
||||
Future<NostrProfile?> _fetchProfileFromRelay(String publicKey, String relayUrl, Duration timeout) async {
|
||||
Future<NostrProfile?> _fetchProfileFromRelay(
|
||||
String publicKey, String relayUrl, Duration timeout) async {
|
||||
final channel = _connections[relayUrl];
|
||||
final messageController = _messageControllers[relayUrl];
|
||||
if (channel == null || messageController == null) {
|
||||
@@ -371,20 +377,20 @@ class NostrService {
|
||||
// Send REQ message to request kind 0 events for this public key
|
||||
// Nostr REQ format: ["REQ", <subscription_id>, <filters>]
|
||||
final reqId = 'profile_${DateTime.now().millisecondsSinceEpoch}';
|
||||
|
||||
|
||||
final completer = Completer<NostrProfile?>();
|
||||
final subscription = messageController.stream.listen(
|
||||
(message) {
|
||||
// Message format from connectRelay:
|
||||
// Message format from connectRelay:
|
||||
// {'type': 'EVENT', 'subscription_id': <id>, 'data': <event_json>}
|
||||
// or {'type': 'EOSE', 'subscription_id': <id>, 'data': null}
|
||||
if (message['type'] == 'EVENT' &&
|
||||
if (message['type'] == 'EVENT' &&
|
||||
message['subscription_id'] == reqId &&
|
||||
message['data'] != null) {
|
||||
try {
|
||||
final eventData = message['data'];
|
||||
Event nostrToolsEvent;
|
||||
|
||||
|
||||
// Handle both JSON object and array formats
|
||||
if (eventData is Map<String, dynamic>) {
|
||||
// JSON object format
|
||||
@@ -394,8 +400,11 @@ class NostrService {
|
||||
created_at: eventData['created_at'] as int? ?? 0,
|
||||
kind: eventData['kind'] as int? ?? 0,
|
||||
tags: (eventData['tags'] as List<dynamic>?)
|
||||
?.map((tag) => (tag as List<dynamic>).map((e) => e.toString()).toList())
|
||||
.toList() ?? [],
|
||||
?.map((tag) => (tag as List<dynamic>)
|
||||
.map((e) => e.toString())
|
||||
.toList())
|
||||
.toList() ??
|
||||
[],
|
||||
content: eventData['content'] as String? ?? '',
|
||||
sig: eventData['sig'] as String? ?? '',
|
||||
verify: false, // Skip verification for profile fetching
|
||||
@@ -408,8 +417,11 @@ class NostrService {
|
||||
created_at: eventData[2] as int? ?? 0,
|
||||
kind: eventData[3] as int? ?? 0,
|
||||
tags: (eventData[4] as List<dynamic>?)
|
||||
?.map((tag) => (tag as List<dynamic>).map((e) => e.toString()).toList())
|
||||
.toList() ?? [],
|
||||
?.map((tag) => (tag as List<dynamic>)
|
||||
.map((e) => e.toString())
|
||||
.toList())
|
||||
.toList() ??
|
||||
[],
|
||||
content: eventData[5] as String? ?? '',
|
||||
sig: eventData[6] as String? ?? '',
|
||||
verify: false, // Skip verification for profile fetching
|
||||
@@ -417,16 +429,18 @@ class NostrService {
|
||||
} else {
|
||||
return; // Invalid format
|
||||
}
|
||||
|
||||
|
||||
// Convert to our NostrEvent model
|
||||
final event = NostrEvent.fromNostrToolsEvent(nostrToolsEvent);
|
||||
|
||||
|
||||
// Check if it's a kind 0 (metadata) event for this public key
|
||||
if (event.kind == 0 && event.pubkey.toLowerCase() == publicKey.toLowerCase()) {
|
||||
if (event.kind == 0 &&
|
||||
event.pubkey.toLowerCase() == publicKey.toLowerCase()) {
|
||||
final profile = NostrProfile.fromEventContent(
|
||||
publicKey: publicKey,
|
||||
content: event.content,
|
||||
updatedAt: DateTime.fromMillisecondsSinceEpoch(event.createdAt * 1000),
|
||||
updatedAt:
|
||||
DateTime.fromMillisecondsSinceEpoch(event.createdAt * 1000),
|
||||
);
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(profile);
|
||||
@@ -436,8 +450,8 @@ class NostrService {
|
||||
// Ignore parsing errors
|
||||
debugPrint('Error parsing profile event: $e');
|
||||
}
|
||||
} else if (message['type'] == 'EOSE' &&
|
||||
message['subscription_id'] == reqId) {
|
||||
} else if (message['type'] == 'EOSE' &&
|
||||
message['subscription_id'] == reqId) {
|
||||
// End of stored events - no profile found
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(null);
|
||||
@@ -461,33 +475,33 @@ class NostrService {
|
||||
'limit': 1,
|
||||
}
|
||||
]);
|
||||
|
||||
|
||||
channel.sink.add(reqMessage);
|
||||
|
||||
try {
|
||||
final profile = await completer.future.timeout(timeout);
|
||||
subscription?.cancel();
|
||||
subscription.cancel();
|
||||
return profile;
|
||||
} catch (e) {
|
||||
subscription?.cancel();
|
||||
subscription.cancel();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Fetches preferred relays from a NIP-05 identifier.
|
||||
///
|
||||
///
|
||||
/// NIP-05 verification endpoint format: https://<domain>/.well-known/nostr.json?name=<local-part>
|
||||
/// The response can include relay hints in the format:
|
||||
/// {
|
||||
/// "names": { "<local-part>": "<hex-pubkey>" },
|
||||
/// "relays": { "<hex-pubkey>": ["wss://relay1.com", "wss://relay2.com"] }
|
||||
/// }
|
||||
///
|
||||
///
|
||||
/// [nip05] - The NIP-05 identifier (e.g., '[email protected]').
|
||||
/// [publicKey] - The public key (hex format) to match against relay hints.
|
||||
///
|
||||
///
|
||||
/// Returns a list of preferred relay URLs, or empty list if none found.
|
||||
///
|
||||
///
|
||||
/// Throws [NostrException] if fetch fails.
|
||||
Future<List<String>> fetchPreferredRelaysFromNip05(
|
||||
String nip05,
|
||||
@@ -504,7 +518,8 @@ class NostrService {
|
||||
final domain = parts[1];
|
||||
|
||||
// Construct the verification URL
|
||||
final url = Uri.https(domain, '/.well-known/nostr.json', {'name': localPart});
|
||||
final url =
|
||||
Uri.https(domain, '/.well-known/nostr.json', {'name': localPart});
|
||||
|
||||
// Fetch the NIP-05 verification data
|
||||
final response = await http.get(url).timeout(
|
||||
@@ -515,7 +530,8 @@ class NostrService {
|
||||
);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw NostrException('Failed to fetch NIP-05 data: ${response.statusCode}');
|
||||
throw NostrException(
|
||||
'Failed to fetch NIP-05 data: ${response.statusCode}');
|
||||
}
|
||||
|
||||
// Parse the JSON response
|
||||
@@ -552,20 +568,21 @@ class NostrService {
|
||||
}
|
||||
|
||||
/// Loads preferred relays from NIP-05 if available and adds them to the relay list.
|
||||
///
|
||||
///
|
||||
/// [nip05] - The NIP-05 identifier (e.g., '[email protected]').
|
||||
/// [publicKey] - The public key (hex format) to match against relay hints.
|
||||
///
|
||||
///
|
||||
/// Returns the number of relays added.
|
||||
///
|
||||
///
|
||||
/// Throws [NostrException] if fetch fails.
|
||||
Future<int> loadPreferredRelaysFromNip05(
|
||||
String nip05,
|
||||
String publicKey,
|
||||
) async {
|
||||
try {
|
||||
final preferredRelays = await fetchPreferredRelaysFromNip05(nip05, publicKey);
|
||||
|
||||
final preferredRelays =
|
||||
await fetchPreferredRelaysFromNip05(nip05, publicKey);
|
||||
|
||||
int addedCount = 0;
|
||||
for (final relayUrl in preferredRelays) {
|
||||
try {
|
||||
@@ -594,4 +611,3 @@ class NostrService {
|
||||
_relays.clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user