use std::fmt;
pub const UPGRADE_URL: &str = "https://app.mailcycle.email/operator/billing";
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Api {
status: u16,
code: String,
message: String,
required_plan_id: Option<String>,
},
Decryption,
Base64Url(&'static str),
Phrase(PhraseProblem),
AuthProof(&'static str),
Unsupported(String),
}
impl Error {
pub(crate) fn api(status: u16, code: impl Into<String>, message: impl Into<String>) -> Self {
Error::Api { status, code: code.into(), message: message.into(), required_plan_id: None }
}
pub fn required_plan_id(&self) -> Option<&str> {
match self {
Error::Api { required_plan_id, .. } => required_plan_id.as_deref(),
_ => None,
}
}
pub fn upgrade_url(&self) -> Option<String> {
let Error::Api { code, required_plan_id, .. } = self else { return None };
if code != "plan_required" && code != "plan_capability_required" {
return None;
}
match required_plan_id.as_deref() {
Some(plan) if is_plan_id(plan) => Some(format!("{UPGRADE_URL}?upgrade={plan}")),
_ => Some(UPGRADE_URL.to_string()),
}
}
pub fn code(&self) -> Option<&str> {
match self {
Error::Api { code, .. } => Some(code),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Api { code, message, .. } => match self.upgrade_url() {
Some(url) => write!(f, "{code}: {message} Upgrade at {url}"),
None => write!(f, "{code}: {message}"),
},
Error::Decryption => f.write_str("This data could not be decrypted with the key provided."),
Error::Base64Url(why) => write!(f, "Not canonical base64url: {why}"),
Error::Phrase(problem) => write!(f, "{problem}"),
Error::AuthProof(why) => f.write_str(why),
Error::Unsupported(what) => f.write_str(what),
}
}
}
impl std::error::Error for Error {}
fn is_plan_id(plan: &str) -> bool {
plan.strip_prefix("plan_")
.is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_lowercase()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PhraseProblem {
Length(usize),
UnknownWord { word: String, index: usize },
Checksum,
}
impl fmt::Display for PhraseProblem {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PhraseProblem::Length(count) => {
write!(f, "A recovery phrase is twelve words; this one has {count}.")
}
PhraseProblem::UnknownWord { word, index } => {
write!(f, "Word {} is not in the list: {word:?}.", index + 1)
}
PhraseProblem::Checksum => {
f.write_str("Those twelve words do not check out; one of them is wrong.")
}
}
}
}