Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sdk: cleanup Client methods #608

Merged
merged 5 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@
### Breaking changes

* nostr: change `EventBuilder::gift_wrap` (and linked methods) args to take `extra_tags` instead of `expiration` ([erskingardner])
* nostr: change `EventBuilder::gift_wrap` (and linked methods) args to take an `EventBuilder` rumor instead of `UnsignedEvent` ([Yuki Kishimoto])
* nostr: change `EventBuilder::private_msg_rumor` arg to take `extra_tags` instead of `reply_to` ([Yuki Kishimoto])
* nostr: remove `tags` arg from `EventBuilder::new` ([Yuki Kishimoto])
* nostr: remove `tags` arg from `EventBuilder::text_note` ([Yuki Kishimoto])
* nostr: remove `tags` arg from `EventBuilder::long_form_text_note` ([Yuki Kishimoto])
* nostr: remove `tags` arg from `EventBuilder::job_request` ([Yuki Kishimoto])
* nostr: disable all default features except `std` ([Yuki Kishimoto])
* nostr: change `Timestamp::to_human_datetime` fingerprint ([Yuki Kishimoto])
* pool: switch from async to sync message sending for `Relay` ([Yuki Kishimoto])
Expand All @@ -51,6 +57,7 @@
* pool: rename `RelayOptions::retry_sec` to `RelayOptions::retry_interval` ([Yuki Kishimoto])
* pool: rename `RelayOptions::adjust_retry_sec` to `RelayOptions::adjust_retry_interval` ([Yuki Kishimoto])
* pool: request NIP11 document only after a successful WebSocket connection ([Yuki Kishimoto])
* sdk: cleanup `Client` methods

### Added

Expand All @@ -64,9 +71,12 @@
* nostr: add `A/a` tags in `EventBuilder::comment` (NIP22) events ([Yuki Kishimoto])
* nostr: add NIP73 support ([Yuki Kishimoto])
* nostr: add `NostrSigner::backend` ([Yuki Kishimoto])
* nostr: add `EventBuilder::private_msg` ([Yuki Kishimoto])
* nostr: add `EventBuilder::tag` and `EventBuilder::tags` ([Yuki Kishimoto])
* pool: add relay reconnection and disconnection unit tests ([Yuki Kishimoto])
* sdk: allow to specify relay pool notification channel size in `Options` ([Yuki Kishimoto])
* connect: add `NostrConnect::non_secure_set_user_public_key` ([Yuki Kishimoto])
* ffi: add `make_private_msg` func ([Yuki Kishimoto])
* book: add some examples ([RydalWater])

### Fixed
Expand All @@ -82,6 +92,7 @@

### Deprecated

* nostr: deprecate `EventBuilder::add_tags` ([Yuki Kishimoto])
* pool: deprecate `RelayPoolNotification::RelayStatus` variant ([Yuki Kishimoto])
* sdk: deprecate `Client::with_opts` ([Yuki Kishimoto])
* sdk: deprecate `Options::connection_timeout` ([Yuki Kishimoto])
Expand Down
5 changes: 3 additions & 2 deletions bindings/nostr-sdk-ffi/python/examples/bot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import asyncio
from nostr_sdk import Client, Keys, Event, UnsignedEvent, Filter, \
HandleNotification, Timestamp, UnwrappedGift, init_logger, LogLevel, Kind, KindEnum
HandleNotification, Timestamp, UnwrappedGift, init_logger, LogLevel, Kind, KindEnum, make_private_msg


async def main():
Expand Down Expand Up @@ -43,7 +43,8 @@ async def handle(self, relay_url, subscription_id, event: Event):
if rumor.kind().as_enum() == KindEnum.PRIVATE_DIRECT_MESSAGE():
msg = rumor.content()
print(f"Received new msg [sealed]: {msg}")
await client.send_private_msg(sender, f"Echo: {msg}", None)
event = await make_private_msg(keys, sender, f"Echo: {msg}")
await client.send_event(event)
else:
print(f"{rumor.as_json()}")
except Exception as e:
Expand Down
2 changes: 1 addition & 1 deletion bindings/nostr-sdk-ffi/python/examples/client-with-opts.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async def main():
keys = Keys.generate()
print(keys.public_key().to_bech32())

