All basic functions plus guide README to use

This commit is contained in:
Malte Schröder
2025-12-19 20:25:39 +01:00
parent db48f07b78
commit 397635d43e
12 changed files with 486 additions and 22 deletions

93
src/bin/testall.rs Normal file
View File

@@ -0,0 +1,93 @@
use easy_nostr::EasyNostr;
use nostr_sdk::prelude::*;
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
println!("=== EasyNostr Production Test Suite ===");
// 1. Identity
let keys = Keys::generate();
let nsec = keys.secret_key().to_bech32()?;
let npub = keys.public_key().to_bech32()?;
println!("[INFO] Identity: {}", npub);
// 2. Init
let ez = EasyNostr::new(&nsec).await?;
// 3. Relays (More reliable set)
println!("\n[STEP 1] Connecting to Relays...");
let relays = vec![
"wss://relay.damus.io",
"wss://nos.lol",
"wss://relay.primal.net",
];
ez.add_relays(relays).await?;
// Give relays a moment to fully welcome us
sleep(Duration::from_secs(2)).await;
println!(" [OK] Connected.");
// 4. Follow Self (Critical for Timeline Test reliability)
println!("\n[STEP 2] Following Self (for robust timeline testing)...");
ez.create_contact(&npub, Some("Me Myself".to_string()))
.await?;
println!(" [OK] Followed self.");
// 5. Publish Post
println!("\n[STEP 3] Publishing Post...");
let secret_code = format!("Test Run {}", Timestamp::now().as_secs());
let event_id = ez
.post_text(&format!("Hello Nostr! {}", secret_code))
.await?;
println!(" [OK] Posted: {}", event_id.to_bech32()?);
// 6. Verify Timeline (with Retry)
println!("\n[STEP 4] verifying Timeline (expecting own post)...");
let mut found_post = false;
for i in 1..=5 {
sleep(Duration::from_secs(2)).await; // Wait for propagation
let posts = ez.get_timeline(vec![npub.clone()]).await?;
// Look for our specific post
if posts.iter().any(|p| p.content.contains(&secret_code)) {
println!(" [OK] Found our post in timeline after {}s!", i * 2);
found_post = true;
break;
} else {
println!(" ... attempt {}/5: Post not yet visible...", i);
}
}
if !found_post {
println!(" [ERR] Verified Failed: Post did not appear in timeline.");
}
// 7. DM Test (with Retry)
println!("\n[STEP 5] Testing Direct Messages...");
let dm_msg = format!("Secret DM {}", secret_code);
ez.send_private_message(&npub, &dm_msg).await?;
let mut found_dm = false;
for i in 1..=5 {
sleep(Duration::from_secs(2)).await;
let dms = ez.get_private_messages(&npub).await?;
if dms.iter().any(|m| m.content == dm_msg) {
println!(" [OK] Found DM after {}s!", i * 2);
found_dm = true;
break;
} else {
println!(" ... attempt {}/5: DM not yet visible...", i);
}
}
if !found_dm {
println!(" [ERR] DM propagation failed.");
// Non-fatal, DMs are slower
}
println!("\n=== Test Complete ===");
Ok(())
}

75
src/functions/feed.rs Normal file
View File

