use std::env;
use std::fmt;
use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use crate::error::{Error, Result};
use crate::http::{HttpRequest, HttpResponse, ReqwestTransport, Transport};
use crate::params;
use crate::resources::{
ApiKeys, Assets, AutomationRuns, Automations, ContactProperties, Contacts, Domains, Emails,
EventDefinitions, Events, Posts, Segments, Senders, Suppressions, Templates, Topics, Webhooks,
};
pub const DEFAULT_BASE_URL: &str = "https://api.mailtea.app";
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[derive(Clone)]
pub struct Mailtea {
pub emails: Emails,
pub contacts: Contacts,
pub posts: Posts,
pub segments: Segments,
pub senders: Senders,
pub assets: Assets,
pub suppressions: Suppressions,
pub topics: Topics,
pub templates: Templates,
pub domains: Domains,
pub webhooks: Webhooks,
pub contact_properties: ContactProperties,
pub api_keys: ApiKeys,
pub automations: Automations,
pub automation_runs: AutomationRuns,
pub events: Events,
pub event_definitions: EventDefinitions,
inner: Arc<Inner>,
}
impl Mailtea {
pub fn new(api_key: impl Into<String>) -> Self {
Self::builder()
.api_key(api_key)
.build()
.expect("an explicit API key is all `build` requires")
}
pub fn from_env() -> Result<Self> {
Self::builder().build()
}
pub fn builder() -> MailteaBuilder {
MailteaBuilder::default()
}
pub fn base_url(&self) -> &str {
&self.inner.base_url
}
pub async fn request<T: DeserializeOwned>(
&self,
method: &str,
path: &str,
body: impl Serialize,
) -> Result<T> {
self.inner.call(method, path, params::to_body(body)?).await
}
}
impl fmt::Debug for Mailtea {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Mailtea")
.field("base_url", &self.inner.base_url)
.field("api_key", &"<redacted>")
.finish()
}
}
#[derive(Default)]
pub struct MailteaBuilder {
api_key: Option<String>,
base_url: Option<String>,
transport: Option<Arc<dyn Transport>>,
}
impl fmt::Debug for MailteaBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MailteaBuilder")
.field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
.field("base_url", &self.base_url)
.field("transport", &self.transport.as_ref().map(|_| "<custom>"))
.finish()
}
}
impl MailteaBuilder {
pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
self.api_key = Some(api_key.into());
self
}
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = Some(base_url.into());
self
}
pub fn transport(mut self, transport: impl Transport + 'static) -> Self {
self.transport = Some(Arc::new(transport));
self
}
pub fn build(self) -> Result<Mailtea> {
let api_key = self
.api_key
.or_else(|| env::var("MAILTEA_API_KEY").ok())
.filter(|key| !key.is_empty())
.ok_or_else(|| {
Error::client(
"Missing Mailtea API key. Pass it to Mailtea::new(api_key) or set the \
MAILTEA_API_KEY environment variable.",
"missing_api_key",
)
})?;
let base_url = self
.base_url
.or_else(|| env::var("MAILTEA_API_BASE_URL").ok())
.filter(|url| !url.is_empty())
.unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
let inner = Arc::new(Inner {
api_key,
base_url: base_url.trim_end_matches('/').to_string(),
transport: self
.transport
.unwrap_or_else(|| Arc::new(ReqwestTransport::new())),
});
Ok(Mailtea {
emails: Emails::new(Arc::clone(&inner)),
contacts: Contacts::new(Arc::clone(&inner)),
posts: Posts::new(Arc::clone(&inner)),
segments: Segments::new(Arc::clone(&inner)),
senders: Senders::new(Arc::clone(&inner)),
assets: Assets::new(Arc::clone(&inner)),
suppressions: Suppressions::new(Arc::clone(&inner)),
topics: Topics::new(Arc::clone(&inner)),
templates: Templates::new(Arc::clone(&inner)),
domains: Domains::new(Arc::clone(&inner)),
webhooks: Webhooks::new(Arc::clone(&inner)),
contact_properties: ContactProperties::new(Arc::clone(&inner)),
api_keys: ApiKeys::new(Arc::clone(&inner)),
automations: Automations::new(Arc::clone(&inner)),
automation_runs: AutomationRuns::new(Arc::clone(&inner)),
events: Events::new(Arc::clone(&inner)),
event_definitions: EventDefinitions::new(Arc::clone(&inner)),
inner,
})
}
}
pub(crate) struct Inner {
api_key: String,
base_url: String,
transport: Arc<dyn Transport>,
}
impl fmt::Debug for Inner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Mailtea")
.field("base_url", &self.base_url)
.field("api_key", &"<redacted>")
.finish()
}
}
impl Inner {
async fn execute(
&self,
method: &str,
path: &str,
body: Option<Vec<u8>>,
extra_headers: &[(String, String)],
) -> Result<HttpResponse> {
let mut headers = vec![
(
"Authorization".to_string(),
format!("Bearer {}", self.api_key),
),
("User-Agent".to_string(), format!("mailtea-rust/{VERSION}")),
("Accept".to_string(), "application/json".to_string()),
];
if body.is_some() {
headers.push(("Content-Type".to_string(), "application/json".to_string()));
}
headers.extend_from_slice(extra_headers);
let response = self
.transport
.execute(HttpRequest {
method: method.to_string(),
url: format!("{}{path}", self.base_url),
headers,
body,
})
.await?;
if response.status >= 400 {
return Err(api_error(&response));
}
Ok(response)
}
pub(crate) async fn call<T: DeserializeOwned>(
&self,
method: &str,
path: &str,
body: Option<Vec<u8>>,
) -> Result<T> {
self.call_with_headers(method, path, body, &[]).await
}
pub(crate) async fn call_with_headers<T: DeserializeOwned>(
&self,
method: &str,
path: &str,
body: Option<Vec<u8>>,
extra_headers: &[(String, String)],
) -> Result<T> {
let response = self.execute(method, path, body, extra_headers).await?;
let text = if response.body.trim().is_empty() {
"null"
} else {
&response.body
};
serde_json::from_str(text).map_err(|error| {
Error::client(
format!("unexpected response from Mailtea: {error}"),
"invalid_response",
)
.with_source(error)
})
}
pub(crate) async fn call_text(
&self,
method: &str,
path: &str,
body: Option<Vec<u8>>,
) -> Result<String> {
Ok(self.execute(method, path, body, &[]).await?.body)
}
}
fn api_error(response: &HttpResponse) -> Error {
let request_id = response.header("x-request-id").map(str::to_string);
let mut message = format!("HTTP {}", response.status);
let mut code = None;
let mut details = None;
if let Ok(Value::Object(parsed)) = serde_json::from_str::<Value>(&response.body) {
if let Some(error) = parsed.get("error").and_then(Value::as_str) {
if !error.is_empty() {
message = error.to_string();
}
}
code = parsed
.get("code")
.and_then(Value::as_str)
.map(str::to_string);
details = parsed.get("details").cloned().filter(|d| !d.is_null());
}
Error::api(response.status, message, code, details, request_id)
}