Skip to main content

zero_bounce/api/
inbox_placement.rs

1//! Inbox Placement Tester (bulkapi.zerobounce.net/api/ipt).
2//!
3//! The API key goes in an `Authorization: Bearer` header, and bodies are
4//! JSON with camelCase fields. Only fields the caller set are sent. Uses the
5//! account's inbox-test credits.
6
7use std::collections::HashMap;
8
9use serde_json::{json, Map, Value};
10
11use crate::utility::{encode_path_segment, ZBError, ZBResult};
12use crate::ZeroBounce;
13
14const TEST_TYPES: [u8; 3] = [1, 2, 3];
15const TEST_STATUSES: [&str; 2] = ["running", "finished"];
16
17/// A per-provider seed cap for [`ZeroBounce::create_inbox_placement_test`].
18#[derive(Clone, Debug)]
19pub struct InboxPlacementProviderSelection {
20    pub id: i64,
21    /// At least 1 when given.
22    pub max_seeds: Option<i64>,
23}
24
25/// Options for [`ZeroBounce::create_inbox_placement_test`]. Unset fields are not sent.
26#[derive(Clone, Debug, Default)]
27pub struct CreateInboxPlacementTestOptions {
28    /// 1 (Email, needs `sender_email`), 2 (Unique ID) or 3 (Auto Alias).
29    pub test_type: Option<u8>,
30    /// The From address to match; required when `test_type` is 1.
31    pub sender_email: Option<String>,
32    /// Use every active seed of these providers.
33    pub provider_ids: Option<Vec<i64>>,
34    /// Use these seed mailboxes.
35    pub seed_ids: Option<Vec<i64>>,
36    /// Cap the seeds taken from each provider.
37    pub providers: Option<Vec<InboxPlacementProviderSelection>>,
38    /// Where the finished result is posted.
39    pub webhook_url: Option<String>,
40}
41
42/// Filters for [`ZeroBounce::list_inbox_placement_tests`]. Unset fields are not sent.
43#[derive(Clone, Debug, Default)]
44pub struct ListInboxPlacementTestsOptions {
45    /// "running" or "finished".
46    pub status: Option<String>,
47    /// ISO 8601 date or datetime.
48    pub created_after: Option<String>,
49    /// ISO 8601 date or datetime.
50    pub created_before: Option<String>,
51    /// From 1.
52    pub page: Option<u32>,
53    /// 1 to 100.
54    pub page_size: Option<u32>,
55}
56
57impl ZeroBounce {
58    /// Seed providers available for new tests. `GET /providers`
59    pub fn get_inbox_placement_providers(&self) -> ZBResult<Value> {
60        self.inbox_placement_get("/providers", HashMap::new())
61    }
62
63    /// Supported test types and the default one. `GET /test-types`
64    pub fn get_inbox_placement_test_types(&self) -> ZBResult<Value> {
65        self.inbox_placement_get("/test-types", HashMap::new())
66    }
67
68    /// Create an inbox placement test. `POST /test`
69    ///
70    /// `name` must be non-empty and at most 64 characters. Spends one inbox test.
71    pub fn create_inbox_placement_test(
72        &self,
73        name: &str,
74        options: &CreateInboxPlacementTestOptions,
75    ) -> ZBResult<Value> {
76        if name.trim().is_empty() {
77            return Err(ZBError::explicit("Empty parameter: name"));
78        }
79        if name.chars().count() > 64 {
80            return Err(ZBError::explicit(
81                "Invalid parameter: name (at most 64 characters)",
82            ));
83        }
84        if let Some(test_type) = options.test_type {
85            if !TEST_TYPES.contains(&test_type) {
86                return Err(ZBError::explicit(
87                    "Invalid parameter: test_type (must be 1, 2 or 3)",
88                ));
89            }
90            if test_type == 1
91                && options
92                    .sender_email
93                    .as_deref()
94                    .map(|value| value.trim().is_empty())
95                    .unwrap_or(true)
96            {
97                return Err(ZBError::explicit(
98                    "Empty parameter: sender_email (required when test_type is 1)",
99                ));
100            }
101        }
102        for provider in options.providers.iter().flatten() {
103            if provider.max_seeds.map(|seeds| seeds < 1).unwrap_or(false) {
104                return Err(ZBError::explicit(
105                    "Invalid parameter: providers (max_seeds must be at least 1)",
106                ));
107            }
108        }
109
110        let mut body = Map::new();
111        body.insert("name".to_string(), json!(name));
112        if let Some(test_type) = options.test_type {
113            body.insert("testType".to_string(), json!(test_type));
114        }
115        if let Some(sender_email) = options.sender_email.as_deref() {
116            body.insert("senderEmail".to_string(), json!(sender_email));
117        }
118        if let Some(provider_ids) = options.provider_ids.as_ref() {
119            body.insert("providerIds".to_string(), json!(provider_ids));
120        }
121        if let Some(seed_ids) = options.seed_ids.as_ref() {
122            body.insert("seedIds".to_string(), json!(seed_ids));
123        }
124        if let Some(providers) = options.providers.as_ref() {
125            let entries: Vec<Value> = providers
126                .iter()
127                .map(|provider| match provider.max_seeds {
128                    Some(max_seeds) => json!({"id": provider.id, "maxSeeds": max_seeds}),
129                    None => json!({"id": provider.id}),
130                })
131                .collect();
132            body.insert("providers".to_string(), Value::Array(entries));
133        }
134        if let Some(webhook_url) = options.webhook_url.as_deref() {
135            body.insert("webhookUrl".to_string(), json!(webhook_url));
136        }
137        self.inbox_placement_json("POST", "/test", Value::Object(body))
138    }
139
140    /// A test and its placement results. `GET /test/{id}`
141    pub fn get_inbox_placement_test(&self, test_id: &str) -> ZBResult<Value> {
142        let path = format!("/test/{}", Self::inbox_placement_test_path(test_id)?);
143        self.inbox_placement_get(&path, HashMap::new())
144    }
145
146    /// List tests, newest first. `GET /tests`
147    pub fn list_inbox_placement_tests(
148        &self,
149        options: &ListInboxPlacementTestsOptions,
150    ) -> ZBResult<Value> {
151        if let Some(status) = options.status.as_deref() {
152            if !TEST_STATUSES.contains(&status) {
153                return Err(ZBError::explicit(
154                    "Invalid parameter: status (must be running or finished)",
155                ));
156            }
157        }
158        if options.page.map(|page| page < 1).unwrap_or(false) {
159            return Err(ZBError::explicit(
160                "Invalid parameter: page (must be at least 1)",
161            ));
162        }
163        if options
164            .page_size
165            .map(|size| !(1..=100).contains(&size))
166            .unwrap_or(false)
167        {
168            return Err(ZBError::explicit(
169                "Invalid parameter: page_size (must be between 1 and 100)",
170            ));
171        }
172
173        let page_param;
174        let page_size_param;
175        let mut query: HashMap<&str, &str> = HashMap::new();
176        if let Some(status) = options.status.as_deref() {
177            query.insert("status", status);
178        }
179        if let Some(created_after) = options.created_after.as_deref() {
180            query.insert("createdAfter", created_after);
181        }
182        if let Some(created_before) = options.created_before.as_deref() {
183            query.insert("createdBefore", created_before);
184        }
185        if let Some(page) = options.page {
186            page_param = page.to_string();
187            query.insert("page", &page_param);
188        }
189        if let Some(page_size) = options.page_size {
190            page_size_param = page_size.to_string();
191            query.insert("page_size", &page_size_param);
192        }
193        self.inbox_placement_get("/tests", query)
194    }
195
196    /// Delete a finished test. `DELETE /test/{id}`
197    pub fn delete_inbox_placement_test(&self, test_id: &str) -> ZBResult<Value> {
198        let path = format!("/test/{}", Self::inbox_placement_test_path(test_id)?);
199        self.inbox_placement_request("DELETE", &path, HashMap::new(), None)
200    }
201
202    /// The webhook URL saved on this API key. `GET /webhook`
203    pub fn get_inbox_placement_webhook(&self) -> ZBResult<Value> {
204        self.inbox_placement_get("/webhook", HashMap::new())
205    }
206
207    /// Save the URL finished results are posted to. `PUT /webhook`
208    pub fn set_inbox_placement_webhook(&self, webhook_url: &str) -> ZBResult<Value> {
209        if webhook_url.trim().is_empty() {
210            return Err(ZBError::explicit("Empty parameter: webhook_url"));
211        }
212        self.inbox_placement_json("PUT", "/webhook", json!({ "webhookUrl": webhook_url }))
213    }
214
215    fn inbox_placement_test_path(test_id: &str) -> ZBResult<String> {
216        if test_id.trim().is_empty() {
217            return Err(ZBError::explicit("Empty parameter: test_id"));
218        }
219        Ok(encode_path_segment(test_id.trim()))
220    }
221
222    fn inbox_placement_get<'a>(
223        &'a self,
224        path: &str,
225        query: HashMap<&'a str, &'a str>,
226    ) -> ZBResult<Value> {
227        self.inbox_placement_request("GET", path, query, None)
228    }
229
230    fn inbox_placement_json(&self, method: &str, path: &str, body: Value) -> ZBResult<Value> {
231        self.inbox_placement_request(method, path, HashMap::new(), Some(body))
232    }
233
234    fn inbox_placement_request<'a>(
235        &'a self,
236        method: &str,
237        path: &str,
238        query: HashMap<&'a str, &'a str>,
239        body: Option<Value>,
240    ) -> ZBResult<Value> {
241        self.require_key()?;
242
243        // The same https rule as every other request: an http:// override would
244        // otherwise send the Bearer key in cleartext.
245        let parsed =
246            crate::parse_request_url(&self.url_provider.inbox_placement_url_of(path))?;
247
248        let mut request = match method {
249            "POST" => self.client.post(parsed),
250            "PUT" => self.client.put(parsed),
251            "DELETE" => self.client.delete(parsed),
252            _ => self.client.get(parsed),
253        }
254        .query(&query)
255        // LIVE: the Inbox Placement Tester authenticates with a Bearer header.
256        // Sent as an api_key parameter the request is rejected as unauthorized.
257        .bearer_auth(self.api_key.as_str());
258
259        if let Some(body) = body {
260            // reqwest's json() helper needs its "json" feature, which this crate
261            // does not enable, so the body and content type are set directly.
262            let encoded = serde_json::to_string(&body)
263                .map_err(|_| ZBError::explicit("Invalid parameter: request body"))?;
264            request = request
265                .header(reqwest::header::CONTENT_TYPE, "application/json")
266                .body(encoded);
267        }
268
269        let response = request.send()?;
270        let content = self.read_api_response(response)?;
271        crate::utility::http_error::parse_json_body(&content)
272    }
273}