@@ -0,0 +1,75 @@
use crate::nips::nip01::Post;
use anyhow::{Context, Result};
use nostr_sdk::prelude::*;
use std::time::Duration;
/// Fetches a timeline/feed of posts from specific users (Followed users).
///
/// # Arguments
/// * `client` - The Nostr client.
/// * `followed_pubkeys` - A list of hex strings (bech32 also works if parsed correctly, but we assume hex or wait for parsing) representing the users to follow.
///
/// The function parses the keys, creates a filter, and returns a list of sorted Posts.
pub async fn get_followed_feed(
client: &Client,
followed_pubkeys: Vec<String>,
) -> Result<Vec<Post>> {
let mut keys = Vec::new();
for key in followed_pubkeys {
// We try to parse each key. If one fails, we just ignore it or log it (here we context it).
let pk = PublicKey::parse(&key).context(format!("Invalid public key: {}", key))?;
keys.push(pk);
}
if keys.is_empty() {
return Ok(Vec::new());
}
// Create a filter for Text Notes (Kind 1) from these authors
let filter = Filter::new().kind(Kind::TextNote).authors(keys).limit(50); // Limit to 50 posts for now
let timeout = Duration::from_secs(10);
let events = client.fetch_events(filter, timeout).await?;
// Convert Events to our Post struct
let mut posts: Vec<Post> = events
.into_iter()
.map(|e| Post {
id: e.id,
author: e.pubkey,
content: e.content.clone(),
created_at: e.created_at,
})
.collect();
// Sort by created_at descending (newest first)
posts.sort_by(|a, b| b.created_at.cmp(&a.created_at));
Ok(posts)
}
/// Fetches random (recent) posts from the connected Relays (Global Feed).
///
/// This is useful for discovery.
pub async fn get_random_posts(client: &Client) -> Result<Vec<Post>> {
// Filter for any Text Note, limit 20
let filter = Filter::new().kind(Kind::TextNote).limit(20);
let timeout = Duration::from_secs(10);
let events = client.fetch_events(filter, timeout).await?;
let mut posts: Vec<Post> = events
.into_iter()
.map(|e| Post {
id: e.id,
author: e.pubkey,
content: e.content.clone(),
created_at: e.created_at,
})
.collect();
// Sort by newest first
posts.sort_by(|a, b| b.created_at.cmp(&a.created_at));
Ok(posts)
}

View File

@@ -1,5 +1,7 @@
pub mod new;
pub mod messages;
pub mod relays;
pub mod create_contact;
pub mod feed;
pub mod get_contacts;
pub mod create_contact;
pub mod messages;
pub mod new;
pub mod publish;
pub mod relays;

13
src/functions/publish.rs Normal file
View File

@@ -0,0 +1,13 @@
use crate::nips::nip01;
use anyhow::Result;
use nostr_sdk::prelude::*;
/// Publishes a text post to the network.
///
/// # Arguments
/// * `client` - The Nostr client.
/// * `content` - The text content of the post.
pub async fn post_text_note(client: &Client, content: &str) -> Result<EventId> {
// We delegate the actual protocol work to the nip01 module
nip01::publish_text(client, content).await
}

View File

@@ -1,11 +1,12 @@
pub mod nips;
pub mod functions; // Das neue Modul registrieren
pub mod functions;
pub mod nips; // Das neue Modul registrieren
use anyhow::Result;
use nostr_sdk::prelude::*;
// Wir importieren die Funktionen, um Tipparbeit zu sparen
use crate::functions::{new, messages, relays, get_contacts, create_contact};
use crate::functions::{create_contact, feed, get_contacts, messages, new, publish, relays};
use crate::nips::nip01::Post;
use crate::nips::nip17::Message;
pub struct EasyNostr {
@@ -21,7 +22,11 @@ impl EasyNostr {
}
/// Sendet eine verschlüsselte DM (NIP-17 Wrapper)
pub async fn send_private_message(&self, receiver_pubkey: &str, message: &str) -> Result<EventId> {
pub async fn send_private_message(
&self,
receiver_pubkey: &str,
message: &str,
) -> Result<EventId> {
messages::send_private_message(&self.client, receiver_pubkey, message).await
}
@@ -43,4 +48,19 @@ impl EasyNostr {
pub async fn create_contact(&self, npub: &str, nickname: Option<String>) -> Result<EventId> {
create_contact::create_contact(&self.client, npub, nickname).await
}
}
/// Veröffentlicht einen Text-Post (Kind 1)
pub async fn post_text(&self, content: &str) -> Result<EventId> {
publish::post_text_note(&self.client, content).await
}
/// Ruft den Feed der gefolgten User ab
pub async fn get_timeline(&self, followed_pubkeys: Vec<String>) -> Result<Vec<Post>> {
feed::get_followed_feed(&self.client, followed_pubkeys).await
}
/// Ruft zufällige (aktuelle) Posts ab (Global Feed)
pub async fn get_random_posts(&self) -> Result<Vec<Post>> {
feed::get_random_posts(&self.client).await
}
}

View File

@@ -1,9 +1,19 @@
use anyhow::Result;
use nostr_sdk::prelude::*;
use anyhow::Result; // <--- Hinzufügen
// Das Result hier bezieht sich jetzt auf anyhow::Result
/// A simplified structure for a Text Post (Kind 1)
/// Contains the ID, Author, content, and timestamp.
#[derive(Debug, Clone)]
pub struct Post {
pub id: EventId,
pub author: PublicKey,
pub content: String,
pub created_at: Timestamp,
}
/// Publishes a text note (Kind 1) to the connected relays.
pub async fn publish_text(client: &Client, content: &str) -> Result<EventId> {
let builder = EventBuilder::text_note(content);
let output = client.send_event_builder(builder).await?;
Ok(*output.id())
}
}

