use alloc::string::{String, ToString};
use alloc::vec::Vec;
use crate::{Event, EventBuilder, Kind, RelayUrl, Tag, Tags};
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("expected kind {expected}, got {found}")]
WrongKind {
expected: u16,
found: u16,
},
}
pub type Result<T, E = Error> = core::result::Result<T, E>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RelayMarker {
Read,
Write,
Both,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct RelayListItem {
pub url: RelayUrl,
pub marker: RelayMarker,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct RelayList {
items: Vec<RelayListItem>,
}
impl RelayList {
#[must_use]
pub const fn new(items: Vec<RelayListItem>) -> Self {
Self { items }
}
#[must_use]
pub fn items(&self) -> &[RelayListItem] {
&self.items
}
pub fn read(&self) -> impl Iterator<Item = &RelayUrl> {
self.items
.iter()
.filter(|item| item.marker != RelayMarker::Write)
.map(|item| &item.url)
}
pub fn write(&self) -> impl Iterator<Item = &RelayUrl> {
self.items
.iter()
.filter(|item| item.marker != RelayMarker::Read)
.map(|item| &item.url)
}
}
impl TryFrom<&Event> for RelayList {
type Error = Error;
fn try_from(event: &Event) -> Result<Self> {
if event.kind() != Kind::RELAY_LIST {
return Err(Error::WrongKind {
expected: Kind::RELAY_LIST.as_u16(),
found: event.kind().as_u16(),
});
}
let mut items: Vec<RelayListItem> = Vec::new();
for tag in event.tags() {
if tag.name() != "r" {
continue;
}
let Some(value) = tag.value() else {
continue;
};
if value.is_empty() {
continue;
}
let Ok(url) = RelayUrl::parse(value) else {
continue;
};
if items.iter().any(|item| item.url == url) {
continue;
}
let marker = match tag.as_slice().get(2).map(String::as_str) {
Some("read") => RelayMarker::Read,
Some("write") => RelayMarker::Write,
_ => RelayMarker::Both,
};
items.push(RelayListItem { url, marker });
}
Ok(Self { items })
}
}
impl From<RelayList> for EventBuilder {
fn from(list: RelayList) -> Self {
let tags: Tags = list
.items
.iter()
.map(|item| {
let marker = match item.marker {
RelayMarker::Read => Some("read"),
RelayMarker::Write => Some("write"),
RelayMarker::Both => None,
};
Tag::reference(item.url.to_string(), marker)
})
.collect();
Self::new(Kind::RELAY_LIST, "").tags(tags)
}
}