Skip to main content

zero_bounce/api/
validation.rs

1use std::collections::HashMap;
2
3use serde::Serialize;
4use serde_json::{Map as SerdeMap, Value};
5
6use crate::utility::structures::validate_options::ZBValidateOptions;
7use crate::utility::structures::validation::{ZBBatchValidation, ZBValidation};
8use crate::utility::{ZBError, CONTENT_TYPE_JSON, ENDPOINT_BATCH_VALIDATE, ENDPOINT_VALIDATE};
9use crate::{ZBResult, ZeroBounce};
10
11/// Whether a validate result (or a validatebatch row) has the `address` and
12/// `status` strings it cannot do without (standard.md ยง3, "field types are
13/// part of the shape"), or is the greylist answer, which carries only
14/// `"Message"`. Serde already refuses a field of another JSON type, and
15/// `null` for these two; the struct defaults them only for the greylist answer.
16fn has_address_and_status(row: &Value) -> bool {
17    let is_string = |key: &str| row.get(key).is_some_and(Value::is_string);
18    is_string("Message") || (is_string("address") && is_string("status"))
19}
20
21fn unexpected_shape(status: u16) -> ZBError {
22    ZBError::api(status, crate::utility::http_error::UNEXPECTED_JSON_SHAPE_MESSAGE)
23}
24
25impl ZeroBounce {
26    pub fn validate_email_and_ip(&self, email: &str, ip_address: &str) -> ZBResult<ZBValidation> {
27        self.validate_email_with_options(email, ip_address, &ZBValidateOptions::default())
28    }
29
30    pub fn validate_email_with_options(
31        &self,
32        email: &str,
33        ip_address: &str,
34        options: &ZBValidateOptions,
35    ) -> ZBResult<ZBValidation> {
36        if let Some(timeout) = options.timeout {
37            if !(3..=60).contains(&timeout) {
38                return Err(ZBError::explicit(
39                    "Invalid parameter: timeout (must be between 3 and 60 seconds)",
40                ));
41            }
42        }
43        // callback_url only means anything while greylist processing is on, so it is
44        // rejected here rather than letting the API take the request.
45        if let Some(callback_url) = options.callback_url.as_deref() {
46            if options.greylist_processing != Some(true) {
47                return Err(ZBError::explicit(
48                    "Invalid parameter: callback_url requires greylist_processing = true",
49                ));
50            }
51            if callback_url.trim().is_empty() {
52                return Err(ZBError::explicit("Empty parameter: callback_url"));
53            }
54        }
55
56        let mut query_args = HashMap::from([("email", email)]);
57        let timeout_param;
58        let activity_param;
59        let verify_param;
60        let domain_info_param;
61        let greylist_param;
62
63        if !ip_address.is_empty() {
64            query_args.insert("ip_address", ip_address);
65        }
66        if let Some(timeout) = options.timeout {
67            timeout_param = timeout.to_string();
68            query_args.insert("timeout", &timeout_param);
69        }
70        if let Some(activity_data) = options.activity_data {
71            activity_param = if activity_data { "true" } else { "false" };
72            query_args.insert("activity_data", activity_param);
73        }
74        if let Some(verify_plus) = options.verify_plus {
75            verify_param = if verify_plus { "true" } else { "false" };
76            query_args.insert("verify_plus", verify_param);
77        }
78        if let Some(domain_info) = options.domain_info {
79            domain_info_param = if domain_info { "true" } else { "false" };
80            query_args.insert("domain_info", domain_info_param);
81        }
82        if let Some(greylist_processing) = options.greylist_processing {
83            greylist_param = if greylist_processing { "true" } else { "false" };
84            query_args.insert("greylist_processing", greylist_param);
85        }
86        if let Some(callback_url) = options.callback_url.as_deref() {
87            query_args.insert("callback_url", callback_url);
88        }
89
90        let (status, response_content) = if options.use_post {
91            let mut form_args = HashMap::from([("email", email)]);
92            let timeout_param;
93            let activity_param;
94            let verify_param;
95            let domain_info_param;
96            let greylist_param;
97            if !ip_address.is_empty() {
98                form_args.insert("ip_address", ip_address);
99            }
100            if let Some(timeout) = options.timeout {
101                timeout_param = timeout.to_string();
102                form_args.insert("timeout", &timeout_param);
103            }
104            if let Some(activity_data) = options.activity_data {
105                activity_param = if activity_data { "true" } else { "false" };
106                form_args.insert("activity_data", activity_param);
107            }
108            if let Some(verify_plus) = options.verify_plus {
109                verify_param = if verify_plus { "true" } else { "false" };
110                form_args.insert("verify_plus", verify_param);
111            }
112            if let Some(domain_info) = options.domain_info {
113                domain_info_param = if domain_info { "true" } else { "false" };
114                form_args.insert("domain_info", domain_info_param);
115            }
116            if let Some(greylist_processing) = options.greylist_processing {
117                greylist_param = if greylist_processing { "true" } else { "false" };
118                form_args.insert("greylist_processing", greylist_param);
119            }
120            if let Some(callback_url) = options.callback_url.as_deref() {
121                form_args.insert("callback_url", callback_url);
122            }
123            self.form_post_request_with_status(self.url_provider.url_of(ENDPOINT_VALIDATE), form_args)?
124        } else {
125            self.get_request_with_status(self.url_provider.url_of(ENDPOINT_VALIDATE), query_args, false)?
126        };
127
128        let validation: ZBValidation =
129            crate::utility::http_error::parse_json_body_with_status(status, &response_content)?;
130        let body: Value =
131            crate::utility::http_error::parse_json_body_with_status(status, &response_content)?;
132        if !has_address_and_status(&body) {
133            return Err(unexpected_shape(status));
134        }
135        Ok(validation)
136    }
137
138    pub fn validate_email(&self, email: &str) -> ZBResult<ZBValidation> {
139        self.validate_email_and_ip(email, "")
140    }
141
142    // Represent a list of tuples (containing email and ip_address) into a
143    // serializable `serde_json::Value` that respects the expected structure
144    // of the batch validation endpoint.
145    //
146    // Said structure:
147    // ```json
148    // {
149    //     "api_key": {{apikey}},
150    //     "email_batch": [
151    //         {"email_address": "valid@example.com", "ip_address": "0.0.0.0"},
152    //         {"email_address": "invalid@example.com", "ip_address": "1.1.1.1"}
153    //     ]
154    // }
155    // ```
156    // After the value is built, serialize and return the resulted string.
157    fn batch_validate_prepare_body(
158        &self,
159        emails_and_ip_addresses: Vec<(String, String)>,
160        options: &ZBValidateOptions,
161    ) -> ZBResult<String> {
162        let email_batch = emails_and_ip_addresses
163            .into_iter()
164            .map(|(email, ip_address)| {
165                [
166                    ("email_address".to_string(), Value::String(email)),
167                    ("ip_address".to_string(), Value::String(ip_address)),
168                ]
169            })
170            .map(SerdeMap::<String, Value>::from_iter)
171            .map(Value::Object)
172            .collect::<Vec<Value>>();
173
174        let mut request_body_map = SerdeMap::from_iter([
175            ("api_key".to_string(), Value::String(self.api_key.clone())),
176            ("email_batch".to_string(), Value::Array(email_batch)),
177        ]);
178        if let Some(timeout) = options.timeout {
179            // LIVE: validatebatch takes timeout as a JSON *string*. Sent as a
180            // number, the API rejects the whole batch with the account-level
181            // "Invalid API Key or your account ran out of credits".
182            request_body_map.insert("timeout".to_string(), Value::String(timeout.to_string()));
183        }
184        if let Some(activity_data) = options.activity_data {
185            request_body_map.insert("activity_data".to_string(), Value::Bool(activity_data));
186        }
187        if let Some(verify_plus) = options.verify_plus {
188            request_body_map.insert("verify_plus".to_string(), Value::Bool(verify_plus));
189        }
190
191        // let request_body_object = Value::Object(request_body_map);
192        let mut serializer = serde_json::Serializer::new(Vec::new());
193        Value::Object(request_body_map)
194            .serialize(&mut serializer)
195            .map_err(ZBError::from)?;
196
197        let final_string = String::from_utf8(serializer.into_inner())
198            .map_err(|error| ZBError::ExplicitError(error.to_string()))?;
199
200        Ok(final_string)
201    }
202
203    pub fn batch_validate(
204        &self,
205        emails_and_ip_addresses: Vec<(String, String)>,
206    ) -> ZBResult<ZBBatchValidation> {
207        self.batch_validate_with_options(emails_and_ip_addresses, &ZBValidateOptions::default())
208    }
209
210    pub fn batch_validate_with_options(
211        &self,
212        emails_and_ip_addresses: Vec<(String, String)>,
213        options: &ZBValidateOptions,
214    ) -> ZBResult<ZBBatchValidation> {
215        if let Some(timeout) = options.timeout {
216            if !(10..=120).contains(&timeout) {
217                return Err(ZBError::explicit(
218                    "Invalid parameter: timeout (must be between 10 and 120 seconds)",
219                ));
220            }
221        }
222        self.require_key()?;
223        let body_content = self.batch_validate_prepare_body(emails_and_ip_addresses, options)?;
224        let url = self.url_provider.url_of(ENDPOINT_BATCH_VALIDATE);
225
226        let response = self
227            .client
228            .post(crate::parse_request_url(&url)?)
229            .body(body_content)
230            .header("content-type", CONTENT_TYPE_JSON)
231            .send()?;
232
233        let (status, response_content) = self.read_api_response_with_status(response, false)?;
234        let validation: ZBBatchValidation =
235            crate::utility::http_error::parse_json_body_with_status(status, &response_content)?;
236        let body: Value =
237            crate::utility::http_error::parse_json_body_with_status(status, &response_content)?;
238        let rows = body.get("email_batch").and_then(Value::as_array).map_or(&[][..], Vec::as_slice);
239        if !rows.iter().all(has_address_and_status) {
240            return Err(unexpected_shape(status));
241        }
242        for item in &validation.errors {
243            if item.email_address.eq_ignore_ascii_case("all") {
244                let message = crate::utility::http_error::strip_error_prefix(&item.error);
245                let message = if message.is_empty() {
246                    "Invalid API Key or your account ran out of credits".to_string()
247                } else {
248                    message
249                };
250                // The account-level failure arrives on an HTTP 200; carry it so
251                // status_code() is Some, like every other failed response.
252                return Err(self.redact_error(ZBError::api(status, message)));
253            }
254        }
255        Ok(validation)
256    }
257}
258
259#[cfg(test)]
260mod test {
261    use crate::ZeroBounce;
262
263    #[test]
264    fn test_serializing_example() {
265        let emails_and_ip_addresses = vec![
266            (
267                "valid@example.com".to_string(),
268                "123.123.123.123".to_string(),
269            ),
270            ("invalid@example.com".to_string(), "".to_string()),
271        ];
272
273        let body_result = ZeroBounce::new("some_api_key").batch_validate_prepare_body(
274            emails_and_ip_addresses,
275            &crate::utility::structures::validate_options::ZBValidateOptions::default(),
276        );
277
278        assert!(body_result.is_ok())
279    }
280
281    /// The crate's own validate and batch fixtures keep parsing under the
282    /// address/status check.
283    #[test]
284    fn the_validate_fixtures_have_address_and_status() {
285        use crate::utility::mock_constants::*;
286        for fixture in [VALIDATION_RESPONSE_VALID, VALIDATION_RESPONSE_INVALID, VALIDATION_RESPONSE_NULL_FIELDS] {
287            let body: serde_json::Value = serde_json::from_str(fixture).unwrap();
288            assert!(super::has_address_and_status(&body), "{fixture}");
289        }
290        for fixture in [BATCH_VALIDATION_WITH_ERROR, BATCH_VALIDATION_ERROR_ONLY, BATCH_VALIDATION_NO_ERROR] {
291            let body: serde_json::Value = serde_json::from_str(fixture).unwrap();
292            assert!(body["email_batch"].as_array().unwrap().iter().all(super::has_address_and_status), "{fixture}");
293        }
294    }
295}