upload image to nostr working

This commit is contained in:
gitea
2025-11-06 23:36:24 +01:00
parent 49dd0fdaf1
commit 2c5f0eaefc
7 changed files with 734 additions and 152 deletions
+75 -59
View File
@@ -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();
}
}