#![allow(clippy::derive_partial_eq_without_eq)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::nonstandard_macro_braces)]
#![allow(clippy::large_enum_variant)]
#![allow(clippy::tabs_in_doc_comments)]
#![allow(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]
pub mod activity_feed;
pub mod authorized_apps;
pub mod automations;
pub mod batch_webhooks;
pub mod batches;
pub mod campaign_folders;
pub mod campaigns;
pub mod connected_sites;
pub mod conversations;
pub mod customer_journeys;
pub mod ecommerce;
pub mod facebook_ads;
pub mod file_manager;
pub mod landing_pages;
pub mod lists;
pub mod ping;
pub mod reporting;
pub mod reports;
pub mod root;
pub mod search_campaigns;
pub mod search_members;
pub mod template_folders;
pub mod templates;
#[cfg(test)]
mod tests;
pub mod types;
#[doc(hidden)]
pub mod utils;
pub mod verified_domains;
use anyhow::{anyhow, Error, Result};
pub const DEFAULT_HOST: &str = "https://us1.api.mailchimp.com";
mod progenitor_support {
use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};
const PATH_SET: &AsciiSet = &CONTROLS
.add(b' ')
.add(b'"')
.add(b'#')
.add(b'<')
.add(b'>')
.add(b'?')
.add(b'`')
.add(b'{')
.add(b'}');
#[allow(dead_code)]
pub(crate) fn encode_path(pc: &str) -> String {
utf8_percent_encode(pc, PATH_SET).to_string()
}
}
use std::convert::TryInto;
use std::env;
use std::ops::Add;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
const TOKEN_ENDPOINT: &str = "https://login.mailchimp.com/oauth2/token";
const USER_CONSENT_ENDPOINT: &str = "https://login.mailchimp.com/oauth2/authorize";
#[derive(Clone)]
pub struct Client {
host: String,
token: Arc<RwLock<InnerToken>>,
client_id: String,
client_secret: String,
redirect_uri: String,
auto_refresh: bool,
client: reqwest_middleware::ClientWithMiddleware,
}
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, JsonSchema, Clone, Default, Serialize, Deserialize)]
pub struct AccessToken {
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub token_type: String,
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub access_token: String,
#[serde(default)]
pub expires_in: i64,
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub refresh_token: String,
#[serde(default, alias = "x_refresh_token_expires_in")]
pub refresh_token_expires_in: i64,
#[serde(
default,
skip_serializing_if = "String::is_empty",
deserialize_with = "crate::utils::deserialize_null_string::deserialize"
)]
pub scope: String,
}
const REFRESH_THRESHOLD: Duration = Duration::from_secs(60);
#[derive(Debug, Clone)]
struct InnerToken {
access_token: String,
refresh_token: String,
expires_at: Option<Instant>,
}
impl Client {
pub fn new<I, K, R, T, Q>(
client_id: I,
client_secret: K,
redirect_uri: R,
token: T,
refresh_token: Q,
) -> Self
where
I: ToString,
K: ToString,
R: ToString,
T: ToString,
Q: ToString,
{
let retry_policy =
reqwest_retry::policies::ExponentialBackoff::builder().build_with_max_retries(3);
let client = reqwest::Client::builder().build();
match client {
Ok(c) => {
let client = reqwest_middleware::ClientBuilder::new(c)
.with(reqwest_tracing::TracingMiddleware::default())
.with(reqwest_conditional_middleware::ConditionalMiddleware::new(
reqwest_retry::RetryTransientMiddleware::new_with_policy(retry_policy),
|req: &reqwest::Request| req.try_clone().is_some(),
))
.build();
Client {
host: DEFAULT_HOST.to_string(),
client_id: client_id.to_string(),
client_secret: client_secret.to_string(),
redirect_uri: redirect_uri.to_string(),
token: Arc::new(RwLock::new(InnerToken {
access_token: token.to_string(),
refresh_token: refresh_token.to_string(),
expires_at: None,
})),
auto_refresh: false,
client,
}
}
Err(e) => panic!("creating reqwest client failed: {:?}", e),
}
}
pub fn set_auto_access_token_refresh(&mut self, enabled: bool) -> &mut Self {
self.auto_refresh = enabled;
self
}
pub async fn set_expires_at(&self, expires_at: Option<Instant>) -> &Self {
self.token.write().await.expires_at = expires_at;
self
}
pub async fn expires_at(&self) -> Option<Instant> {
self.token.read().await.expires_at
}
pub async fn set_expires_in(&self, expires_in: i64) -> &Self {
self.token.write().await.expires_at = Self::compute_expires_at(expires_in);
self
}
pub async fn expires_in(&self) -> Option<Duration> {
self.token
.read()
.await
.expires_at
.map(|i| i.duration_since(Instant::now()))
}
pub async fn is_expired(&self) -> Option<bool> {
self.token
.read()
.await
.expires_at
.map(|expiration| expiration <= Instant::now())
}
fn compute_expires_at(expires_in: i64) -> Option<Instant> {
let seconds_valid = expires_in
.try_into()
.ok()
.map(Duration::from_secs)
.and_then(|dur| dur.checked_sub(REFRESH_THRESHOLD))
.or_else(|| Some(Duration::from_secs(0)));
seconds_valid.map(|seconds_valid| Instant::now().add(seconds_valid))
}
pub fn with_host<H>(&self, host: H) -> Self
where
H: ToString,
{
let mut c = self.clone();
c.host = host.to_string();
c
}
pub fn new_from_env<T, R>(token: T, refresh_token: R) -> Self
where
T: ToString,
R: ToString,
{
let client_id = env::var("MAILCHIMP_CLIENT_ID").expect("must set MAILCHIMP_CLIENT_ID");
let client_secret =
env::var("MAILCHIMP_CLIENT_SECRET").expect("must set MAILCHIMP_CLIENT_SECRET");
let redirect_uri =
env::var("MAILCHIMP_REDIRECT_URI").expect("must set MAILCHIMP_REDIRECT_URI");
Client::new(client_id, client_secret, redirect_uri, token, refresh_token)
}
pub fn user_consent_url(&self, scopes: &[String]) -> String {
let state = uuid::Uuid::new_v4();
let url = format!(
"{}?client_id={}&response_type=code&redirect_uri={}&state={}",
USER_CONSENT_ENDPOINT, self.client_id, self.redirect_uri, state
);
if scopes.is_empty() {
return url;
}
format!("{}&scope={}", url, scopes.join(" "))
}
pub async fn refresh_access_token(&self) -> Result<AccessToken> {
let response = {
let refresh_token = &self.token.read().await.refresh_token;
if refresh_token.is_empty() {
anyhow!("refresh token cannot be empty");
}
let mut headers = reqwest::header::HeaderMap::new();
headers.append(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
let params = [
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
("redirect_uri", &self.redirect_uri),
];
let client = reqwest::Client::new();
client
.post(TOKEN_ENDPOINT)
.headers(headers)
.form(¶ms)
.basic_auth(&self.client_id, Some(&self.client_secret))
.send()
.await?
};
let t: AccessToken = response.json().await?;
let refresh_token = self.token.read().await.refresh_token.clone();
*self.token.write().await = InnerToken {
access_token: t.access_token.clone(),
refresh_token,
expires_at: Self::compute_expires_at(t.expires_in),
};
Ok(t)
}
pub async fn get_access_token(&mut self, code: &str, state: &str) -> Result<AccessToken> {
let mut headers = reqwest::header::HeaderMap::new();
headers.append(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
let params = [
("grant_type", "authorization_code"),
("code", code),
("client_id", &self.client_id),
("client_secret", &self.client_secret),
("redirect_uri", &self.redirect_uri),
("state", state),
];
let client = reqwest::Client::new();
let resp = client
.post(TOKEN_ENDPOINT)
.headers(headers)
.form(¶ms)
.basic_auth(&self.client_id, Some(&self.client_secret))
.send()
.await?;
let t: AccessToken = resp.json().await?;
*self.token.write().await = InnerToken {
access_token: t.access_token.clone(),
refresh_token: t.refresh_token.clone(),
expires_at: Self::compute_expires_at(t.expires_in),
};
Ok(t)
}
async fn url_and_auth(&self, uri: &str) -> Result<(reqwest::Url, Option<String>)> {
let parsed_url = uri.parse::<reqwest::Url>();
let auth = format!("Bearer {}", self.token.read().await.access_token);
parsed_url.map(|u| (u, Some(auth))).map_err(Error::from)
}
async fn make_request(
&self,
method: &reqwest::Method,
uri: &str,
body: Option<reqwest::Body>,
) -> Result<reqwest::Request> {
let u = if uri.starts_with("https://") {
uri.to_string()
} else {
(self.host.clone() + uri).to_string()
};
let (url, auth) = self.url_and_auth(&u).await?;
let instance = <&Client>::clone(&self);
let mut req = instance.client.request(method.clone(), url);
req = req.header(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
req = req.header(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_static("application/json"),
);
if let Some(auth_str) = auth {
req = req.header(http::header::AUTHORIZATION, &*auth_str);
}
if let Some(body) = body {
req = req.body(body);
}
Ok(req.build()?)
}
async fn request_raw(
&self,
method: reqwest::Method,
uri: &str,
body: Option<reqwest::Body>,
) -> Result<reqwest::Response> {
if self.auto_refresh {
let expired = self.is_expired().await;
match expired {
Some(true) => {
self.refresh_access_token().await?;
}
Some(false) => (),
None => (),
}
}
let req = self.make_request(&method, uri, body).await?;
let resp = self.client.execute(req).await?;
Ok(resp)
}
async fn request<Out>(
&self,
method: reqwest::Method,
uri: &str,
body: Option<reqwest::Body>,
) -> Result<Out>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let response = self.request_raw(method, uri, body).await?;
let status = response.status();
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")
} else {
serde_json::from_slice::<Out>(&response_body)
};
parsed_response.map_err(Error::from)
} else {
let error = if response_body.is_empty() {
anyhow!("code: {}, empty response", status)
} else {
anyhow!(
"code: {}, error: {:?}",
status,
String::from_utf8_lossy(&response_body),
)
};
Err(error)
}
}
async fn request_with_links<Out>(
&self,
method: http::Method,
uri: &str,
body: Option<reqwest::Body>,
) -> Result<(Option<hyperx::header::Link>, Out)>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let response = self.request_raw(method, uri, body).await?;
let status = response.status();
let link = response
.headers()
.get(http::header::LINK)
.and_then(|l| l.to_str().ok())
.and_then(|l| l.parse().ok());
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")
} else {
serde_json::from_slice::<Out>(&response_body)
};
parsed_response.map(|out| (link, out)).map_err(Error::from)
} else {
let error = if response_body.is_empty() {
anyhow!("code: {}, empty response", status)
} else {
anyhow!(
"code: {}, error: {:?}",
status,
String::from_utf8_lossy(&response_body),
)
};
Err(error)
}
}
#[allow(dead_code)]
async fn post_form<Out>(&self, uri: &str, form: reqwest::multipart::Form) -> Result<Out>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let u = if uri.starts_with("https://") {
uri.to_string()
} else {
(self.host.clone() + uri).to_string()
};
let (url, auth) = self.url_and_auth(&u).await?;
let instance = <&Client>::clone(&self);
let mut req = instance.client.request(http::Method::POST, url);
req = req.header(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
if let Some(auth_str) = auth {
req = req.header(http::header::AUTHORIZATION, &*auth_str);
}
req = req.multipart(form);
let response = req.send().await?;
let status = response.status();
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")
} else if std::any::TypeId::of::<Out>() == std::any::TypeId::of::<String>() {
serde_json::from_value(serde_json::json!(&String::from_utf8(
response_body.to_vec()
)?))
} else {
serde_json::from_slice::<Out>(&response_body)
};
parsed_response.map_err(Error::from)
} else {
let error = if response_body.is_empty() {
anyhow!("code: {}, empty response", status)
} else {
anyhow!(
"code: {}, error: {:?}",
status,
String::from_utf8_lossy(&response_body),
)
};
Err(error)
}
}
#[allow(dead_code)]
async fn request_with_accept_mime<Out>(
&self,
method: reqwest::Method,
uri: &str,
accept_mime_type: &str,
) -> Result<Out>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let u = if uri.starts_with("https://") {
uri.to_string()
} else {
(self.host.clone() + uri).to_string()
};
let (url, auth) = self.url_and_auth(&u).await?;
let instance = <&Client>::clone(&self);
let mut req = instance.client.request(method, url);
req = req.header(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_str(accept_mime_type)?,
);
if let Some(auth_str) = auth {
req = req.header(http::header::AUTHORIZATION, &*auth_str);
}
let response = req.send().await?;
let status = response.status();
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")
} else if std::any::TypeId::of::<Out>() == std::any::TypeId::of::<String>() {
serde_json::from_value(serde_json::json!(&String::from_utf8(
response_body.to_vec()
)?))
} else {
serde_json::from_slice::<Out>(&response_body)
};
parsed_response.map_err(Error::from)
} else {
let error = if response_body.is_empty() {
anyhow!("code: {}, empty response", status)
} else {
anyhow!(
"code: {}, error: {:?}",
status,
String::from_utf8_lossy(&response_body),
)
};
Err(error)
}
}
#[allow(dead_code)]
async fn request_with_mime<Out>(
&self,
method: reqwest::Method,
uri: &str,
content: &[u8],
mime_type: &str,
) -> Result<Out>
where
Out: serde::de::DeserializeOwned + 'static + Send,
{
let u = if uri.starts_with("https://") {
uri.to_string()
} else {
(self.host.clone() + uri).to_string()
};
let (url, auth) = self.url_and_auth(&u).await?;
let instance = <&Client>::clone(&self);
let mut req = instance.client.request(method, url);
req = req.header(
reqwest::header::ACCEPT,
reqwest::header::HeaderValue::from_static("application/json"),
);
req = req.header(
reqwest::header::CONTENT_TYPE,
reqwest::header::HeaderValue::from_bytes(mime_type.as_bytes()).unwrap(),
);
req = req.header(
reqwest::header::HeaderName::from_static("x-upload-content-type"),
reqwest::header::HeaderValue::from_static("application/octet-stream"),
);
req = req.header(
reqwest::header::HeaderName::from_static("x-upload-content-length"),
reqwest::header::HeaderValue::from_bytes(format!("{}", content.len()).as_bytes())
.unwrap(),
);
if let Some(auth_str) = auth {
req = req.header(http::header::AUTHORIZATION, &*auth_str);
}
if content.len() > 1 {
let b = bytes::Bytes::copy_from_slice(content);
req = req.body(b);
}
let response = req.send().await?;
let status = response.status();
let response_body = response.bytes().await?;
if status.is_success() {
log::debug!("Received successful response. Read payload.");
let parsed_response = if status == http::StatusCode::NO_CONTENT
|| std::any::TypeId::of::<Out>() == std::any::TypeId::of::<()>()
{
serde_json::from_str("null")
} else {
serde_json::from_slice::<Out>(&response_body)
};
parsed_response.map_err(Error::from)
} else {
let error = if response_body.is_empty() {
anyhow!("code: {}, empty response", status)
} else {
anyhow!(
"code: {}, error: {:?}",
status,
String::from_utf8_lossy(&response_body),
)
};
Err(error)
}
}
async fn request_entity<D>(
&self,
method: http::Method,
uri: &str,
body: Option<reqwest::Body>,
) -> Result<D>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
let r = self.request(method, uri, body).await?;
Ok(r)
}
#[allow(dead_code)]
async fn get<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::GET, &(self.host.to_string() + uri), message)
.await
}
#[allow(dead_code)]
async fn get_all_pages<D>(&self, uri: &str, _message: Option<reqwest::Body>) -> Result<Vec<D>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.unfold(uri).await
}
#[allow(dead_code)]
async fn unfold<D>(&self, uri: &str) -> Result<Vec<D>>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
let mut global_items = Vec::new();
let (new_link, mut items) = self.get_pages(uri).await?;
let mut link = new_link;
while !items.is_empty() {
global_items.append(&mut items);
if let Some(url) = link.as_ref().and_then(crate::utils::next_link) {
let url = reqwest::Url::parse(&url)?;
let (new_link, new_items) = self.get_pages_url(&url).await?;
link = new_link;
items = new_items;
}
}
Ok(global_items)
}
#[allow(dead_code)]
async fn get_pages<D>(&self, uri: &str) -> Result<(Option<hyperx::header::Link>, Vec<D>)>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_with_links(http::Method::GET, &(self.host.to_string() + uri), None)
.await
}
#[allow(dead_code)]
async fn get_pages_url<D>(
&self,
url: &reqwest::Url,
) -> Result<(Option<hyperx::header::Link>, Vec<D>)>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_with_links(http::Method::GET, url.as_str(), None)
.await
}
#[allow(dead_code)]
async fn post<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::POST, &(self.host.to_string() + uri), message)
.await
}
#[allow(dead_code)]
async fn patch<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::PATCH, &(self.host.to_string() + uri), message)
.await
}
#[allow(dead_code)]
async fn put<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(http::Method::PUT, &(self.host.to_string() + uri), message)
.await
}
#[allow(dead_code)]
async fn delete<D>(&self, uri: &str, message: Option<reqwest::Body>) -> Result<D>
where
D: serde::de::DeserializeOwned + 'static + Send,
{
self.request_entity(
http::Method::DELETE,
&(self.host.to_string() + uri),
message,
)
.await
}
pub fn activity_feed(&self) -> activity_feed::ActivityFeed {
activity_feed::ActivityFeed::new(self.clone())
}
pub fn authorized_apps(&self) -> authorized_apps::AuthorizedApps {
authorized_apps::AuthorizedApps::new(self.clone())
}
pub fn automations(&self) -> automations::Automations {
automations::Automations::new(self.clone())
}
pub fn batch_webhooks(&self) -> batch_webhooks::BatchWebhooks {
batch_webhooks::BatchWebhooks::new(self.clone())
}
pub fn batches(&self) -> batches::Batches {
batches::Batches::new(self.clone())
}
pub fn campaign_folders(&self) -> campaign_folders::CampaignFolders {
campaign_folders::CampaignFolders::new(self.clone())
}
pub fn campaigns(&self) -> campaigns::Campaigns {
campaigns::Campaigns::new(self.clone())
}
pub fn connected_sites(&self) -> connected_sites::ConnectedSites {
connected_sites::ConnectedSites::new(self.clone())
}
pub fn conversations(&self) -> conversations::Conversations {
conversations::Conversations::new(self.clone())
}
pub fn customer_journeys(&self) -> customer_journeys::CustomerJourneys {
customer_journeys::CustomerJourneys::new(self.clone())
}
pub fn ecommerce(&self) -> ecommerce::Ecommerce {
ecommerce::Ecommerce::new(self.clone())
}
pub fn facebook_ads(&self) -> facebook_ads::FacebookAds {
facebook_ads::FacebookAds::new(self.clone())
}
pub fn file_manager(&self) -> file_manager::FileManager {
file_manager::FileManager::new(self.clone())
}
pub fn landing_pages(&self) -> landing_pages::LandingPages {
landing_pages::LandingPages::new(self.clone())
}
pub fn lists(&self) -> lists::Lists {
lists::Lists::new(self.clone())
}
pub fn ping(&self) -> ping::Ping {
ping::Ping::new(self.clone())
}
pub fn reporting(&self) -> reporting::Reporting {
reporting::Reporting::new(self.clone())
}
pub fn reports(&self) -> reports::Reports {
reports::Reports::new(self.clone())
}
pub fn root(&self) -> root::Root {
root::Root::new(self.clone())
}
pub fn search_campaigns(&self) -> search_campaigns::SearchCampaigns {
search_campaigns::SearchCampaigns::new(self.clone())
}
pub fn search_members(&self) -> search_members::SearchMembers {
search_members::SearchMembers::new(self.clone())
}
pub fn template_folders(&self) -> template_folders::TemplateFolders {
template_folders::TemplateFolders::new(self.clone())
}
pub fn templates(&self) -> templates::Templates {
templates::Templates::new(self.clone())
}
pub fn verified_domains(&self) -> verified_domains::VerifiedDomains {
verified_domains::VerifiedDomains::new(self.clone())
}
}