View File

@@ -1,5 +1,5 @@
use nostr_sdk::prelude::*;
use anyhow::Result;
use nostr_sdk::prelude::*;
use std::time::Duration;
/// UI Message Struktur
@@ -38,8 +38,12 @@ pub async fn get_dm_messages(client: &Client, contact_npub: &str) -> Result<Vec<
.limit(100);
// --- Abrufen: zwei einzelne fetches, dann Ergebnisse mergen ---
let mut events = client.fetch_events(filter_in, Duration::from_secs(10)).await?;
let more_events = client.fetch_events(filter_out, Duration::from_secs(10)).await?;
let mut events = client
.fetch_events(filter_in, Duration::from_secs(10))
.await?;
let more_events = client
.fetch_events(filter_out, Duration::from_secs(10))
.await?;
events.extend(more_events.into_iter());
let mut messages: Vec<Message> = Vec::new();
@@ -49,7 +53,10 @@ pub async fn get_dm_messages(client: &Client, contact_npub: &str) -> Result<Vec<
if event.kind == Kind::GiftWrap {
if let Ok(unwrapped) = client.unwrap_gift_wrap(event).await {
let rumor = unwrapped.rumor;
if rumor.pubkey == contact_pubkey && rumor.kind == Kind::TextNote {
// Allow TextNote (1) or ChatMessage (14)
if rumor.pubkey == contact_pubkey
&& (rumor.kind == Kind::TextNote || rumor.kind == Kind::from(14))
{
messages.push(Message {
id: event.id,
sender: rumor.pubkey,
@@ -63,18 +70,20 @@ pub async fn get_dm_messages(client: &Client, contact_npub: &str) -> Result<Vec<
// === NIP-04 (Legacy) Verarbeitung ===
else if event.kind == Kind::EncryptedDirectMessage {
// TagStandard::PublicKey ist ein Struct-Variant: Felder mit Struct-Syntax matchen
let has_contact_tag = event.tags.iter().any(|t| {
match t.as_standardized() {
Some(TagStandard::PublicKey { public_key, .. }) => *public_key == contact_pubkey,
_ => false,
}
let has_contact_tag = event.tags.iter().any(|t| match t.as_standardized() {
Some(TagStandard::PublicKey { public_key, .. }) => *public_key == contact_pubkey,
_ => false,
});
let is_incoming = event.pubkey == contact_pubkey;
let is_outgoing = event.pubkey == my_pubkey && has_contact_tag;
if is_incoming || is_outgoing {
let counterparty = if is_incoming { event.pubkey } else { contact_pubkey };
let counterparty = if is_incoming {
event.pubkey
} else {
contact_pubkey
};
if let Ok(content) = signer.nip04_decrypt(&counterparty, &event.content).await {
messages.push(Message {
id: event.id,