use std::collections::HashMap;
use serde_json::{json, Map, Value};
use crate::utility::{encode_path_segment, ZBError, ZBResult};
use crate::ZeroBounce;
const TEST_TYPES: [u8; 3] = [1, 2, 3];
const TEST_STATUSES: [&str; 2] = ["running", "finished"];
#[derive(Clone, Debug)]
pub struct InboxPlacementProviderSelection {
pub id: i64,
pub max_seeds: Option<i64>,
}
#[derive(Clone, Debug, Default)]
pub struct CreateInboxPlacementTestOptions {
pub test_type: Option<u8>,
pub sender_email: Option<String>,
pub provider_ids: Option<Vec<i64>>,
pub seed_ids: Option<Vec<i64>>,
pub providers: Option<Vec<InboxPlacementProviderSelection>>,
pub webhook_url: Option<String>,
}
#[derive(Clone, Debug, Default)]
pub struct ListInboxPlacementTestsOptions {
pub status: Option<String>,
pub created_after: Option<String>,
pub created_before: Option<String>,
pub page: Option<u32>,
pub page_size: Option<u32>,
}
impl ZeroBounce {
pub fn get_inbox_placement_providers(&self) -> ZBResult<Value> {
self.inbox_placement_get("/providers", HashMap::new())
}
pub fn get_inbox_placement_test_types(&self) -> ZBResult<Value> {
self.inbox_placement_get("/test-types", HashMap::new())
}
pub fn create_inbox_placement_test(
&self,
name: &str,
options: &CreateInboxPlacementTestOptions,
) -> ZBResult<Value> {
if name.trim().is_empty() {
return Err(ZBError::explicit("Empty parameter: name"));
}
if name.chars().count() > 64 {
return Err(ZBError::explicit(
"Invalid parameter: name (at most 64 characters)",
));
}
if let Some(test_type) = options.test_type {
if !TEST_TYPES.contains(&test_type) {
return Err(ZBError::explicit(
"Invalid parameter: test_type (must be 1, 2 or 3)",
));
}
if test_type == 1
&& options
.sender_email
.as_deref()
.map(|value| value.trim().is_empty())
.unwrap_or(true)
{
return Err(ZBError::explicit(
"Empty parameter: sender_email (required when test_type is 1)",
));
}
}
for provider in options.providers.iter().flatten() {
if provider.max_seeds.map(|seeds| seeds < 1).unwrap_or(false) {
return Err(ZBError::explicit(
"Invalid parameter: providers (max_seeds must be at least 1)",
));
}
}
let mut body = Map::new();
body.insert("name".to_string(), json!(name));
if let Some(test_type) = options.test_type {
body.insert("testType".to_string(), json!(test_type));
}
if let Some(sender_email) = options.sender_email.as_deref() {
body.insert("senderEmail".to_string(), json!(sender_email));
}
if let Some(provider_ids) = options.provider_ids.as_ref() {
body.insert("providerIds".to_string(), json!(provider_ids));
}
if let Some(seed_ids) = options.seed_ids.as_ref() {
body.insert("seedIds".to_string(), json!(seed_ids));
}
if let Some(providers) = options.providers.as_ref() {
let entries: Vec<Value> = providers
.iter()
.map(|provider| match provider.max_seeds {
Some(max_seeds) => json!({"id": provider.id, "maxSeeds": max_seeds}),
None => json!({"id": provider.id}),
})
.collect();
body.insert("providers".to_string(), Value::Array(entries));
}
if let Some(webhook_url) = options.webhook_url.as_deref() {
body.insert("webhookUrl".to_string(), json!(webhook_url));
}
self.inbox_placement_json("POST", "/test", Value::Object(body))
}
pub fn get_inbox_placement_test(&self, test_id: &str) -> ZBResult<Value> {
let path = format!("/test/{}", Self::inbox_placement_test_path(test_id)?);
self.inbox_placement_get(&path, HashMap::new())
}
pub fn list_inbox_placement_tests(
&self,
options: &ListInboxPlacementTestsOptions,
) -> ZBResult<Value> {
if let Some(status) = options.status.as_deref() {
if !TEST_STATUSES.contains(&status) {
return Err(ZBError::explicit(
"Invalid parameter: status (must be running or finished)",
));
}
}
if options.page.map(|page| page < 1).unwrap_or(false) {
return Err(ZBError::explicit(
"Invalid parameter: page (must be at least 1)",
));
}
if options
.page_size
.map(|size| !(1..=100).contains(&size))
.unwrap_or(false)
{
return Err(ZBError::explicit(
"Invalid parameter: page_size (must be between 1 and 100)",
));
}
let page_param;
let page_size_param;
let mut query: HashMap<&str, &str> = HashMap::new();
if let Some(status) = options.status.as_deref() {
query.insert("status", status);
}
if let Some(created_after) = options.created_after.as_deref() {
query.insert("createdAfter", created_after);
}
if let Some(created_before) = options.created_before.as_deref() {
query.insert("createdBefore", created_before);
}
if let Some(page) = options.page {
page_param = page.to_string();
query.insert("page", &page_param);
}
if let Some(page_size) = options.page_size {
page_size_param = page_size.to_string();
query.insert("page_size", &page_size_param);
}
self.inbox_placement_get("/tests", query)
}
pub fn delete_inbox_placement_test(&self, test_id: &str) -> ZBResult<Value> {
let path = format!("/test/{}", Self::inbox_placement_test_path(test_id)?);
self.inbox_placement_send("DELETE", &path, HashMap::new(), None, true)
}
pub fn get_inbox_placement_webhook(&self) -> ZBResult<Value> {
self.inbox_placement_get("/webhook", HashMap::new())
}
pub fn set_inbox_placement_webhook(&self, webhook_url: &str) -> ZBResult<Value> {
if webhook_url.trim().is_empty() {
return Err(ZBError::explicit("Empty parameter: webhook_url"));
}
self.inbox_placement_json("PUT", "/webhook", json!({ "webhookUrl": webhook_url }))
}
fn inbox_placement_test_path(test_id: &str) -> ZBResult<String> {
if test_id.trim().is_empty() {
return Err(ZBError::explicit("Empty parameter: test_id"));
}
Ok(encode_path_segment(test_id.trim()))
}
fn inbox_placement_get<'a>(
&'a self,
path: &str,
query: HashMap<&'a str, &'a str>,
) -> ZBResult<Value> {
self.inbox_placement_request("GET", path, query, None)
}
fn inbox_placement_json(&self, method: &str, path: &str, body: Value) -> ZBResult<Value> {
self.inbox_placement_request(method, path, HashMap::new(), Some(body))
}
fn inbox_placement_request<'a>(
&'a self,
method: &str,
path: &str,
query: HashMap<&'a str, &'a str>,
body: Option<Value>,
) -> ZBResult<Value> {
self.inbox_placement_send(method, path, query, body, false)
}
fn inbox_placement_send<'a>(
&'a self,
method: &str,
path: &str,
query: HashMap<&'a str, &'a str>,
body: Option<Value>,
empty_2xx_is_success: bool,
) -> ZBResult<Value> {
self.require_key()?;
let parsed =
crate::parse_request_url(&self.url_provider.inbox_placement_url_of(path))?;
let mut request = match method {
"POST" => self.client.post(parsed),
"PUT" => self.client.put(parsed),
"DELETE" => self.client.delete(parsed),
_ => self.client.get(parsed),
}
.query(&query)
.bearer_auth(self.api_key.as_str());
if let Some(body) = body {
let encoded = serde_json::to_string(&body)
.map_err(|_| ZBError::explicit("Invalid parameter: request body"))?;
request = request
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(encoded);
}
let response = request.send()?;
let (status, content_type, content) = Self::read_api_body(response)?;
if empty_2xx_is_success && (200..300).contains(&status) && content.is_empty() {
return Ok(Value::Null);
}
crate::utility::http_error::ensure_json_api_body(status, &content_type, &content)
.map_err(|error| self.redact_error(error))?;
crate::utility::http_error::parse_json_body_with_status(status, &content)
}
}