use crate::roster::Role;
use crate::wire::{self, Agent, Envelope};
use anyhow::{Result, anyhow, bail};
use iroh::EndpointId;
use serde_json::Value;
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Connector {
Public,
Relay(String),
Private,
}
impl FromStr for Connector {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"public" => Ok(Self::Public),
"private" => Ok(Self::Private),
url if url.starts_with("https://") || url.starts_with("http://") => Ok(Self::Relay(url.into())),
_ => bail!("connector is public, private or a relay URL"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Address {
pub agent: String,
pub computer: String,
}
impl FromStr for Address {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
let (agent, computer) = s.trim().rsplit_once('@').ok_or_else(|| anyhow!("an address is agent@computer"))?;
if agent.is_empty() || computer.is_empty() {
bail!("an address is agent@computer");
}
Ok(Self { agent: agent.into(), computer: computer.into() })
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}@{}", self.agent, self.computer)
}
}
#[derive(Clone, Debug)]
pub struct Letter {
pub id: String,
pub from: String,
pub to: Address,
pub body: String,
pub wake: bool,
pub reply_to: Option<String>,
pub hops: u8,
pub meta: Option<Value>,
}
impl Letter {
pub fn new(from: impl Into<String>, to: Address, body: impl Into<String>) -> Self {
Self {
id: wire::random_hex(12),
from: from.into(),
to,
body: body.into(),
wake: true,
reply_to: None,
hops: 0,
meta: None,
}
}
#[must_use]
pub fn notice(mut self) -> Self {
self.wake = false;
self
}
#[must_use]
pub fn reply_to(mut self, id: impl Into<String>) -> Self {
self.reply_to = Some(id.into());
self
}
#[must_use]
pub fn hops(mut self, hops: u8) -> Self {
self.hops = hops;
self
}
#[must_use]
pub fn meta(mut self, meta: Value) -> Self {
self.meta = Some(meta);
self
}
pub(crate) fn seal(self, sent_at: u64) -> Envelope {
let Self { id, from, to, body, wake, reply_to, hops, meta } = self;
Envelope { id, from, to: to.agent, body, wake, reply_to, hops, meta, sent_at }
}
}
#[derive(Clone, Debug)]
pub struct Message {
pub id: String,
pub from: Address,
pub to: String,
pub body: String,
pub wake: bool,
pub reply_to: Option<String>,
pub hops: u8,
pub meta: Option<Value>,
}
impl Envelope {
pub(crate) fn open(self, computer: String) -> Message {
let Self { id, from, to, body, wake, reply_to, hops, meta, sent_at: _ } = self;
Message { id, from: Address { agent: from, computer }, to, body, wake, reply_to, hops, meta }
}
}
#[derive(Clone, Debug)]
pub struct Peer {
pub id: EndpointId,
pub name: String,
pub role: Role,
pub me: bool,
pub online: bool,
pub agents: Vec<Agent>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Sent {
Delivered,
Queued,
}