nostr tools added
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import 'dart:convert';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:nostr_tools/nostr_tools.dart';
|
||||
|
||||
/// Represents a Nostr event.
|
||||
class NostrEvent {
|
||||
@@ -24,6 +23,10 @@ class NostrEvent {
|
||||
/// Event signature (64-byte hex string).
|
||||
final String sig;
|
||||
|
||||
/// Event API instance for event operations.
|
||||
static final _eventApi = EventApi();
|
||||
static final _keyApi = KeyApi();
|
||||
|
||||
/// Creates a [NostrEvent] with the provided values.
|
||||
NostrEvent({
|
||||
required this.id,
|
||||
@@ -50,6 +53,33 @@ class NostrEvent {
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a [NostrEvent] from a nostr_tools Event object.
|
||||
factory NostrEvent.fromNostrToolsEvent(Event event) {
|
||||
return NostrEvent(
|
||||
id: event.id,
|
||||
pubkey: event.pubkey,
|
||||
createdAt: event.created_at,
|
||||
kind: event.kind,
|
||||
tags: event.tags,
|
||||
content: event.content,
|
||||
sig: event.sig,
|
||||
);
|
||||
}
|
||||
|
||||
/// Converts this [NostrEvent] to a nostr_tools Event object.
|
||||
Event toNostrToolsEvent() {
|
||||
return Event(
|
||||
id: id,
|
||||
pubkey: pubkey,
|
||||
created_at: createdAt,
|
||||
kind: kind,
|
||||
tags: tags,
|
||||
content: content,
|
||||
sig: sig,
|
||||
verify: false, // Already verified if coming from our model
|
||||
);
|
||||
}
|
||||
|
||||
/// Converts the [NostrEvent] to a JSON array (Nostr event format).
|
||||
List<dynamic> toJson() {
|
||||
return [
|
||||
@@ -63,7 +93,7 @@ class NostrEvent {
|
||||
];
|
||||
}
|
||||
|
||||
/// Creates an event from content and signs it with a private key.
|
||||
/// Creates an event from content and signs it with a private key using nostr_tools.
|
||||
///
|
||||
/// [content] - Event content.
|
||||
/// [kind] - Event kind (default: 1 for text note).
|
||||
@@ -75,51 +105,42 @@ class NostrEvent {
|
||||
required String privateKey,
|
||||
List<List<String>>? tags,
|
||||
}) {
|
||||
// Derive public key from private key (simplified)
|
||||
final privateKeyBytes = _hexToBytes(privateKey);
|
||||
final publicKeyBytes = sha256.convert(privateKeyBytes).bytes.sublist(0, 32);
|
||||
final pubkey = publicKeyBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
// Get public key from private key using nostr_tools
|
||||
final pubkey = _keyApi.getPublicKey(privateKey);
|
||||
|
||||
final createdAt = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
||||
final eventTags = tags ?? [];
|
||||
|
||||
// Create event data for signing
|
||||
final eventData = [
|
||||
0,
|
||||
pubkey,
|
||||
createdAt,
|
||||
kind,
|
||||
eventTags,
|
||||
content,
|
||||
];
|
||||
|
||||
// Generate event ID (hash of event data)
|
||||
final eventJson = jsonEncode(eventData);
|
||||
final idBytes = sha256.convert(utf8.encode(eventJson)).bytes.sublist(0, 32);
|
||||
final id = idBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
// Generate signature (simplified - in real Nostr, use secp256k1)
|
||||
final sigBytes = sha256.convert(utf8.encode(id + privateKey)).bytes.sublist(0, 32);
|
||||
final sig = sigBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
return NostrEvent(
|
||||
id: id,
|
||||
pubkey: pubkey,
|
||||
createdAt: createdAt,
|
||||
// Create event using nostr_tools Event model
|
||||
final event = Event(
|
||||
kind: kind,
|
||||
tags: eventTags,
|
||||
content: content,
|
||||
sig: sig,
|
||||
created_at: createdAt,
|
||||
pubkey: pubkey,
|
||||
verify: false, // We'll sign it next
|
||||
);
|
||||
|
||||
// Get event hash (ID) using nostr_tools
|
||||
event.id = _eventApi.getEventHash(event);
|
||||
|
||||
// Sign the event using nostr_tools
|
||||
event.sig = _eventApi.signEvent(event, privateKey);
|
||||
|
||||
// Convert to our NostrEvent model
|
||||
return NostrEvent.fromNostrToolsEvent(event);
|
||||
}
|
||||
|
||||
/// Converts hex string to bytes.
|
||||
static List<int> _hexToBytes(String hex) {
|
||||
final result = <int>[];
|
||||
for (int i = 0; i < hex.length; i += 2) {
|
||||
result.add(int.parse(hex.substring(i, i + 2), radix: 16));
|
||||
/// Verifies the event signature using nostr_tools.
|
||||
///
|
||||
/// Returns true if the signature is valid, false otherwise.
|
||||
bool verifySignature() {
|
||||
try {
|
||||
final event = toNostrToolsEvent();
|
||||
return _eventApi.verifySignature(event);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -127,4 +148,3 @@ class NostrEvent {
|
||||
return 'NostrEvent(id: ${id.substring(0, 8)}..., kind: $kind, content: ${content.substring(0, content.length > 20 ? 20 : content.length)}...)';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import 'dart:convert';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:nostr_tools/nostr_tools.dart';
|
||||
|
||||
/// Represents a Nostr keypair (private and public keys).
|
||||
class NostrKeyPair {
|
||||
@@ -9,6 +8,12 @@ class NostrKeyPair {
|
||||
/// Public key in hex format (32 bytes, 64 hex characters).
|
||||
final String publicKey;
|
||||
|
||||
/// Key API instance for key operations.
|
||||
static final _keyApi = KeyApi();
|
||||
|
||||
/// NIP-19 API instance for bech32 encoding/decoding.
|
||||
static final _nip19 = Nip19();
|
||||
|
||||
/// Creates a [NostrKeyPair] with the provided keys.
|
||||
///
|
||||
/// [privateKey] - Private key in hex format.
|
||||
@@ -18,25 +23,91 @@ class NostrKeyPair {
|
||||
required this.publicKey,
|
||||
});
|
||||
|
||||
/// Generates a new Nostr keypair.
|
||||
/// Generates a new Nostr keypair using nostr_tools.
|
||||
///
|
||||
/// Returns a new [NostrKeyPair] with random private and public keys.
|
||||
factory NostrKeyPair.generate() {
|
||||
// Generate random 32-byte private key
|
||||
final random = List<int>.generate(32, (i) => DateTime.now().microsecondsSinceEpoch % 256);
|
||||
final privateKeyBytes = sha256.convert(utf8.encode(DateTime.now().toString() + random.toString())).bytes.sublist(0, 32);
|
||||
final privateKey = privateKeyBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
// Derive public key from private key (simplified - in real Nostr, use secp256k1)
|
||||
final publicKeyBytes = sha256.convert(privateKeyBytes).bytes.sublist(0, 32);
|
||||
final publicKey = publicKeyBytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
final privateKey = _keyApi.generatePrivateKey();
|
||||
final publicKey = _keyApi.getPublicKey(privateKey);
|
||||
|
||||
return NostrKeyPair(
|
||||
privateKey: privateKey,
|
||||
publicKey: publicKey,
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a [NostrKeyPair] from nsec (private key in bech32 format).
|
||||
///
|
||||
/// [nsec] - Private key in nsec format (e.g., 'nsec1...').
|
||||
///
|
||||
/// Returns a [NostrKeyPair] with the decoded private key and derived public key.
|
||||
///
|
||||
/// Throws [FormatException] if nsec is invalid.
|
||||
factory NostrKeyPair.fromNsec(String nsec) {
|
||||
try {
|
||||
final decoded = _nip19.decode(nsec);
|
||||
if (decoded['type'] != 'nsec') {
|
||||
throw FormatException('Invalid nsec format: expected "nsec" type');
|
||||
}
|
||||
|
||||
final privateKey = decoded['data'] as String;
|
||||
final publicKey = _keyApi.getPublicKey(privateKey);
|
||||
|
||||
return NostrKeyPair(
|
||||
privateKey: privateKey,
|
||||
publicKey: publicKey,
|
||||
);
|
||||
} catch (e) {
|
||||
throw FormatException('Failed to parse nsec: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [NostrKeyPair] from npub (public key in bech32 format).
|
||||
///
|
||||
/// Note: This creates a keypair with only the public key. Private key operations won't work.
|
||||
///
|
||||
/// [npub] - Public key in npub format (e.g., 'npub1...').
|
||||
///
|
||||
/// Returns a [NostrKeyPair] with the decoded public key and empty private key.
|
||||
///
|
||||
/// Throws [FormatException] if npub is invalid.
|
||||
factory NostrKeyPair.fromNpub(String npub) {
|
||||
try {
|
||||
final decoded = _nip19.decode(npub);
|
||||
if (decoded['type'] != 'npub') {
|
||||
throw FormatException('Invalid npub format: expected "npub" type');
|
||||
}
|
||||
|
||||
final publicKey = decoded['data'] as String;
|
||||
|
||||
// No private key available when importing from npub
|
||||
return NostrKeyPair(
|
||||
privateKey: '', // Empty private key - can't sign events
|
||||
publicKey: publicKey,
|
||||
);
|
||||
} catch (e) {
|
||||
throw FormatException('Failed to parse npub: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [NostrKeyPair] from a hex private key.
|
||||
///
|
||||
/// [hexPrivateKey] - Private key in hex format (64 hex characters).
|
||||
///
|
||||
/// Returns a [NostrKeyPair] with the provided private key and derived public key.
|
||||
factory NostrKeyPair.fromHexPrivateKey(String hexPrivateKey) {
|
||||
if (hexPrivateKey.length != 64) {
|
||||
throw FormatException('Invalid hex private key: expected 64 hex characters');
|
||||
}
|
||||
|
||||
final publicKey = _keyApi.getPublicKey(hexPrivateKey);
|
||||
|
||||
return NostrKeyPair(
|
||||
privateKey: hexPrivateKey,
|
||||
publicKey: publicKey,
|
||||
);
|
||||
}
|
||||
|
||||
/// Creates a [NostrKeyPair] from a JSON map.
|
||||
factory NostrKeyPair.fromJson(Map<String, dynamic> json) {
|
||||
return NostrKeyPair(
|
||||
@@ -53,9 +124,21 @@ class NostrKeyPair {
|
||||
};
|
||||
}
|
||||
|
||||
/// Encodes the private key to nsec format.
|
||||
String toNsec() {
|
||||
if (privateKey.isEmpty) {
|
||||
throw StateError('Cannot encode empty private key to nsec');
|
||||
}
|
||||
return _nip19.nsecEncode(privateKey);
|
||||
}
|
||||
|
||||
/// Encodes the public key to npub format.
|
||||
String toNpub() {
|
||||
return _nip19.npubEncode(publicKey);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'NostrKeyPair(publicKey: ${publicKey.substring(0, 8)}...)';
|
||||
return 'NostrKeyPair(publicKey: $publicKey)';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import 'dart:convert';
|
||||
|
||||
/// Represents a Nostr user profile (metadata from kind 0 events).
|
||||
class NostrProfile {
|
||||
/// Public key (npub or hex).
|
||||
final String publicKey;
|
||||
|
||||
/// Display name or username.
|
||||
final String? name;
|
||||
|
||||
/// About/bio text.
|
||||
final String? about;
|
||||
|
||||
/// Profile picture URL.
|
||||
final String? picture;
|
||||
|
||||
/// Website URL.
|
||||
final String? website;
|
||||
|
||||
/// NIP-05 identifier (e.g., [email protected]).
|
||||
final String? nip05;
|
||||
|
||||
/// Banner image URL.
|
||||
final String? banner;
|
||||
|
||||
/// LUD16 (Lightning address).
|
||||
final String? lud16;
|
||||
|
||||
/// Raw metadata JSON for additional fields.
|
||||
final Map<String, dynamic> rawMetadata;
|
||||
|
||||
/// Timestamp when profile was last updated.
|
||||
final DateTime? updatedAt;
|
||||
|
||||
/// Creates a [NostrProfile] instance.
|
||||
NostrProfile({
|
||||
required this.publicKey,
|
||||
this.name,
|
||||
this.about,
|
||||
this.picture,
|
||||
this.website,
|
||||
this.nip05,
|
||||
this.banner,
|
||||
this.lud16,
|
||||
Map<String, dynamic>? rawMetadata,
|
||||
this.updatedAt,
|
||||
}) : rawMetadata = rawMetadata ?? {};
|
||||
|
||||
/// Creates a [NostrProfile] from Nostr metadata event content (JSON string).
|
||||
///
|
||||
/// [publicKey] - The public key of the profile owner.
|
||||
/// [content] - JSON string from kind 0 event content.
|
||||
/// [updatedAt] - Optional timestamp when profile was updated.
|
||||
factory NostrProfile.fromEventContent({
|
||||
required String publicKey,
|
||||
required String content,
|
||||
DateTime? updatedAt,
|
||||
}) {
|
||||
try {
|
||||
final metadata = jsonDecode(content) as Map<String, dynamic>;
|
||||
|
||||
return NostrProfile(
|
||||
publicKey: publicKey,
|
||||
name: metadata['name'] as String?,
|
||||
about: metadata['about'] as String?,
|
||||
picture: metadata['picture'] as String?,
|
||||
website: metadata['website'] as String?,
|
||||
nip05: metadata['nip05'] as String?,
|
||||
banner: metadata['banner'] as String?,
|
||||
lud16: metadata['lud16'] as String?,
|
||||
rawMetadata: metadata,
|
||||
updatedAt: updatedAt ?? DateTime.now(),
|
||||
);
|
||||
} catch (e) {
|
||||
// Return minimal profile if parsing fails
|
||||
return NostrProfile(
|
||||
publicKey: publicKey,
|
||||
rawMetadata: {},
|
||||
updatedAt: updatedAt ?? DateTime.now(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a [NostrProfile] from a JSON map.
|
||||
factory NostrProfile.fromJson(Map<String, dynamic> json) {
|
||||
return NostrProfile(
|
||||
publicKey: json['publicKey'] as String,
|
||||
name: json['name'] as String?,
|
||||
about: json['about'] as String?,
|
||||
picture: json['picture'] as String?,
|
||||
website: json['website'] as String?,
|
||||
nip05: json['nip05'] as String?,
|
||||
banner: json['banner'] as String?,
|
||||
lud16: json['lud16'] as String?,
|
||||
rawMetadata: json['rawMetadata'] as Map<String, dynamic>? ?? {},
|
||||
updatedAt: json['updatedAt'] != null
|
||||
? DateTime.parse(json['updatedAt'] as String)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
/// Converts [NostrProfile] to JSON.
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'publicKey': publicKey,
|
||||
'name': name,
|
||||
'about': about,
|
||||
'picture': picture,
|
||||
'website': website,
|
||||
'nip05': nip05,
|
||||
'banner': banner,
|
||||
'lud16': lud16,
|
||||
'rawMetadata': rawMetadata,
|
||||
'updatedAt': updatedAt?.toIso8601String(),
|
||||
};
|
||||
}
|
||||
|
||||
/// Gets display name (name, nip05, or public key prefix).
|
||||
String get displayName {
|
||||
if (name != null && name!.isNotEmpty) return name!;
|
||||
if (nip05 != null && nip05!.isNotEmpty) return nip05!;
|
||||
return publicKey.length > 16
|
||||
? '${publicKey.substring(0, 8)}...${publicKey.substring(publicKey.length - 8)}'
|
||||
: publicKey;
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'NostrProfile(publicKey: ${publicKey.substring(0, 8)}..., name: $name)';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import 'package:nostr_tools/nostr_tools.dart';
|
||||
import 'models/nostr_keypair.dart';
|
||||
import 'models/nostr_event.dart';
|
||||
import 'models/nostr_relay.dart';
|
||||
import 'models/nostr_profile.dart';
|
||||
|
||||
/// Exception thrown when Nostr operations fail.
|
||||
class NostrException implements Exception {
|
||||
@@ -104,11 +107,31 @@ class NostrService {
|
||||
(message) {
|
||||
try {
|
||||
final data = jsonDecode(message as String);
|
||||
if (data is List) {
|
||||
controller.add({
|
||||
'type': data[0] as String,
|
||||
'data': data.length > 1 ? data[1] : null,
|
||||
});
|
||||
if (data is List && data.isNotEmpty) {
|
||||
final messageType = data[0] as String;
|
||||
if (messageType == 'EVENT' && data.length >= 3) {
|
||||
// EVENT format: ["EVENT", <subscription_id>, <event_json>]
|
||||
// event_json can be either a JSON object or array format
|
||||
final eventData = data[2];
|
||||
controller.add({
|
||||
'type': 'EVENT',
|
||||
'subscription_id': data[1],
|
||||
'data': eventData,
|
||||
});
|
||||
} else if (messageType == 'EOSE' && data.length >= 2) {
|
||||
// EOSE format: ["EOSE", <subscription_id>]
|
||||
controller.add({
|
||||
'type': 'EOSE',
|
||||
'subscription_id': data[1],
|
||||
'data': null,
|
||||
});
|
||||
} else {
|
||||
// Other message types
|
||||
controller.add({
|
||||
'type': messageType,
|
||||
'data': data.length > 1 ? data[1] : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore invalid messages
|
||||
@@ -165,8 +188,12 @@ class NostrService {
|
||||
throw NostrException('Not connected to relay: $relayUrl');
|
||||
}
|
||||
|
||||
// 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', event.toJson()]);
|
||||
final message = jsonEncode(['EVENT', eventJson]);
|
||||
channel.sink.add(message);
|
||||
} catch (e) {
|
||||
throw NostrException('Failed to publish event: $e');
|
||||
@@ -229,6 +256,163 @@ 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 {
|
||||
if (_relays.isEmpty) {
|
||||
throw NostrException('No relays configured');
|
||||
}
|
||||
|
||||
// Try to fetch from connected relays first
|
||||
for (final relay in _relays) {
|
||||
if (relay.isConnected) {
|
||||
try {
|
||||
final profile = await _fetchProfileFromRelay(publicKey, relay.url, timeout);
|
||||
if (profile != null) {
|
||||
return profile;
|
||||
}
|
||||
} catch (e) {
|
||||
// Continue to next relay
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no connected relays or all failed, try connecting to first relay
|
||||
if (_relays.isNotEmpty) {
|
||||
try {
|
||||
final firstRelay = _relays.first;
|
||||
if (!firstRelay.isConnected) {
|
||||
await connectRelay(firstRelay.url).timeout(timeout);
|
||||
}
|
||||
return await _fetchProfileFromRelay(publicKey, firstRelay.url, timeout);
|
||||
} catch (e) {
|
||||
throw NostrException('Failed to fetch profile: $e');
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Fetches profile from a specific relay.
|
||||
Future<NostrProfile?> _fetchProfileFromRelay(String publicKey, String relayUrl, Duration timeout) async {
|
||||
final channel = _connections[relayUrl];
|
||||
if (channel == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 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 = _messageControllers[relayUrl]?.stream.listen(
|
||||
(message) {
|
||||
// Message format from connectRelay:
|
||||
// {'type': 'EVENT', 'subscription_id': <id>, 'data': <event_json>}
|
||||
// or {'type': 'EOSE', 'subscription_id': <id>, 'data': null}
|
||||
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
|
||||
nostrToolsEvent = Event(
|
||||
id: eventData['id'] as String? ?? '',
|
||||
pubkey: eventData['pubkey'] as String? ?? '',
|
||||
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() ?? [],
|
||||
content: eventData['content'] as String? ?? '',
|
||||
sig: eventData['sig'] as String? ?? '',
|
||||
verify: false, // Skip verification for profile fetching
|
||||
);
|
||||
} else if (eventData is List && eventData.length >= 7) {
|
||||
// Array format: [id, pubkey, created_at, kind, tags, content, sig]
|
||||
nostrToolsEvent = Event(
|
||||
id: eventData[0] as String? ?? '',
|
||||
pubkey: eventData[1] as String? ?? '',
|
||||
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() ?? [],
|
||||
content: eventData[5] as String? ?? '',
|
||||
sig: eventData[6] as String? ?? '',
|
||||
verify: false, // Skip verification for profile fetching
|
||||
);
|
||||
} 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()) {
|
||||
final profile = NostrProfile.fromEventContent(
|
||||
publicKey: publicKey,
|
||||
content: event.content,
|
||||
updatedAt: DateTime.fromMillisecondsSinceEpoch(event.createdAt * 1000),
|
||||
);
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(profile);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore parsing errors
|
||||
debugPrint('Error parsing profile event: $e');
|
||||
}
|
||||
} else if (message['type'] == 'EOSE' &&
|
||||
message['subscription_id'] == reqId) {
|
||||
// End of stored events - no profile found
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete(null);
|
||||
}
|
||||
}
|
||||
},
|
||||
onError: (error) {
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Send REQ message to request kind 0 events for this public key
|
||||
final reqMessage = jsonEncode([
|
||||
'REQ',
|
||||
reqId,
|
||||
{
|
||||
'authors': [publicKey],
|
||||
'kinds': [0],
|
||||
'limit': 1,
|
||||
}
|
||||
]);
|
||||
|
||||
channel.sink.add(reqMessage);
|
||||
|
||||
try {
|
||||
final profile = await completer.future.timeout(timeout);
|
||||
subscription?.cancel();
|
||||
return profile;
|
||||
} catch (e) {
|
||||
subscription?.cancel();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes all connections and cleans up resources.
|
||||
void dispose() {
|
||||
for (final relayUrl in _connections.keys.toList()) {
|
||||
|
||||
Reference in New Issue
Block a user