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
11impl ZeroBounce {
12    pub fn validate_email_and_ip(&self, email: &str, ip_address: &str) -> ZBResult<ZBValidation> {
13        self.validate_email_with_options(email, ip_address, &ZBValidateOptions::default())
14    }
15
16    pub fn validate_email_with_options(
17        &self,
18        email: &str,
19        ip_address: &str,
20        options: &ZBValidateOptions,
21    ) -> ZBResult<ZBValidation> {
22        if let Some(timeout) = options.timeout {
23            if !(3..=60).contains(&timeout) {
24                return Err(ZBError::explicit(
25                    "Invalid parameter: timeout (must be between 3 and 60 seconds)",
26                ));
27            }
28        }
29        // callback_url only means anything while greylist processing is on, so it is
30        // rejected here rather than letting the API take the request.
31        if let Some(callback_url) = options.callback_url.as_deref() {
32            if options.greylist_processing != Some(true) {
33                return Err(ZBError::explicit(
34                    "Invalid parameter: callback_url requires greylist_processing = true",
35                ));
36            }
37            if callback_url.trim().is_empty() {
38                return Err(ZBError::explicit("Empty parameter: callback_url"));
39            }
40        }
41
42        let mut query_args = HashMap::from([("email", email)]);
43        let timeout_param;
44        let activity_param;
45        let verify_param;
46        let domain_info_param;
47        let greylist_param;
48
49        if !ip_address.is_empty() {
50            query_args.insert("ip_address", ip_address);
51        }
52        if let Some(timeout) = options.timeout {
53            timeout_param = timeout.to_string();
54            query_args.insert("timeout", &timeout_param);
55        }
56        if let Some(activity_data) = options.activity_data {
57            activity_param = if activity_data { "true" } else { "false" };
58            query_args.insert("activity_data", activity_param);
59        }
60        if let Some(verify_plus) = options.verify_plus {
61            verify_param = if verify_plus { "true" } else { "false" };
62            query_args.insert("verify_plus", verify_param);
63        }
64        if let Some(domain_info) = options.domain_info {
65            domain_info_param = if domain_info { "true" } else { "false" };
66            query_args.insert("domain_info", domain_info_param);
67        }
68        if let Some(greylist_processing) = options.greylist_processing {
69            greylist_param = if greylist_processing { "true" } else { "false" };
70            query_args.insert("greylist_processing", greylist_param);
71        }
72        if let Some(callback_url) = options.callback_url.as_deref() {
73            query_args.insert("callback_url", callback_url);
74        }
75
76        let response_content = if options.use_post {
77            let mut form_args = HashMap::from([("email", email)]);
78            let timeout_param;
79            let activity_param;
80            let verify_param;
81            let domain_info_param;
82            let greylist_param;
83            if !ip_address.is_empty() {
84                form_args.insert("ip_address", ip_address);
85            }
86            if let Some(timeout) = options.timeout {
87                timeout_param = timeout.to_string();
88                form_args.insert("timeout", &timeout_param);
89            }
90            if let Some(activity_data) = options.activity_data {
91                activity_param = if activity_data { "true" } else { "false" };
92                form_args.insert("activity_data", activity_param);
93            }
94            if let Some(verify_plus) = options.verify_plus {
95                verify_param = if verify_plus { "true" } else { "false" };
96                form_args.insert("verify_plus", verify_param);
97            }
98            if let Some(domain_info) = options.domain_info {
99                domain_info_param = if domain_info { "true" } else { "false" };
100                form_args.insert("domain_info", domain_info_param);
101            }
102            if let Some(greylist_processing) = options.greylist_processing {
103                greylist_param = if greylist_processing { "true" } else { "false" };
104                form_args.insert("greylist_processing", greylist_param);
105            }
106            if let Some(callback_url) = options.callback_url.as_deref() {
107                form_args.insert("callback_url", callback_url);
108            }
109            self.generic_form_post_request(self.url_provider.url_of(ENDPOINT_VALIDATE), form_args)?
110        } else {
111            self.generic_get_request(self.url_provider.url_of(ENDPOINT_VALIDATE), query_args)?
112        };
113
114        crate::utility::http_error::parse_json_body(&response_content)
115    }
116
117    pub fn validate_email(&self, email: &str) -> ZBResult<ZBValidation> {
118        self.validate_email_and_ip(email, "")
119    }
120
121    // Represent a list of tuples (containing email and ip_address) into a
122    // serializable `serde_json::Value` that respects the expected structure
123    // of the batch validation endpoint.
124    //
125    // Said structure:
126    // ```json
127    // {
128    //     "api_key": {{apikey}},
129    //     "email_batch": [
130    //         {"email_address": "valid@example.com", "ip_address": "0.0.0.0"},
131    //         {"email_address": "invalid@example.com", "ip_address": "1.1.1.1"}
132    //     ]
133    // }
134    // ```
135    // After the value is built, serialize and return the resulted string.
136    fn batch_validate_prepare_body(
137        &self,
138        emails_and_ip_addresses: Vec<(String, String)>,
139        options: &ZBValidateOptions,
140    ) -> ZBResult<String> {
141        let email_batch = emails_and_ip_addresses
142            .into_iter()
143            .map(|(email, ip_address)| {
144                [
145                    ("email_address".to_string(), Value::String(email)),
146                    ("ip_address".to_string(), Value::String(ip_address)),
147                ]
148            })
149            .map(SerdeMap::<String, Value>::from_iter)
150            .map(Value::Object)
151            .collect::<Vec<Value>>();
152
153        let mut request_body_map = SerdeMap::from_iter([
154            ("api_key".to_string(), Value::String(self.api_key.clone())),
155            ("email_batch".to_string(), Value::Array(email_batch)),
156        ]);
157        if let Some(timeout) = options.timeout {
158            // LIVE: validatebatch takes timeout as a JSON *string*. Sent as a
159            // number, the API rejects the whole batch with the account-level
160            // "Invalid API Key or your account ran out of credits".
161            request_body_map.insert("timeout".to_string(), Value::String(timeout.to_string()));
162        }
163        if let Some(activity_data) = options.activity_data {
164            request_body_map.insert("activity_data".to_string(), Value::Bool(activity_data));
165        }
166        if let Some(verify_plus) = options.verify_plus {
167            request_body_map.insert("verify_plus".to_string(), Value::Bool(verify_plus));
168        }
169
170        // let request_body_object = Value::Object(request_body_map);
171        let mut serializer = serde_json::Serializer::new(Vec::new());
172        Value::Object(request_body_map)
173            .serialize(&mut serializer)
174            .map_err(ZBError::JsonError)?;
175
176        let final_string = String::from_utf8(serializer.into_inner())
177            .map_err(|error| ZBError::ExplicitError(error.to_string()))?;
178
179        Ok(final_string)
180    }
181
182    pub fn batch_validate(
183        &self,
184        emails_and_ip_addresses: Vec<(String, String)>,
185    ) -> ZBResult<ZBBatchValidation> {
186        self.batch_validate_with_options(emails_and_ip_addresses, &ZBValidateOptions::default())
187    }
188
189    pub fn batch_validate_with_options(
190        &self,
191        emails_and_ip_addresses: Vec<(String, String)>,
192        options: &ZBValidateOptions,
193    ) -> ZBResult<ZBBatchValidation> {
194        if let Some(timeout) = options.timeout {
195            if !(10..=120).contains(&timeout) {
196                return Err(ZBError::explicit(
197                    "Invalid parameter: timeout (must be between 10 and 120 seconds)",
198                ));
199            }
200        }
201        self.require_key()?;
202        let body_content = self.batch_validate_prepare_body(emails_and_ip_addresses, options)?;
203        let url = self.url_provider.url_of(ENDPOINT_BATCH_VALIDATE);
204
205        let response = self
206            .client
207            .post(crate::parse_request_url(&url)?)
208            .body(body_content)
209            .header("content-type", CONTENT_TYPE_JSON)
210            .send()?;
211
212        let status = response.status().as_u16();
213        let response_content = self.read_api_response(response)?;
214        let validation: ZBBatchValidation =
215            crate::utility::http_error::parse_json_body(&response_content)?;
216        for item in &validation.errors {
217            if item.email_address.eq_ignore_ascii_case("all") {
218                let message = crate::utility::http_error::strip_error_prefix(&item.error);
219                let message = if message.is_empty() {
220                    "Invalid API Key or your account ran out of credits".to_string()
221                } else {
222                    message
223                };
224                // The account-level failure arrives on an HTTP 200; carry it so
225                // status_code() is Some, like every other failed response.
226                return Err(ZBError::api(status, message));
227            }
228        }
229        Ok(validation)
230    }
231}
232
233#[cfg(test)]
234mod test {
235    use crate::ZeroBounce;
236
237    #[test]
238    fn test_serializing_example() {
239        let emails_and_ip_addresses = vec![
240            (
241                "valid@example.com".to_string(),
242                "123.123.123.123".to_string(),
243            ),
244            ("invalid@example.com".to_string(), "".to_string()),
245        ];
246
247        let body_result = ZeroBounce::new("some_api_key").batch_validate_prepare_body(
248            emails_and_ip_addresses,
249            &crate::utility::structures::validate_options::ZBValidateOptions::default(),
250        );
251
252        assert!(body_result.is_ok())
253    }
254}