use alloc::vec::Vec;
use crate::{Event, EventBuilder, Kind, RelayUrl, Tag, Tags};
#[cfg(feature = "nip44")]
use crate::nips::nip59::{self, Rumor, WrapOptions};
#[cfg(feature = "nip44")]
use crate::{EventId, Keys, PublicKey, Timestamp, UnsignedEvent};
#[cfg(feature = "nip44")]
use alloc::{borrow::ToOwned, string::String};
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("expected kind {expected}, got {found}")]
WrongKind {
expected: u16,
found: u16,
},
#[error("{0}")]
Empty(&'static str),
#[cfg(feature = "nip44")]
#[error("{0}")]
Wrap(#[from] nip59::Error),
#[cfg(feature = "nip44")]
#[error("rng failed")]
Rng,
}
pub type Result<T, E = Error> = core::result::Result<T, E>;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct DmRelayList {
relays: Vec<RelayUrl>,
}
impl DmRelayList {
#[must_use]
pub fn relays(&self) -> &[RelayUrl] {
&self.relays
}
}
impl TryFrom<&Event> for DmRelayList {
type Error = Error;
fn try_from(event: &Event) -> Result<Self> {
if event.kind() != Kind::DIRECT_MESSAGE_RELAYS_LIST {
return Err(Error::WrongKind {
expected: Kind::DIRECT_MESSAGE_RELAYS_LIST.as_u16(),
found: event.kind().as_u16(),
});
}
Ok(Self {
relays: RelayUrl::normalize_all(event.tags().iter().filter_map(|tag| {
if tag.name() == "relay" {
tag.value()
} else {
None
}
})),
})
}
}
impl From<DmRelayList> for EventBuilder {
fn from(list: DmRelayList) -> Self {
let tags: Tags = list
.relays
.iter()
.map(|url| Tag::custom("relay", [url.as_str()]))
.collect();
Self::new(Kind::DIRECT_MESSAGE_RELAYS_LIST, "").tags(tags)
}
}
impl DmRelayList {
pub fn from_urls<I, S>(relays: I) -> Result<Self>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let relays = RelayUrl::normalize_all(relays);
if relays.is_empty() {
return Err(Error::Empty("DM relay list requires at least one relay"));
}
Ok(Self { relays })
}
}
#[cfg(feature = "nip44")]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Recipient {
pub pubkey: PublicKey,
pub relay_hint: Option<RelayUrl>,
}
#[cfg(feature = "nip44")]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ReplyTo {
pub id: EventId,
pub relay_hint: Option<RelayUrl>,
}
#[cfg(feature = "nip44")]
#[derive(Clone, Debug)]
pub struct ChatMessage {
recipients: Vec<Recipient>,
content: String,
reply_to: Option<ReplyTo>,
subject: Option<String>,
}
#[cfg(feature = "nip44")]
impl ChatMessage {
#[must_use]
pub fn new<I: IntoIterator<Item = Recipient>>(
recipients: I,
content: impl Into<String>,
) -> Self {
Self {
recipients: normalize_recipients(recipients),
content: content.into(),
reply_to: None,
subject: None,
}
}
#[must_use]
pub fn reply_to(mut self, reply: ReplyTo) -> Self {
self.reply_to = Some(reply);
self
}
#[must_use]
pub fn subject(mut self, subject: impl Into<String>) -> Self {
self.subject = Some(subject.into());
self
}
pub fn into_rumor(self, sender: PublicKey, created_at: Timestamp) -> Result<Rumor> {
if self.recipients.is_empty() {
return Err(Error::Empty("recipients must not be empty"));
}
let mut tags = Vec::with_capacity(self.recipients.len() + 2);
for recipient in &self.recipients {
tags.push(Tag::public_key(
recipient.pubkey,
recipient.relay_hint.as_ref(),
None,
));
}
if let Some(reply) = &self.reply_to {
tags.push(Tag::custom(
"e",
[
reply.id.to_hex(),
reply
.relay_hint
.as_ref()
.map_or_else(String::new, |url| url.as_str().to_owned()),
],
));
}
if let Some(subject) = &self.subject {
tags.push(Tag::custom("subject", [subject.as_str()]));
}
Ok(Rumor::new(UnsignedEvent::new(
sender,
created_at,
Kind::PRIVATE_DIRECT_MESSAGE,
tags.into_iter().collect(),
self.content,
)))
}
}
#[cfg(feature = "nip44")]
pub(crate) fn normalize_recipients<I: IntoIterator<Item = Recipient>>(
recipients: I,
) -> Vec<Recipient> {
let mut out: Vec<Recipient> = Vec::new();
for recipient in recipients {
if out.iter().any(|seen| seen.pubkey == recipient.pubkey) {
continue;
}
out.push(recipient);
}
out
}
#[cfg(feature = "nip44")]
pub fn wrap_direct_message<R>(
sender: &Keys,
recipients: &[Recipient],
rumor: &Rumor,
options: &WrapOptions,
rng: &mut R,
) -> Result<Vec<(PublicKey, Event)>>
where
R: rand_core::TryCryptoRng + ?Sized,
{
let targets = wrap_targets(recipients, rumor)?;
let mut out = Vec::with_capacity(targets.len());
for target in targets {
let seal = nip59::seal(rumor, sender, &target.pubkey, options, rng)?;
let wrap = nip59::gift_wrap(
&seal,
&target.pubkey,
&options.dm_wrap(target.relay_hint),
rng,
)?;
out.push((target.pubkey, wrap));
}
Ok(out)
}
#[cfg(feature = "nip44")]
pub async fn wrap_direct_message_with_signer<R>(
signer: &dyn crate::NostrSigner,
recipients: &[Recipient],
rumor: &Rumor,
options: &WrapOptions,
rng: &mut R,
) -> Result<Vec<(PublicKey, Event)>>
where
R: rand_core::TryCryptoRng + ?Sized,
{
let targets = wrap_targets(recipients, rumor)?;
let mut out = Vec::with_capacity(targets.len());
for target in targets {
let wrap = rumor
.wrap_with_signer(
signer,
&target.pubkey,
&options.dm_wrap(target.relay_hint),
rng,
)
.await?;
out.push((target.pubkey, wrap));
}
Ok(out)
}
#[cfg(feature = "nip44")]
fn wrap_targets(recipients: &[Recipient], rumor: &Rumor) -> Result<Vec<Recipient>> {
if recipients.is_empty() {
return Err(Error::Empty("recipients must not be empty"));
}
let own = rumor.unsigned().pubkey();
let mut targets: Vec<Recipient> = Vec::with_capacity(recipients.len() + 1);
targets.push(Recipient {
pubkey: own,
relay_hint: recipients
.iter()
.find(|r| r.pubkey == own)
.and_then(|r| r.relay_hint.clone()),
});
for recipient in recipients {
if targets.iter().any(|t| t.pubkey == recipient.pubkey) {
continue;
}
targets.push(recipient.clone());
}
Ok(targets)
}