event = EventBuilder.text_note("Hello from rust-nostr Python bindings!", []).sign_with_keys(keys)
event = EventBuilder.text_note("Hello from rust-nostr Python bindings!").sign_with_keys(keys)
event_id = await client.send_event(event)
print("Event sent:")
print(f" hex: {event_id.to_hex()}")
Expand Down
2 changes: 1 addition & 1 deletion bindings/nostr-sdk-ffi/python/examples/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async def main():
# Mine a POW event and sign it with custom keys
custom_keys = Keys.generate()
print("Mining a POW text note...")
event = EventBuilder.text_note("Hello from rust-nostr Python bindings!", []).pow(20).sign_with_keys(custom_keys)
event = EventBuilder.text_note("Hello from rust-nostr Python bindings!").pow(20).sign_with_keys(custom_keys)
output = await client.send_event(event)
print("Event sent:")
print(f" hex: {output.id.to_hex()}")
Expand Down
5 changes: 2 additions & 3 deletions bindings/nostr-sdk-ffi/python/examples/event_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ async def main():
keys = Keys.generate()

# Build a text note
builder = EventBuilder.text_note("Note from rust-nostr python bindings", [])
builder = EventBuilder.text_note("Note from rust-nostr python bindings")
event = await builder.sign(keys)
print(event.as_json())

# Build a custom event
kind = Kind(1234)
content = "My custom content"
tags = []
builder = EventBuilder(kind, content, tags)
builder = EventBuilder(kind, content)

# Sign with generic signer
event = await builder.sign(keys)
Expand Down
2 changes: 1 addition & 1 deletion bindings/nostr-sdk-ffi/python/examples/tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# OR
tag = Tag.public_key(other_user_pk)

event = EventBuilder.text_note("New note from Rust Nostr python bindings", [tag]).sign_with_keys(keys)
event = EventBuilder.text_note("New note from Rust Nostr python bindings").tags([tag]).sign_with_keys(keys)
print(event.as_json())

print("\nTags:")
Expand Down
2 changes: 1 addition & 1 deletion bindings/nostr-sdk-ffi/python/examples/tor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async def main():
await client.add_relay("ws://2jsnlhfnelig5acq6iacydmzdbdmg7xwunm4xl6qwbvzacw4lwrjmlyd.onion")
await client.connect()

event = EventBuilder.text_note("Hello from rust-nostr Python bindings!", [])
event = EventBuilder.text_note("Hello from rust-nostr Python bindings!")
res = await client.send_event_builder(event)
print("Event sent:")
print(f" hex: {res.id.to_hex()}")
Expand Down
145 changes: 2 additions & 143 deletions bindings/nostr-sdk-ffi/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::time::Duration;

use nostr_sdk::client::Client as ClientSdk;
use nostr_sdk::pool::RelayPoolNotification as RelayPoolNotificationSdk;
use nostr_sdk::{SubscriptionId, UncheckedUrl};
use nostr_sdk::SubscriptionId;
use uniffi::Object;

mod builder;
Expand All @@ -23,11 +23,8 @@ use crate::database::events::Events;
use crate::error::Result;
use crate::pool::result::{Output, ReconciliationOutput, SendEventOutput, SubscribeOutput};
use crate::pool::RelayPool;
use crate::protocol::nips::nip59::UnwrappedGift;
use crate::protocol::signer::{NostrSigner, NostrSignerFFI2Rust, NostrSignerRust2FFI};
use crate::protocol::{
ClientMessage, Event, EventBuilder, EventId, FileMetadata, Filter, Metadata, PublicKey, Tag,
};
use crate::protocol::{ClientMessage, Event, EventBuilder, Filter, Metadata, PublicKey};
use crate::relay::options::{SubscribeAutoCloseOptions, SyncOptions};
use crate::relay::RelayFiltering;
use crate::{HandleNotification, NostrDatabase, Relay};
Expand Down Expand Up @@ -520,79 +517,6 @@ impl Client {
.into())
}

