use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde_json::{json, Map, Value};
use crate::crypto::authproof::{prove_account, DELETE_DOMAIN, DOMAIN};
use crate::crypto::cipher::{open_json, seal_json, SealedBox, SEAL_VERSION};
use crate::crypto::mnemonic::generate_phrase;
use crate::encoding::to_b64;
use crate::error::{Error, Result};
use crate::events::{EventStream, Hooks};
use crate::http::{path_segment, Http, DEFAULT_API_URL, DEFAULT_TIMEOUT_SECONDS};
use crate::keys::Keys;
use crate::mail::{open_attachment_bytes_at, to_message};
use crate::manage::{ApiKeys, Sessions, Webhooks};
use crate::models::{
Account, ActivityEntry, ActivityPage, Address, Device, Domain, Message, MessagePage, NameStyle, Plan,
SendResult, Subscription,
};
const ID_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";
const STREAM_OPEN: Duration = Duration::from_secs(10);
const CLOCK_SKEW: Duration = Duration::from_secs(5);
const MAX_ATTACHMENTS: usize = 10;
const MAX_ATTACHMENT_BYTES: usize = 7 * 1024 * 1024 / 2;
pub(crate) fn new_id(prefix: &str, length: usize) -> String {
let random = crate::crypto::primitives::random_bytes(length * 2);
let mut out = String::with_capacity(length);
for byte in random {
if out.len() == length {
break;
}
if byte < 252 {
out.push(ID_ALPHABET[(byte % 36) as usize] as char);
}
}
while out.len() < length {
let extra = crate::crypto::primitives::random_bytes(1)[0];
if extra < 252 {
out.push(ID_ALPHABET[(extra % 36) as usize] as char);
}
}
format!("{prefix}_{out}")
}
pub(crate) fn vault_aad(kind: &str, id: &str) -> String {
format!("mailcycle/v1/{kind}:{id}")
}
pub(crate) fn open_vault_record(vault_key: &[u8], kind: &str, id: &str, box_: &SealedBox) -> Result<Value> {
match open_json::<Value>(vault_key, box_, &vault_aad(kind, id)) {
Ok(value) => Ok(value),
Err(_) => open_json(vault_key, box_, id),
}
}
pub(crate) fn is_sealed_box(value: Option<&Value>) -> bool {
value.is_some_and(|v| v.get("c").is_some() && v.get("epk").is_none())
}
pub struct Options {
pub api_url: String,
pub passphrase: String,
pub timeout_seconds: u64,
}
impl Default for Options {
fn default() -> Self {
Options {
api_url: DEFAULT_API_URL.into(),
passphrase: String::new(),
timeout_seconds: DEFAULT_TIMEOUT_SECONDS,
}
}
}
#[derive(Default)]
pub struct NewAddress {
pub domain: Option<String>,
pub prefix: Option<String>,
pub local_part: Option<String>,
pub style: Option<NameStyle>,
pub label: Option<String>,
pub retention_days: Option<u32>,
}
pub struct Outgoing<'a> {
pub from: &'a str,
pub to: &'a str,
pub subject: &'a str,
pub text: &'a str,
pub html: Option<&'a str>,
pub from_name: Option<&'a str>,
pub reply_to: Option<&'a Message>,
pub attachments: &'a [OutgoingAttachment<'a>],
}
impl<'a> Outgoing<'a> {
pub fn new(from: &'a str, to: &'a str, subject: &'a str, text: &'a str) -> Self {
Outgoing { from, to, subject, text, html: None, from_name: None, reply_to: None, attachments: &[] }
}
}
pub struct OutgoingAttachment<'a> {
pub filename: &'a str,
pub content: &'a [u8],
pub mime_type: Option<&'a str>,
pub content_id: Option<&'a str>,
}
impl<'a> OutgoingAttachment<'a> {
pub fn new(filename: &'a str, content: &'a [u8]) -> Self {
OutgoingAttachment { filename, content, mime_type: None, content_id: None }
}
}
fn attachments_body(attachments: &[OutgoingAttachment<'_>]) -> Result<Value> {
if attachments.len() > MAX_ATTACHMENTS {
return Err(Error::api(
0,
"too_many_attachments",
format!("A message can have at most {MAX_ATTACHMENTS} attachments."),
));
}
if attachments.iter().map(|a| a.content.len()).sum::<usize>() > MAX_ATTACHMENT_BYTES {
return Err(Error::api(0, "attachments_too_large", "Attachments can add up to 3.5 MB per message."));
}
let items = attachments
.iter()
.map(|a| {
let mut item = Map::new();
item.insert("filename".into(), json!(a.filename));
item.insert("content".into(), json!(to_b64(a.content)));
if let Some(mime_type) = a.mime_type {
item.insert("mimeType".into(), json!(mime_type));
}
if let Some(content_id) = a.content_id {
item.insert("contentId".into(), json!(content_id));
}
Value::Object(item)
})
.collect();
Ok(Value::Array(items))
}
pub struct WaitFor<'a> {
pub address_id: Option<&'a str>,
pub from: Option<&'a str>,
pub subject: Option<&'a str>,
pub timeout: Duration,
pub poll_every: Duration,
pub stream_open: Duration,
pub since: Option<SystemTime>,
}
impl Default for WaitFor<'_> {
fn default() -> Self {
WaitFor {
address_id: None,
from: None,
subject: None,
timeout: Duration::from_secs(60),
poll_every: Duration::from_secs(5),
stream_open: STREAM_OPEN,
since: None,
}
}
}
pub struct Mailcycle {
pub(crate) http: Http,
pub(crate) keys: Option<Keys>,
api_key: bool,
}
impl Mailcycle {
pub fn generate_phrase() -> String {
generate_phrase().join(" ")
}
pub fn sign_in(phrase: &str, options: Options) -> Result<Self> {
let keys = Keys::from_phrase(phrase, &options.passphrase)?;
let mut http = Http::new(&options.api_url, None, options.timeout_seconds);
let challenge: Value = http.request(
"POST",
"/accounts/challenge",
Some(&json!({ "accountId": keys.account_id() })),
&[],
)?;
let nonce = challenge["nonce"].as_str().unwrap_or_default();
let challenge_key = challenge["challengeKey"].as_str().unwrap_or_default();
let proof = prove_account(keys.auth_key(), challenge_key, nonce, keys.account_id(), DOMAIN)?;
let session: Value = http.request(
"POST",
"/accounts/verify",
Some(&json!({ "accountId": keys.account_id(), "nonce": nonce, "proof": proof })),
&[],
)?;
http.set_token(session["token"].as_str().map(str::to_string));
Ok(Mailcycle { http, keys: Some(keys), api_key: false })
}
pub fn resume(session_token: &str, phrase: &str, options: Options) -> Result<Self> {
let keys = Keys::from_phrase(phrase, &options.passphrase)?;
let http = Http::new(&options.api_url, Some(session_token.to_string()), options.timeout_seconds);
let client = Mailcycle { http, keys: Some(keys), api_key: false };
client.check_phrase_matches("session")?;
Ok(client)
}
pub fn with_api_key(api_key: &str, phrase: Option<&str>, options: Options) -> Result<Self> {
let keys = phrase.map(|p| Keys::from_phrase(p, &options.passphrase)).transpose()?;
let http = Http::new(&options.api_url, Some(api_key.to_string()), options.timeout_seconds);
let client = Mailcycle { http, keys, api_key: true };
if client.keys.is_some() {
client.check_phrase_matches("API key")?;
}
Ok(client)
}
pub fn create_account(phrase: Option<&str>, options: Options) -> Result<(Self, String)> {
let words = phrase.map(str::to_string).unwrap_or_else(Self::generate_phrase);
let keys = Keys::from_phrase(&words, &options.passphrase)?;
let mut http = Http::new(&options.api_url, None, options.timeout_seconds);
let session: Value = http.request(
"POST",
"/accounts",
Some(&json!({
"accountId": keys.account_id(),
"authVerifier": keys.auth_verifier(),
"authPublicKey": keys.auth_public_key(),
})),
&[],
)?;
http.set_token(session["token"].as_str().map(str::to_string));
Ok((Mailcycle { http, keys: Some(keys), api_key: false }, words))
}
fn check_phrase_matches(&self, what: &str) -> Result<()> {
let keys = self.keys.as_ref().expect("checked by the caller");
if self.account()?.id != keys.account_id() {
return Err(Error::Unsupported(format!(
"That phrase belongs to a different account from the {what}."
)));
}
Ok(())
}
pub fn account_id(&self) -> Option<&str> {
self.keys.as_ref().map(Keys::account_id)
}
pub fn session_token(&self) -> Option<&str> {
self.http.token()
}
pub fn can_decrypt(&self) -> bool {
self.keys.is_some()
}
pub fn account(&self) -> Result<Account> {
let result: Value = self.http.request("GET", "/accounts/me", None, &[])?;
let operator = &result["operator"];
Ok(Account {
id: operator["id"].as_str().unwrap_or_default().to_string(),
plan_id: operator["planId"].as_str().unwrap_or_default().to_string(),
created_at: operator["createdAt"].as_str().unwrap_or_default().to_string(),
plan: serde_json::from_value(result["plan"].clone()).unwrap_or(Plan {
id: String::new(),
name: String::new(),
extra: Default::default(),
}),
})
}
pub fn activity(&self, limit: u32) -> Result<Vec<ActivityEntry>> {
Ok(self.activity_page(Some(limit), None)?.activity)
}
pub fn activity_page(&self, limit: Option<u32>, cursor: Option<&str>) -> Result<ActivityPage> {
let mut query: Vec<(&str, String)> = Vec::new();
if let Some(limit) = limit {
query.push(("limit", limit.to_string()));
}
if let Some(cursor) = cursor {
query.push(("cursor", cursor.to_string()));
}
let result: Value = self.http.request("GET", "/activity", None, &query)?;
Ok(ActivityPage {
activity: serde_json::from_value(result["activity"].clone()).unwrap_or_default(),
next_cursor: result["nextCursor"].as_str().map(str::to_string),
})
}
pub fn all_activity(&self) -> Result<Vec<ActivityEntry>> {
let mut out = Vec::new();
let mut cursor: Option<String> = None;
loop {
let page = self.activity_page(Some(200), cursor.as_deref())?;
out.extend(page.activity);
match page.next_cursor {
Some(next) => cursor = Some(next),
None => return Ok(out),
}
}
}
pub fn usage(&self) -> Result<Value> {
self.http.request("GET", "/usage", None, &[])
}
pub fn sign_out(&mut self) -> Result<()> {
if self.api_key {
return Ok(());
}
let _: Value = self.http.request("POST", "/accounts/signout", Some(&json!({})), &[])?;
self.http.set_token(None);
Ok(())
}
pub fn delete_account(&mut self) -> Result<()> {
let mut body = None;
if let (Some(keys), false) = (&self.keys, self.api_key) {
let challenge: Value = self.http.request(
"POST",
"/accounts/challenge",
Some(&json!({ "accountId": keys.account_id() })),
&[],
)?;
let nonce = challenge["nonce"].as_str().unwrap_or_default();
let challenge_key = challenge["challengeKey"].as_str().unwrap_or_default();
let proof =
prove_account(keys.auth_key(), challenge_key, nonce, keys.account_id(), DELETE_DOMAIN)?;
body = Some(json!({ "nonce": nonce, "proof": proof }));
}
let _: Value = self.http.request("DELETE", "/accounts/me", body.as_ref(), &[])?;
self.http.set_token(None);
Ok(())
}
pub fn subscription(&self) -> Result<Subscription> {
let result: Value = self.http.request("GET", "/subscription", None, &[])?;
let subscription = &result["subscription"];
let text = |key: &str| subscription[key].as_str().unwrap_or_default().to_string();
Ok(Subscription {
id: text("id"),
plan_id: text("planId"),
status: text("status"),
renewal_date: text("renewalDate"),
pending_plan_id: subscription["pendingPlanId"].as_str().map(str::to_string),
balance_minor: result["balanceMinor"].as_i64().unwrap_or(0),
pause: Some(result["pause"].clone()).filter(|value| !value.is_null()),
})
}
pub fn plans(&self) -> Result<Vec<Plan>> {
let result: Value = self.http.request("GET", "/plans", None, &[])?;
Ok(serde_json::from_value(result["plans"].clone()).unwrap_or_default())
}
pub fn addresses(&self) -> Addresses<'_> {
Addresses { client: self }
}
pub fn messages(&self) -> Messages<'_> {
Messages { client: self }
}
pub fn devices(&self) -> Devices<'_> {
Devices { client: self }
}
pub fn domains(&self) -> Domains<'_> {
Domains { client: self }
}
pub fn events(&self) -> Events<'_> {
Events { client: self }
}
pub fn api_keys(&self) -> ApiKeys<'_> {
ApiKeys { client: self }
}
pub fn webhooks(&self) -> Webhooks<'_> {
Webhooks { client: self }
}
pub fn sessions(&self) -> Sessions<'_> {
Sessions { client: self }
}
pub(crate) fn require_keys(&self, what: &str) -> Result<&Keys> {
self.keys.as_ref().ok_or_else(|| {
Error::Unsupported(format!(
"The recovery phrase is needed to {what}. Pass it when building the client."
))
})
}
}
pub struct Addresses<'a> {
client: &'a Mailcycle,
}
impl Addresses<'_> {
fn to_address(&self, wire: &Value) -> Address {
let id = wire["id"].as_str().unwrap_or_default().to_string();
let mut meta = Value::Null;
if let (Some(keys), true) = (self.client.keys.as_ref(), is_sealed_box(wire.get("meta"))) {
if let Ok(box_) = serde_json::from_value::<SealedBox>(wire["meta"].clone()) {
meta = open_vault_record(keys.vault_key(), "inbox", &id, &box_).unwrap_or(Value::Null);
}
}
let text = |field: &str| meta[field].as_str().filter(|text| !text.is_empty()).map(str::to_string);
let (label, sender_name) = (text("label"), text("senderName"));
Address {
id,
email_address: wire["emailAddress"].as_str().unwrap_or_default().to_string(),
status: wire["status"].as_str().unwrap_or_default().to_string(),
created_at: wire["createdAt"].as_str().unwrap_or_default().to_string(),
retention_days: wire["retentionDays"].as_u64().unwrap_or(0) as u32,
assigned_worker_id: wire["assignedWorkerId"].as_str().map(str::to_string),
paused_at: wire["pausedAt"].as_str().map(str::to_string),
label,
sender_name,
receives: wire["receives"].as_bool().unwrap_or(true),
}
}
fn default_domain(&self) -> Result<String> {
self.client
.domains()
.list()?
.into_iter()
.next()
.map(|domain| domain.domain)
.ok_or_else(|| Error::Unsupported("The account has no domain to create addresses on.".into()))
}
pub fn list(&self) -> Result<Vec<Address>> {
let result: Value = self.client.http.request("GET", "/inboxes", None, &[])?;
Ok(result["inboxes"]
.as_array()
.map(|items| items.iter().map(|item| self.to_address(item)).collect())
.unwrap_or_default())
}
pub fn roll_names(&self, style: NameStyle, domain: Option<&str>) -> Result<Vec<String>> {
let domain = match domain {
Some(domain) => domain.to_string(),
None => self.default_domain()?,
};
let query = [("style", style.as_str().to_string()), ("domain", domain)];
let result: Value = self.client.http.request("GET", "/inboxes/names", None, &query)?;
Ok(result["names"]
.as_array()
.map(|items| items.iter().filter_map(Value::as_str).map(str::to_string).collect())
.unwrap_or_default())
}
pub fn create(&self, wanted: NewAddress) -> Result<Address> {
let keys = self.client.require_keys("create an address that receives mail")?;
let id = new_id("ibx", 12);
let domain = match wanted.domain {
Some(domain) => domain,
None => self.default_domain()?,
};
let meta = match &wanted.label {
Some(label) => seal_json(
keys.vault_key(),
&json!({ "label": label }),
&vault_aad("inbox", &id),
SEAL_VERSION,
)?,
None => seal_json(keys.vault_key(), &json!({}), &vault_aad("inbox", &id), SEAL_VERSION)?,
};
let mut body = Map::new();
body.insert("id".into(), json!(id));
body.insert("domain".into(), json!(domain));
body.insert("meta".into(), serde_json::to_value(&meta).unwrap());
body.insert("publicKey".into(), json!(keys.address_public_key(&id)?));
if let Some(local_part) = &wanted.local_part {
body.insert("localPart".into(), json!(local_part));
} else if let Some(prefix) = &wanted.prefix {
body.insert("prefix".into(), json!(prefix));
} else if let Some(style) = wanted.style {
body.insert("style".into(), json!(style.as_str()));
}
if let Some(days) = wanted.retention_days {
body.insert("retentionDays".into(), json!(days));
}
let result: Value = self.client.http.request("POST", "/inboxes", Some(&Value::Object(body)), &[])?;
Ok(self.to_address(&result["inbox"]))
}
pub fn update(
&self,
address_id: &str,
label: Option<Option<&str>>,
retention_days: Option<u32>,
) -> Result<Address> {
let mut body = Map::new();
if let Some(days) = retention_days {
body.insert("retentionDays".into(), json!(days));
}
if let Some(wanted) = label {
let keys = self.client.require_keys("change a label")?;
let value = match wanted.filter(|text| !text.is_empty()) {
Some(text) => json!({ "label": text }),
None => json!({}),
};
let box_ = seal_json(keys.vault_key(), &value, &vault_aad("inbox", address_id), SEAL_VERSION)?;
body.insert("meta".into(), serde_json::to_value(&box_).unwrap());
}
let path = format!("/inboxes/{}", path_segment(address_id));
let result: Value = self.client.http.request("PATCH", &path, Some(&Value::Object(body)), &[])?;
Ok(self.to_address(&result["inbox"]))
}
pub fn delete(&self, address_id: &str) -> Result<()> {
let path = format!("/inboxes/{}", path_segment(address_id));
let _: Value = self.client.http.request("DELETE", &path, None, &[])?;
Ok(())
}
pub fn allocation(&self) -> Result<Value> {
self.client.http.request("GET", "/inboxes/allocation", None, &[])
}
}
pub struct Messages<'a> {
client: &'a Mailcycle,
}
impl Messages<'_> {
pub fn list(
&self,
address_id: &str,
folder: Option<&str>,
limit: Option<u32>,
cursor: Option<&str>,
) -> Result<MessagePage> {
let mut query: Vec<(&str, String)> = Vec::new();
if let Some(folder) = folder {
query.push(("folder", folder.to_string()));
}
if let Some(limit) = limit {
query.push(("limit", limit.to_string()));
}
if let Some(cursor) = cursor {
query.push(("cursor", cursor.to_string()));
}
let path = format!("/inboxes/{}/messages", path_segment(address_id));
let result: Value = self.client.http.request("GET", &path, None, &query)?;
Ok(MessagePage {
messages: result["messages"]
.as_array()
.map(|items| items.iter().map(|item| to_message(self.client.keys.as_ref(), item)).collect())
.unwrap_or_default(),
next_cursor: result["nextCursor"].as_str().map(str::to_string),
})
}
pub fn all(&self, address_id: &str, folder: Option<&str>) -> Result<Vec<Message>> {
let mut out = Vec::new();
let mut cursor: Option<String> = None;
loop {
let page = self.list(address_id, folder, Some(100), cursor.as_deref())?;
out.extend(page.messages);
match page.next_cursor {
Some(next) => cursor = Some(next),
None => return Ok(out),
}
}
}
pub fn get(&self, message_id: &str) -> Result<Message> {
let path = format!("/messages/{}", path_segment(message_id));
let result: Value = self.client.http.request("GET", &path, None, &[])?;
Ok(to_message(self.client.keys.as_ref(), &result["message"]))
}
pub fn attachment(&self, message: &Message, index: usize) -> Result<Vec<u8>> {
let keys = self.client.require_keys("open an attachment")?;
let path = format!("/messages/{}/attachments/{index}", path_segment(&message.id));
let data = self.client.http.request_bytes("GET", &path)?;
open_attachment_bytes_at(keys, &message.address_id, &message.id, index, message.key_epoch, &data)
}
pub fn mark_read(&self, message_id: &str, read: bool) -> Result<()> {
let path = format!("/messages/{}/read", path_segment(message_id));
let _: Value = self.client.http.request("POST", &path, Some(&json!({ "read": read })), &[])?;
Ok(())
}
pub fn star(&self, message_id: &str, starred: bool) -> Result<()> {
let path = format!("/messages/{}/star", path_segment(message_id));
let _: Value = self.client.http.request("POST", &path, Some(&json!({ "starred": starred })), &[])?;
Ok(())
}
pub fn move_to(&self, message_id: &str, folder: &str) -> Result<()> {
let path = format!("/messages/{}/move", path_segment(message_id));
let _: Value = self.client.http.request("POST", &path, Some(&json!({ "folder": folder })), &[])?;
Ok(())
}
pub fn delete(&self, message_id: &str) -> Result<()> {
let path = format!("/messages/{}", path_segment(message_id));
let _: Value = self.client.http.request("DELETE", &path, None, &[])?;
Ok(())
}
pub fn empty_trash(&self) -> Result<u64> {
let result: Value =
self.client.http.request("POST", "/messages/empty-trash", Some(&json!({})), &[])?;
Ok(result["deleted"].as_u64().unwrap_or(0))
}
pub fn send(&self, outgoing: Outgoing<'_>) -> Result<SendResult> {
let mut body = Map::new();
body.insert("from".into(), json!(outgoing.from));
body.insert("to".into(), json!(outgoing.to));
body.insert("subject".into(), json!(outgoing.subject));
body.insert("text".into(), json!(outgoing.text));
if let Some(html) = outgoing.html {
body.insert("html".into(), json!(html));
}
if let Some(name) = outgoing.from_name {
body.insert("fromName".into(), json!(name));
}
if let Some(original) = outgoing.reply_to {
body.insert("inReplyTo".into(), json!(original.id));
if !original.message_id.is_empty() {
body.insert("inReplyToHeader".into(), json!(original.message_id));
}
}
if !outgoing.attachments.is_empty() {
body.insert("attachments".into(), attachments_body(outgoing.attachments)?);
}
let result: Value =
self.client.http.request("POST", "/messages/send", Some(&Value::Object(body)), &[])?;
Ok(SendResult {
message_id: result["messageId"].as_str().unwrap_or_default().to_string(),
sent_copy_id: result["sentCopyId"].as_str().map(str::to_string),
})
}
pub fn wait_for(&self, mut wanted: WaitFor<'_>) -> Result<Message> {
wanted.since.get_or_insert_with(SystemTime::now);
let deadline = Instant::now() + wanted.timeout;
if let Some(found) = self.wait_on_stream(&wanted, deadline)? {
return Ok(found);
}
if Instant::now() >= deadline {
return Err(Error::api(0, "timeout", "No matching mail arrived in time."));
}
self.wait_by_polling(&wanted, deadline)
}
fn matches(&self, wanted: &WaitFor<'_>, message: &Message) -> bool {
if wanted.address_id.is_some_and(|id| message.address_id != id) {
return false;
}
if let Some(from) = wanted.from {
let haystack = format!("{} {}", message.from_name, message.from_address).to_lowercase();
if !haystack.contains(&from.to_lowercase()) {
return false;
}
}
if let Some(subject) = wanted.subject {
if !message.subject.to_lowercase().contains(&subject.to_lowercase()) {
return false;
}
}
true
}
fn fresh_match(&self, wanted: &WaitFor<'_>, message: &Message) -> bool {
received_since(message, wanted.since.unwrap_or_else(SystemTime::now)) && self.matches(wanted, message)
}
fn wait_on_stream(&self, wanted: &WaitFor<'_>, deadline: Instant) -> Result<Option<Message>> {
let Ok(stream) = self.client.events().stream() else { return Ok(None) };
let opening = wanted.stream_open.min(deadline.saturating_duration_since(Instant::now()));
if !stream.wait_until_open(opening) || stream.ended() {
return Ok(None);
}
if let Some(address_id) = wanted.address_id {
if let Ok(page) = self.list(address_id, None, Some(50), None) {
if let Some(found) = page.messages.into_iter().find(|m| self.fresh_match(wanted, m)) {
return Ok(Some(found));
}
}
}
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Ok(None);
}
let Some(event) = stream.next_event(Some(remaining)) else {
return Ok(None);
};
if event.event_type != "message.received" {
continue;
}
if let Some(id) = wanted.address_id {
if event.payload.get("inboxId").and_then(Value::as_str) != Some(id) {
continue;
}
}
let message_id = event.payload.get("messageId").and_then(Value::as_str).unwrap_or_default();
match self.get(message_id) {
Ok(message) if self.matches(wanted, &message) => return Ok(Some(message)),
Ok(_) | Err(_) => continue,
}
}
}
fn wait_by_polling(&self, wanted: &WaitFor<'_>, deadline: Instant) -> Result<Message> {
let Some(address_id) = wanted.address_id else {
return Err(Error::Unsupported(
"The event stream is not available here. Pass address_id to wait by polling instead.".into(),
));
};
let first = self.list(address_id, None, Some(50), None)?.messages;
if let Some(found) = first.iter().find(|m| self.fresh_match(wanted, m)) {
return Ok(found.clone());
}
let mut newest: Option<String> = first.first().map(|m| format!("{}~{}", m.received_at, m.id));
loop {
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
return Err(Error::api(0, "timeout", "No matching mail arrived in time."));
}
std::thread::sleep(wanted.poll_every.min(remaining));
let mut query = vec![
("inboxIds", address_id.to_string()),
("folder", "inbox".to_string()),
("limit", "50".to_string()),
];
if let Some(marker) = &newest {
query.push(("newer", marker.clone()));
}
let result: Value = self.client.http.request("GET", "/messages", None, &query)?;
let arrived: Vec<Message> = result["messages"]
.as_array()
.map(|items| items.iter().map(|item| to_message(self.client.keys.as_ref(), item)).collect())
.unwrap_or_default();
let Some(top) = arrived.first() else { continue };
newest = Some(format!("{}~{}", top.received_at, top.id));
if let Some(found) = arrived.into_iter().rev().find(|m| self.matches(wanted, m)) {
return Ok(found);
}
}
}
}
fn received_since(message: &Message, since: SystemTime) -> bool {
let Some(received) = parse_rfc3339_nanos(&message.received_at) else { return false };
received >= unix_nanos(since) - CLOCK_SKEW.as_nanos() as i128
}
fn unix_nanos(time: SystemTime) -> i128 {
match time.duration_since(UNIX_EPOCH) {
Ok(after) => after.as_nanos() as i128,
Err(before) => -(before.duration().as_nanos() as i128),
}
}
fn parse_rfc3339_nanos(text: &str) -> Option<i128> {
let bytes = text.as_bytes();
let number = |range: std::ops::Range<usize>| -> Option<i64> {
let part = text.get(range)?;
part.bytes().all(|b| b.is_ascii_digit()).then(|| part.parse().ok())?
};
if bytes.len() < 20 || bytes[4] != b'-' || bytes[7] != b'-' || bytes[13] != b':' || bytes[16] != b':' {
return None;
}
if !matches!(bytes[10], b'T' | b't' | b' ') {
return None;
}
let (year, month, day) = (number(0..4)?, number(5..7)?, number(8..10)?);
let (hour, minute, second) = (number(11..13)?, number(14..16)?, number(17..19)?);
if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || minute > 59 || second > 60 {
return None;
}
let mut rest = &text[19..];
let mut nanos: i128 = 0;
if let Some(fraction) = rest.strip_prefix('.') {
let digits = fraction.bytes().take_while(u8::is_ascii_digit).count();
if digits == 0 {
return None;
}
let kept = &fraction[..digits.min(9)];
nanos = kept.parse::<i128>().ok()? * 10i128.pow(9 - kept.len() as u32);
rest = &fraction[digits..];
}
let offset_seconds: i64 = match rest {
"Z" | "z" => 0,
_ => {
let sign = match rest.as_bytes().first()? {
b'+' => 1,
b'-' => -1,
_ => return None,
};
if rest.len() != 6 || rest.as_bytes()[3] != b':' {
return None;
}
let (h, m) = (rest[1..3].parse::<i64>().ok()?, rest[4..6].parse::<i64>().ok()?);
sign * (h * 3600 + m * 60)
}
};
let y = if month <= 2 { year - 1 } else { year };
let era = y.div_euclid(400);
let yoe = y - era * 400;
let mp = (month + 9) % 12;
let doy = (153 * mp + 2) / 5 + day - 1;
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
let days = era * 146_097 + doe - 719_468;
let seconds = days * 86_400 + hour * 3600 + minute * 60 + second - offset_seconds;
Some(i128::from(seconds) * 1_000_000_000 + nanos)
}
pub struct Devices<'a> {
pub(crate) client: &'a Mailcycle,
}
impl Devices<'_> {
pub(crate) fn to_device(&self, wire: &Value) -> Device {
let id = wire["id"].as_str().unwrap_or_default().to_string();
let mut profile = Value::Null;
if let (Some(keys), true) = (self.client.keys.as_ref(), is_sealed_box(wire.get("profile"))) {
if let Ok(box_) = serde_json::from_value::<SealedBox>(wire["profile"].clone()) {
profile = open_vault_record(keys.vault_key(), "worker", &id, &box_).unwrap_or(Value::Null);
}
}
Device {
id,
platform: wire["platform"].as_str().unwrap_or_default().to_string(),
kind: wire["kind"].as_str().unwrap_or("device").to_string(),
send_mode: wire["sendMode"].as_str().unwrap_or("full").to_string(),
status: wire["status"].as_str().unwrap_or_default().to_string(),
created_at: wire["createdAt"].as_str().unwrap_or_default().to_string(),
last_active_at: wire["lastActiveAt"].as_str().map(str::to_string),
paused_at: wire["pausedAt"].as_str().map(str::to_string),
name: profile.get("name").and_then(Value::as_str).map(str::to_string),
tags: profile
.get("tags")
.and_then(Value::as_array)
.map(|items| items.iter().filter_map(Value::as_str).map(str::to_string).collect())
.unwrap_or_default(),
}
}
pub fn list(&self) -> Result<Vec<Device>> {
let mut out = Vec::new();
let mut cursor: Option<String> = None;
loop {
let mut query = vec![("limit", "200".to_string())];
if let Some(value) = &cursor {
query.push(("cursor", value.clone()));
}
let page: Value = self.client.http.request("GET", "/workers", None, &query)?;
if let Some(items) = page["workers"].as_array() {
out.extend(items.iter().map(|item| self.to_device(item)));
}
match page["nextCursor"].as_str() {
Some(next) => cursor = Some(next.to_string()),
None => return Ok(out),
}
}
}
pub fn get(&self, device_id: &str) -> Result<Device> {
let path = format!("/workers/{}", path_segment(device_id));
let result: Value = self.client.http.request("GET", &path, None, &[])?;
Ok(self.to_device(&result["worker"]))
}
}
pub struct Domains<'a> {
client: &'a Mailcycle,
}
impl Domains<'_> {
pub fn list(&self) -> Result<Vec<Domain>> {
let result: Value = self.client.http.request("GET", "/domains", None, &[])?;
Ok(serde_json::from_value(result["domains"].clone()).unwrap_or_default())
}
}
pub struct Events<'a> {
client: &'a Mailcycle,
}
impl Events<'_> {
pub fn stream(&self) -> Result<EventStream> {
self.stream_with(Hooks::default())
}
pub fn stream_with(&self, hooks: Hooks) -> Result<EventStream> {
let token = self.client.http.token().ok_or_else(|| Error::Unsupported("Sign in first.".into()))?;
EventStream::open(self.client.http.base_url(), token, hooks)
}
}
#[cfg(test)]
mod tests {
use super::parse_rfc3339_nanos;
#[test]
fn reads_the_times_the_api_writes() {
assert_eq!(parse_rfc3339_nanos("1970-01-01T00:00:00Z"), Some(0));
assert_eq!(parse_rfc3339_nanos("1970-01-01T00:00:01.5Z"), Some(1_500_000_000));
assert_eq!(parse_rfc3339_nanos("2026-09-20T10:00:00.000Z"), Some(1_789_898_400_000_000_000));
assert_eq!(parse_rfc3339_nanos("2026-09-20T12:00:00.000+02:00"), Some(1_789_898_400_000_000_000));
assert_eq!(parse_rfc3339_nanos("2026-09-20T10:00:00.123456789123Z"), Some(1_789_898_400_123_456_789));
assert_eq!(parse_rfc3339_nanos("2000-02-29T00:00:00Z"), Some(951_782_400_000_000_000));
for bad in ["", "2026-09-20", "2026-09-20T10:00:00", "2026-13-20T10:00:00Z", "yesterday"] {
assert_eq!(parse_rfc3339_nanos(bad), None, "{bad}");
}
}
}