1pub mod bulk;
2pub mod inbox_placement;
3pub mod priority3;
4pub mod validation;
5
6use std::collections::HashMap;
7
8use chrono::{NaiveDate, Utc};
9
10pub use crate::ZeroBounce;
11use crate::utility::http_error::{parse_json_body_with_status, UNEXPECTED_JSON_SHAPE_MESSAGE};
12use crate::utility::structures::generic::{
13 FindEmailResponse, FindEmailResponseV2, DomainSearchResponseV2, DOMAIN_SEARCH_V2_FIELD_NAMES,
14};
15use crate::utility::{ZBError, ZBResult, ENDPOINT_EMAIL_FINDER};
16use crate::utility::structures::{ActivityData, ApiUsage};
17use crate::utility::structures::generic::ScoreEmailResponse;
18use crate::utility::{ENDPOINT_ACTIVITY_DATA, ENDPOINT_API_USAGE, ENDPOINT_CREDITS, ENDPOINT_SCORING};
19
20pub struct FindEmailV2Builder<'a> {
38 client: &'a ZeroBounce,
39 first_name: Option<&'a str>,
40 domain: Option<&'a str>,
41 company_name: Option<&'a str>,
42 middle_name: Option<&'a str>,
43 last_name: Option<&'a str>,
44}
45
46pub struct DomainSearchV2Builder<'a> {
62 client: &'a ZeroBounce,
63 domain: Option<&'a str>,
64 company_name: Option<&'a str>,
65}
66
67impl ZeroBounce {
68
69 pub(crate) fn get_request_with_status<'a>(
74 &'a self,
75 url: String,
76 mut query_args: HashMap<&'a str, &'a str>,
77 message_only_is_failure: bool,
78 ) -> ZBResult<(u16, String)> {
79 self.require_key()?;
80 query_args.insert("api_key", self.api_key.as_str());
81 let response = self
82 .client
83 .get(crate::parse_request_url(&url)?)
84 .query(&query_args)
85 .send()?;
86 self.read_api_response_with_status(response, message_only_is_failure)
87 }
88
89 pub(crate) fn form_post_request_with_status<'a>(
91 &'a self,
92 url: String,
93 mut form_args: HashMap<&'a str, &'a str>,
94 ) -> ZBResult<(u16, String)> {
95 self.require_key()?;
96 form_args.insert("api_key", self.api_key.as_str());
97 let response = self
98 .client
99 .post(crate::parse_request_url(&url)?)
100 .form(&form_args)
101 .send()?;
102 self.read_api_response_with_status(response, false)
103 }
104
105 pub(crate) fn read_api_response_with_status(
107 &self,
108 response: reqwest::blocking::Response,
109 message_only_is_failure: bool,
110 ) -> ZBResult<(u16, String)> {
111 let (status, content_type, content) = Self::read_api_body(response)?;
112 crate::utility::http_error::ensure_json_api_body(status, &content_type, &content)
113 .map_err(|error| self.redact_error(error))?;
114 if message_only_is_failure {
115 crate::utility::http_error::reject_message_only_body(status, &content_type, &content)
116 .map_err(|error| self.redact_error(error))?;
117 }
118 Ok((status, content))
119 }
120
121 fn get_credits_from_body(status: u16, string_value: &str) -> ZBResult<i64> {
128 let body = parse_json_body_with_status::<serde_json::Value>(status, string_value)?;
129 match body.get("Credits") {
130 Some(serde_json::Value::String(credits)) => credits.parse::<i64>().ok(),
131 Some(serde_json::Value::Number(credits)) => credits.as_i64(),
132 _ => None,
133 }
134 .ok_or_else(|| ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE))
135 }
136
137 #[cfg(test)]
138 fn get_credits_from_string(string_value: String) -> ZBResult<i64> {
139 Self::get_credits_from_body(200, &string_value)
140 }
141
142 pub fn get_credits(&self) -> ZBResult<i64> {
143 let query_args = HashMap::new();
144
145 let (status, response_content) = self.get_request_with_status(
146 self.url_provider.url_of(ENDPOINT_CREDITS), query_args, false
147 )?;
148
149 Self::get_credits_from_body(status, &response_content)
150 }
151
152 pub fn get_api_usage(&self, start_date: NaiveDate, end_date: NaiveDate) -> ZBResult<ApiUsage> {
153 let start_date_str = start_date.format("%F").to_string();
154 let end_date_str = end_date.format("%F").to_string();
155 let query_args = HashMap::from([
156 ("start_date", start_date_str.as_str()),
157 ("end_date", end_date_str.as_str()),
158 ]);
159
160 let (status, response_content) = self.get_request_with_status(
161 self.url_provider.url_of(ENDPOINT_API_USAGE), query_args, false
162 )?;
163
164 let api_usage = parse_json_body_with_status::<ApiUsage>(status, &response_content)?;
165 Ok(api_usage)
166 }
167
168 pub fn get_api_usage_overall(&self) -> ZBResult<ApiUsage> {
169 let start_date = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
170 let end_date = Utc::now().naive_local().date();
171 self.get_api_usage(start_date, end_date)
172 }
173
174 pub fn get_activity_data(&self, email: &str) -> ZBResult<ActivityData> {
175 let query_args = HashMap::from([
176 ("email", email),
177 ]);
178
179 let (status, response_content) = self.get_request_with_status(
180 self.url_provider.url_of(ENDPOINT_ACTIVITY_DATA), query_args, false
181 )?;
182
183 let activity_data = crate::utility::http_error::parse_unless_message_beside_nulls::<ActivityData>(
184 status, &response_content, &["found", "active_in_days"],
185 )?;
186 Ok(activity_data)
187 }
188
189 pub fn score_email(&self, email: &str) -> ZBResult<ScoreEmailResponse> {
190 let query_args = HashMap::from([("email", email)]);
191
192 let (status, response_content) = self.get_request_with_status(
193 self.url_provider.url_of(ENDPOINT_SCORING),
194 query_args,
195 false,
196 )?;
197
198 let score = crate::utility::http_error::parse_unless_message_beside_nulls::<ScoreEmailResponse>(
199 status, &response_content, &["email", "score"],
200 )?;
201 Ok(score)
202 }
203
204 pub fn score_email_post(&self, email: &str) -> ZBResult<ScoreEmailResponse> {
205 let form_args = HashMap::from([("email", email)]);
206
207 let (status, response_content) = self.form_post_request_with_status(
208 self.url_provider.url_of(ENDPOINT_SCORING),
209 form_args,
210 )?;
211
212 let score = crate::utility::http_error::parse_unless_message_beside_nulls::<ScoreEmailResponse>(
213 status, &response_content, &["email", "score"],
214 )?;
215 Ok(score)
216 }
217
218 #[deprecated(
222 since = "1.2.0",
223 note = "Use `find_email_v2` instead. The new version supports both domain and company_name parameters."
224 )]
225 pub fn find_email(&self, domain: &str, first_name: &str, middle_name: &str, last_name: &str) -> ZBResult<FindEmailResponse> {
226 let mut query_args = HashMap::from([
227 ("domain", domain),
228 ]);
229 if !first_name.is_empty() {
230 query_args.insert("first_name", first_name);
231 }
232 if !middle_name.is_empty() {
233 query_args.insert("middle_name", middle_name);
234 }
235 if !last_name.is_empty() {
236 query_args.insert("last_name", last_name);
237 }
238
239 let (status, response_content) = self.get_request_with_status(
240 self.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args, true
241 )?;
242
243 let activity_data = parse_json_body_with_status::<FindEmailResponse>(status, &response_content)?;
244 Ok(activity_data)
245 }
246
247 pub fn find_email_v2(&self) -> FindEmailV2Builder<'_> {
279 FindEmailV2Builder {
280 client: self,
281 first_name: None,
282 domain: None,
283 company_name: None,
284 middle_name: None,
285 last_name: None,
286 }
287 }
288
289 #[deprecated(
293 since = "1.2.0",
294 note = "Use `domain_search_v2` instead. The new version supports both domain and company_name parameters."
295 )]
296 #[allow(deprecated)] pub fn domain_search(&self, domain: &str) -> ZBResult<FindEmailResponse> {
298 self.find_email(domain, "", "", "")
299 }
300
301 pub fn domain_search_v2(&self) -> DomainSearchV2Builder<'_> {
327 DomainSearchV2Builder {
328 client: self,
329 domain: None,
330 company_name: None,
331 }
332 }
333
334}
335
336impl<'a> FindEmailV2Builder<'a> {
337 pub fn first_name(mut self, name: &'a str) -> Self {
339 self.first_name = Some(name);
340 self
341 }
342
343 pub fn domain(mut self, domain: &'a str) -> Self {
345 self.domain = Some(domain);
346 self
347 }
348
349 pub fn company_name(mut self, company: &'a str) -> Self {
351 self.company_name = Some(company);
352 self
353 }
354
355 pub fn middle_name(mut self, name: &'a str) -> Self {
357 self.middle_name = Some(name);
358 self
359 }
360
361 pub fn last_name(mut self, name: &'a str) -> Self {
363 self.last_name = Some(name);
364 self
365 }
366
367 pub fn call(self) -> ZBResult<FindEmailResponseV2> {
369 if let Some("") = self.first_name {
372 return Err(ZBError::explicit("first_name cannot be empty"));
373 }
374
375 match (self.domain, self.company_name) {
377 (Some(d), None) => {
378 if d.is_empty() {
379 return Err(ZBError::explicit("domain cannot be empty"));
380 }
381 }
382 (None, Some(c)) => {
383 if c.is_empty() {
384 return Err(ZBError::explicit("company_name cannot be empty"));
385 }
386 }
387 (Some(_), Some(_)) => {
388 return Err(ZBError::explicit("exactly one of domain or company_name must be provided, not both"));
389 }
390 (None, None) => {
391 return Err(ZBError::explicit("either domain or company_name must be provided"));
392 }
393 }
394
395 let mut query_args = HashMap::new();
396
397 if let Some(first) = self.first_name {
398 query_args.insert("first_name", first);
399 }
400
401 if let Some(d) = self.domain {
402 query_args.insert("domain", d);
403 }
404
405 if let Some(c) = self.company_name {
406 query_args.insert("company_name", c);
407 }
408
409 if let Some(middle) = self.middle_name {
410 if !middle.is_empty() {
411 query_args.insert("middle_name", middle);
412 }
413 }
414
415 if let Some(last) = self.last_name {
416 if !last.is_empty() {
417 query_args.insert("last_name", last);
418 }
419 }
420
421 let (status, response_content) = self.client.get_request_with_status(
422 self.client.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args, true
423 )?;
424
425 let body = parse_json_body_with_status::<serde_json::Value>(status, &response_content)?;
428 if let Some(object) = body.as_object() {
429 const NAMES: [&str; 6] = [
430 "email",
431 "domain",
432 "email_confidence",
433 "company_name",
434 "did_you_mean",
435 "failure_reason",
436 ];
437 if crate::utility::http_error::object_has_message_key(object)
438 && !crate::utility::http_error::object_has_non_null_named_field(object, &NAMES)
439 {
440 return Err(ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE));
441 }
442 }
443 let find_email_response =
444 parse_json_body_with_status::<FindEmailResponseV2>(status, &response_content)?;
445 Ok(find_email_response)
446 }
447}
448
449impl<'a> DomainSearchV2Builder<'a> {
450 pub fn domain(mut self, domain: &'a str) -> Self {
452 self.domain = Some(domain);
453 self
454 }
455
456 pub fn company_name(mut self, company: &'a str) -> Self {
458 self.company_name = Some(company);
459 self
460 }
461
462 pub fn call(self) -> ZBResult<DomainSearchResponseV2> {
464 match (self.domain, self.company_name) {
466 (Some(d), None) => {
467 if d.is_empty() {
468 return Err(ZBError::explicit("domain cannot be empty"));
469 }
470 }
471 (None, Some(c)) => {
472 if c.is_empty() {
473 return Err(ZBError::explicit("company_name cannot be empty"));
474 }
475 }
476 (Some(_), Some(_)) => {
477 return Err(ZBError::explicit("exactly one of domain or company_name must be provided, not both"));
478 }
479 (None, None) => {
480 return Err(ZBError::explicit("either domain or company_name must be provided"));
481 }
482 }
483
484 let mut query_args = HashMap::new();
485
486 if let Some(d) = self.domain {
487 query_args.insert("domain", d);
488 }
489
490 if let Some(c) = self.company_name {
491 query_args.insert("company_name", c);
492 }
493
494 let (status, response_content) = self.client.get_request_with_status(
495 self.client.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args, true
496 )?;
497
498 let body = parse_json_body_with_status::<serde_json::Value>(status, &response_content)?;
503 let object = body.as_object();
504 let named = object.is_some_and(|object| {
505 DOMAIN_SEARCH_V2_FIELD_NAMES
506 .iter()
507 .any(|name| object.contains_key(*name))
508 });
509 let real = object.is_some_and(|object| {
510 crate::utility::http_error::object_has_non_null_named_field(
511 object,
512 &DOMAIN_SEARCH_V2_FIELD_NAMES,
513 )
514 });
515 let message = object.is_some_and(crate::utility::http_error::object_has_message_key);
516 if !named || (message && !real) {
518 return Err(ZBError::api(status, UNEXPECTED_JSON_SHAPE_MESSAGE));
519 }
520 let domain_search_response =
521 parse_json_body_with_status::<DomainSearchResponseV2>(status, &response_content)?;
522 Ok(domain_search_response)
523 }
524}
525
526#[cfg(test)]
527mod tests {
528 use crate::utility::mock_constants::CREDITS_RESPONSE_OK;
529 use crate::utility::mock_constants::CREDITS_RESPONSE_NEGATIVE;
530
531 use super::*;
532
533 #[test]
534 fn test_credits_negative() {
535 let credits = ZeroBounce::get_credits_from_string(CREDITS_RESPONSE_NEGATIVE.to_string());
536 assert!(credits.is_ok());
537
538 let amount = credits.unwrap();
539 assert_eq!(amount, -1);
540 }
541
542 #[test]
543 fn test_credits_ok() {
544 let credits = ZeroBounce::get_credits_from_string(CREDITS_RESPONSE_OK.to_string());
545 assert!(credits.is_ok());
546
547 let amount = credits.unwrap();
548 assert_eq!(amount, 123456);
549 }
550
551}