/// Send private direct message to all relays
///
/// <https://github.com/nostr-protocol/nips/blob/master/17.md>
#[uniffi::method(default(reply_to = None))]
pub async fn send_private_msg(
&self,
receiver: &PublicKey,
message: String,
reply_to: Option<Arc<EventId>>,
) -> Result<SendEventOutput> {
Ok(self
.inner
.send_private_msg(**receiver, message, reply_to.map(|t| **t))
.await?
.into())
}

/// Send private direct message to specific relays
///
/// <https://github.com/nostr-protocol/nips/blob/master/17.md>
#[uniffi::method(default(reply_to = None))]
pub async fn send_private_msg_to(
&self,
urls: Vec<String>,
receiver: &PublicKey,
message: String,
reply_to: Option<Arc<EventId>>,
) -> Result<SendEventOutput> {
Ok(self
.inner
.send_private_msg_to(urls, **receiver, message, reply_to.map(|t| **t))
.await?
.into())
}

/// Repost
pub async fn repost(
&self,
event: Arc<Event>,
relay_url: Option<String>,
) -> Result<SendEventOutput> {
Ok(self
.inner
.repost(event.as_ref().deref(), relay_url.map(UncheckedUrl::from))
.await?
.into())
}

/// Like event
///
/// <https://github.com/nostr-protocol/nips/blob/master/25.md>
pub async fn like(&self, event: Arc<Event>) -> Result<SendEventOutput> {
Ok(self.inner.like(event.as_ref().deref()).await?.into())
}

/// Disike event
///
/// <https://github.com/nostr-protocol/nips/blob/master/25.md>
pub async fn dislike(&self, event: Arc<Event>) -> Result<SendEventOutput> {
Ok(self.inner.dislike(event.as_ref().deref()).await?.into())
}

/// React to an [`Event`]
///
/// <https://github.com/nostr-protocol/nips/blob/master/25.md>
pub async fn reaction(&self, event: Arc<Event>, reaction: String) -> Result<SendEventOutput> {
Ok(self
.inner
.reaction(event.as_ref().deref(), reaction)
.await?
.into())
}

/// Send a Zap!
pub async fn zap(
&self,
Expand All @@ -606,71 +530,6 @@ impl Client {
.await?)
}

/// Construct Gift Wrap and send to relays
///
/// Check `send_event` method to know how sending events works.
///
/// <https://github.com/nostr-protocol/nips/blob/master/59.md>
pub async fn gift_wrap(
&self,
receiver: &PublicKey,
rumor: Arc<EventBuilder>,
extra_tags: Vec<Arc<Tag>>,
) -> Result<SendEventOutput> {
Ok(self
.inner
.gift_wrap(
receiver.deref(),
rumor.as_ref().deref().clone(),
extra_tags.into_iter().map(|t| t.as_ref().deref().clone()),
)
.await?
.into())
}

/// Construct Gift Wrap and send to specific relays
///
/// <https://github.com/nostr-protocol/nips/blob/master/59.md>
pub async fn gift_wrap_to(
&self,
urls: Vec<String>,
receiver: &PublicKey,
rumor: Arc<EventBuilder>,
extra_tags: Vec<Arc<Tag>>,
) -> Result<SendEventOutput> {
Ok(self
.inner
.gift_wrap_to(
urls,
receiver.deref(),
rumor.as_ref().deref().clone(),
extra_tags.into_iter().map(|t| t.as_ref().deref().clone()),
)
.await?
.into())
}

/// Unwrap Gift Wrap event
///
/// Internally verify the `seal` event
///
/// <https://github.com/nostr-protocol/nips/blob/master/59.md>
pub async fn unwrap_gift_wrap(&self, gift_wrap: &Event) -> Result<UnwrappedGift> {
Ok(self.inner.unwrap_gift_wrap(gift_wrap.deref()).await?.into())
}

pub async fn file_metadata(
&self,
description: String,
metadata: Arc<FileMetadata>,
) -> Result<SendEventOutput> {
Ok(self
.inner
.file_metadata(description, metadata.as_ref().deref().clone())
.await?
.into())
}

