2024-12-10 22:28:38 +03:00
|
|
|
use nostr_sdk::client::Error;
|
|
|
|
use nostr_sdk::prelude::*;
|
|
|
|
use nostr_sdk::RelayPoolNotification;
|
|
|
|
|
|
|
|
pub struct NostrClient {
|
|
|
|
client: Client,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl NostrClient {
|
|
|
|
pub async fn new(relay_url: &str) -> Result<Self, Error> {
|
2024-12-12 23:24:23 +03:00
|
|
|
let keys = Keys::new(SecretKey::generate());
|
|
|
|
let client = Client::new(keys);
|
|
|
|
client.add_relay(relay_url).await?;
|
2024-12-10 22:28:38 +03:00
|
|
|
client.connect().await;
|
|
|
|
|
|
|
|
Ok(Self { client })
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn publish_item(
|
|
|
|
&self,
|
|
|
|
name: String,
|
|
|
|
description: String,
|
|
|
|
tags: Vec<(String, String)>
|
|
|
|
) -> Result<(), Error> {
|
2024-12-12 23:24:23 +03:00
|
|
|
let content = format!("{{\"name\":\"{}\",\"description\":\"{}\",\"tags\":[{}]}}", name, description, tags.iter().map(|(k, v)| format!("(\"{}\",\"{}\")", k, v)).collect::<Vec<_>>().join(","));
|
|
|
|
let event = EventBuilder::new(Kind::TextNote, content).build()?;
|
|
|
|
self.client.send_event_builder(event).await?;
|
2024-12-10 22:28:38 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn subscribe_to_items(
|
|
|
|
&self,
|
2024-12-12 23:24:23 +03:00
|
|
|
tx: std::sync::mpsc::Sender<String>
|
2024-12-10 22:28:38 +03:00
|
|
|
) -> Result<(), Error> {
|
|
|
|
let mut notifications = self.client.notifications();
|
2024-12-12 23:24:23 +03:00
|
|
|
std::thread::spawn(move || {
|
2024-12-10 22:28:38 +03:00
|
|
|
while let Ok(notification) = notifications.recv().await {
|
2024-12-12 23:24:23 +03:00
|
|
|
if let RelayPoolNotification::Event { relay_url, subscription_id, event } = notification {
|
2024-12-10 22:28:38 +03:00
|
|
|
let content = event.content.clone();
|
|
|
|
tx.send(content).await.unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|