/// Handle notifications
pub async fn handle_notifications(&self, handler: Arc<dyn HandleNotification>) -> Result<()> {
Ok(self
Expand Down
44 changes: 16 additions & 28 deletions bindings/nostr-sdk-ffi/src/protocol/event/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,19 @@ impl EventBuilder {
async fn _none(&self) {}

#[uniffi::constructor]
pub fn new(kind: &Kind, content: &str, tags: &[Arc<Tag>]) -> Self {
let tags = tags.iter().map(|t| t.as_ref().deref().clone());
pub fn new(kind: &Kind, content: &str) -> Self {
Self {
inner: nostr::EventBuilder::new(**kind, content, tags),
inner: nostr::EventBuilder::new(**kind, content),
}
}

/// Add tags
pub fn add_tags(self: Arc<Self>, tags: &[Arc<Tag>]) -> Self {
///
/// This method extend the current tags (if any).
pub fn tags(self: Arc<Self>, tags: &[Arc<Tag>]) -> Self {
let mut builder = unwrap_or_clone_arc(self);
let tags = tags.iter().map(|t| t.as_ref().deref().clone());
builder.inner = builder.inner.add_tags(tags);
builder.inner = builder.inner.tags(tags);
builder
}

Expand Down Expand Up @@ -133,10 +134,9 @@ impl EventBuilder {
///
/// <https://github.com/nostr-protocol/nips/blob/master/01.md>
#[uniffi::constructor]
pub fn text_note(content: &str, tags: &[Arc<Tag>]) -> Self {
let tags = tags.iter().map(|t| t.as_ref().deref().clone());
pub fn text_note(content: &str) -> Self {
Self {
inner: nostr::EventBuilder::text_note(content, tags),
inner: nostr::EventBuilder::text_note(content),
}
}

Expand Down Expand Up @@ -188,10 +188,9 @@ impl EventBuilder {
///
/// <https://github.com/nostr-protocol/nips/blob/master/23.md>
#[uniffi::constructor]
pub fn long_form_text_note(content: &str, tags: &[Arc<Tag>]) -> Self {
let tags = tags.iter().map(|t| t.as_ref().deref().clone());
pub fn long_form_text_note(content: &str) -> Self {
Self {
inner: nostr::EventBuilder::long_form_text_note(content, tags),
inner: nostr::EventBuilder::long_form_text_note(content),
}
}

Expand Down Expand Up @@ -499,12 +498,9 @@ impl EventBuilder {
///
/// <https://github.com/nostr-protocol/nips/blob/master/90.md>
#[uniffi::constructor]
pub fn job_request(kind: &Kind, tags: &[Arc<Tag>]) -> Result<Self> {
pub fn job_request(kind: &Kind) -> Result<Self> {
Ok(Self {
inner: nostr::EventBuilder::job_request(
**kind,
tags.iter().map(|t| t.as_ref().deref().clone()),
)?,
inner: nostr::EventBuilder::job_request(**kind)?,
})
}

Expand Down Expand Up @@ -586,7 +582,7 @@ impl EventBuilder {
pub async fn seal(
signer: Arc<dyn NostrSigner>,
receiver_public_key: &PublicKey,
rumor: &UnsignedEvent,
rumor: &EventBuilder,
) -> Result<Self> {
let signer = NostrSignerFFI2Rust::new(signer);
Ok(Self {
Expand All @@ -607,18 +603,10 @@ impl EventBuilder {
/// </div>
///
/// <https://github.com/nostr-protocol/nips/blob/master/17.md>
#[uniffi::constructor(default(reply_to = None))]
pub fn private_msg_rumor(
receiver: &PublicKey,
message: &str,
reply_to: Option<Arc<EventId>>,
) -> Self {
#[uniffi::constructor]
pub fn private_msg_rumor(receiver: &PublicKey, message: &str) -> Self {
Self {
inner: nostr::EventBuilder::private_msg_rumor(
**receiver,
message,
reply_to.map(|id| **id),
),
inner: nostr::EventBuilder::private_msg_rumor(**receiver, message),
}
}

Expand Down
1 change: 1 addition & 0 deletions bindings/nostr-sdk-ffi/src/protocol/nips/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod nip10;
pub mod nip11;
pub mod nip13;
pub mod nip15;
pub mod nip17;
pub mod nip19;
pub mod nip21;
pub mod nip26;
Expand Down
Loading
Loading