Skip to main content

zero_bounce/api/
mod.rs

1pub mod bulk;
2pub mod inbox_placement;
3pub mod priority3;
4pub mod validation;
5
6use std::collections::HashMap;
7
8use chrono::{NaiveDate, Utc};
9use serde_json::from_str;
10
11pub use crate::ZeroBounce;
12use crate::utility::structures::generic::{FindEmailResponse, FindEmailResponseV2, DomainSearchResponseV2};
13use crate::utility::{ZBError, ZBResult, ENDPOINT_EMAIL_FINDER};
14use crate::utility::structures::{ActivityData, ApiUsage};
15use crate::utility::structures::generic::ScoreEmailResponse;
16use crate::utility::{ENDPOINT_ACTIVITY_DATA, ENDPOINT_API_USAGE, ENDPOINT_CREDITS, ENDPOINT_SCORING};
17
18/// Builder for the `find_email_v2` API call.
19/// 
20/// # Example
21/// ```no_run
22/// use zero_bounce::ZeroBounce;
23/// use zero_bounce::utility::ZBResult;
24/// 
25/// # fn main() -> ZBResult<()> {
26/// let zb = ZeroBounce::new("your_api_key");
27/// let result = zb.find_email_v2()
28///     .first_name("John")
29///     .domain("example.com")
30///     .last_name("Doe")
31///     .call()?;
32/// # Ok(())
33/// # }
34/// ```
35pub struct FindEmailV2Builder<'a> {
36    client: &'a ZeroBounce,
37    first_name: Option<&'a str>,
38    domain: Option<&'a str>,
39    company_name: Option<&'a str>,
40    middle_name: Option<&'a str>,
41    last_name: Option<&'a str>,
42}
43
44/// Builder for the `domain_search_v2` API call.
45/// 
46/// # Example
47/// ```no_run
48/// use zero_bounce::ZeroBounce;
49/// use zero_bounce::utility::ZBResult;
50/// 
51/// # fn main() -> ZBResult<()> {
52/// let zb = ZeroBounce::new("your_api_key");
53/// let result = zb.domain_search_v2()
54///     .domain("example.com")
55///     .call()?;
56/// # Ok(())
57/// # }
58/// ```
59pub struct DomainSearchV2Builder<'a> {
60    client: &'a ZeroBounce,
61    domain: Option<&'a str>,
62    company_name: Option<&'a str>,
63}
64
65impl ZeroBounce {
66
67    fn get_credits_from_string(string_value: String) -> ZBResult<i64> {
68        from_str::<serde_json::Value>(string_value.as_ref())?
69            .get("Credits")
70            .and_then(serde_json::Value::as_str)
71            .map(str::parse::<i64>)
72            .ok_or(ZBError::explicit("credits value not in json"))?
73            .map_err(ZBError::IntParseError)
74    }
75
76    pub fn get_credits(&self) -> ZBResult<i64> {
77        let query_args = HashMap::new();
78
79        let response_content = self.generic_get_request(
80            self.url_provider.url_of(ENDPOINT_CREDITS), query_args
81        )?;
82
83        Self::get_credits_from_string(response_content)
84    }
85
86    pub fn get_api_usage(&self, start_date: NaiveDate, end_date: NaiveDate) -> ZBResult<ApiUsage> {
87        let start_date_str = start_date.format("%F").to_string();
88        let end_date_str = end_date.format("%F").to_string();
89        let query_args = HashMap::from([
90            ("start_date", start_date_str.as_str()),
91            ("end_date", end_date_str.as_str()),
92        ]);
93
94        let response_content = self.generic_get_request(
95            self.url_provider.url_of(ENDPOINT_API_USAGE), query_args
96        )?;
97
98        let api_usage = from_str::<ApiUsage>(&response_content)?;
99        Ok(api_usage)
100    }
101
102    pub fn get_api_usage_overall(&self) -> ZBResult<ApiUsage> {
103        let start_date = NaiveDate::from_ymd_opt(2000, 1, 1).unwrap();
104        let end_date = Utc::now().naive_local().date();
105        self.get_api_usage(start_date, end_date)
106    }
107
108    pub fn get_activity_data(&self, email: &str) -> ZBResult<ActivityData> {
109        let query_args = HashMap::from([
110            ("email", email),
111        ]);
112
113        let response_content = self.generic_get_request(
114            self.url_provider.url_of(ENDPOINT_ACTIVITY_DATA), query_args
115        )?;
116
117        let activity_data = from_str::<ActivityData>(&response_content)?;
118        Ok(activity_data)
119    }
120
121    pub fn score_email(&self, email: &str) -> ZBResult<ScoreEmailResponse> {
122        let query_args = HashMap::from([("email", email)]);
123
124        let response_content = self.generic_get_request(
125            self.url_provider.url_of(ENDPOINT_SCORING),
126            query_args,
127        )?;
128
129        let score = from_str::<ScoreEmailResponse>(&response_content)?;
130        Ok(score)
131    }
132
133    pub fn score_email_post(&self, email: &str) -> ZBResult<ScoreEmailResponse> {
134        let form_args = HashMap::from([("email", email)]);
135
136        let response_content = self.generic_form_post_request(
137            self.url_provider.url_of(ENDPOINT_SCORING),
138            form_args,
139        )?;
140
141        let score = from_str::<ScoreEmailResponse>(&response_content)?;
142        Ok(score)
143    }
144
145    /// Deprecated: Use `find_email_v2` instead.
146    /// 
147    /// This function is kept for backward compatibility but will be removed in a future version.
148    #[deprecated(
149        since = "1.2.0",
150        note = "Use `find_email_v2` instead. The new version supports both domain and company_name parameters."
151    )]
152    pub fn find_email(&self, domain: &str, first_name: &str, middle_name: &str, last_name: &str) -> ZBResult<FindEmailResponse> {
153        let mut query_args = HashMap::from([
154            ("domain", domain),
155        ]);
156        if !first_name.is_empty() {
157            query_args.insert("first_name", first_name);
158        }
159        if !middle_name.is_empty() {
160            query_args.insert("middle_name", middle_name);
161        }
162        if !last_name.is_empty() {
163            query_args.insert("last_name", last_name);
164        }
165
166        let response_content = self.finder_get_request(
167            self.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args
168        )?;
169
170        let activity_data = from_str::<FindEmailResponse>(&response_content)?;
171        Ok(activity_data)
172    }
173
174    /// Find an email address using either a domain or company name.
175    /// 
176    /// Returns a builder that allows you to set parameters using method chaining.
177    /// 
178    /// # Requirements
179    /// - Exactly one of `domain` or `company_name` must be provided (XOR requirement)
180    /// - `first_name` is optional; without it the API answers with the domain's
181    ///   address formats, the same as `domain_search_v2`
182    /// 
183    /// # Example
184    /// ```no_run
185    /// use zero_bounce::ZeroBounce;
186    /// use zero_bounce::utility::ZBResult;
187    /// 
188    /// # fn main() -> ZBResult<()> {
189    /// let zb = ZeroBounce::new("your_api_key");
190    /// // Using domain
191    /// let result = zb.find_email_v2()
192    ///     .first_name("John")
193    ///     .domain("example.com")
194    ///     .last_name("Doe")
195    ///     .call()?;
196    /// // Or using company name
197    /// let result = zb.find_email_v2()
198    ///     .first_name("John")
199    ///     .company_name("Example Inc")
200    ///     .last_name("Doe")
201    ///     .call()?;
202    /// # Ok(())
203    /// # }
204    /// ```
205    pub fn find_email_v2(&self) -> FindEmailV2Builder<'_> {
206        FindEmailV2Builder {
207            client: self,
208            first_name: None,
209            domain: None,
210            company_name: None,
211            middle_name: None,
212            last_name: None,
213        }
214    }
215
216    /// Deprecated: Use `domain_search_v2` instead.
217    /// 
218    /// This function is kept for backward compatibility but will be removed in a future version.
219    #[deprecated(
220        since = "1.2.0",
221        note = "Use `domain_search_v2` instead. The new version supports both domain and company_name parameters."
222    )]
223    #[allow(deprecated)] // This method uses deprecated find_email, which is expected
224    pub fn domain_search(&self, domain: &str) -> ZBResult<FindEmailResponse> {
225        self.find_email(domain, "", "", "")
226    }
227
228    /// Search for email formats using either a domain or company name.
229    /// 
230    /// Returns a builder that allows you to set parameters using method chaining.
231    /// 
232    /// # Requirements
233    /// Exactly one of `domain` or `company_name` must be provided (XOR requirement).
234    /// 
235    /// # Example
236    /// ```no_run
237    /// use zero_bounce::ZeroBounce;
238    /// use zero_bounce::utility::ZBResult;
239    /// 
240    /// # fn main() -> ZBResult<()> {
241    /// let zb = ZeroBounce::new("your_api_key");
242    /// // Using domain
243    /// let result = zb.domain_search_v2()
244    ///     .domain("example.com")
245    ///     .call()?;
246    /// // Or using company name
247    /// let result = zb.domain_search_v2()
248    ///     .company_name("Example Inc")
249    ///     .call()?;
250    /// # Ok(())
251    /// # }
252    /// ```
253    pub fn domain_search_v2(&self) -> DomainSearchV2Builder<'_> {
254        DomainSearchV2Builder {
255            client: self,
256            domain: None,
257            company_name: None,
258        }
259    }
260
261}
262
263impl<'a> FindEmailV2Builder<'a> {
264    /// Set the first name (optional).
265    pub fn first_name(mut self, name: &'a str) -> Self {
266        self.first_name = Some(name);
267        self
268    }
269
270    /// Set the domain name (exactly one of domain or company_name must be provided).
271    pub fn domain(mut self, domain: &'a str) -> Self {
272        self.domain = Some(domain);
273        self
274    }
275
276    /// Set the company name (exactly one of domain or company_name must be provided).
277    pub fn company_name(mut self, company: &'a str) -> Self {
278        self.company_name = Some(company);
279        self
280    }
281
282    /// Set the middle name (optional).
283    pub fn middle_name(mut self, name: &'a str) -> Self {
284        self.middle_name = Some(name);
285        self
286    }
287
288    /// Set the last name (optional).
289    pub fn last_name(mut self, name: &'a str) -> Self {
290        self.last_name = Some(name);
291        self
292    }
293
294    /// Execute the API call and return the result.
295    pub fn call(self) -> ZBResult<FindEmailResponseV2> {
296        // first_name is optional: /guessformat answers with the domain's formats
297        // when no name is given. Setting it to an empty string is still a mistake.
298        if let Some("") = self.first_name {
299            return Err(ZBError::explicit("first_name cannot be empty"));
300        }
301
302        // Validate XOR requirement: exactly one of domain or company_name must be provided
303        match (self.domain, self.company_name) {
304            (Some(d), None) => {
305                if d.is_empty() {
306                    return Err(ZBError::explicit("domain cannot be empty"));
307                }
308            }
309            (None, Some(c)) => {
310                if c.is_empty() {
311                    return Err(ZBError::explicit("company_name cannot be empty"));
312                }
313            }
314            (Some(_), Some(_)) => {
315                return Err(ZBError::explicit("exactly one of domain or company_name must be provided, not both"));
316            }
317            (None, None) => {
318                return Err(ZBError::explicit("either domain or company_name must be provided"));
319            }
320        }
321
322        let mut query_args = HashMap::new();
323
324        if let Some(first) = self.first_name {
325            query_args.insert("first_name", first);
326        }
327
328        if let Some(d) = self.domain {
329            query_args.insert("domain", d);
330        }
331
332        if let Some(c) = self.company_name {
333            query_args.insert("company_name", c);
334        }
335
336        if let Some(middle) = self.middle_name {
337            if !middle.is_empty() {
338                query_args.insert("middle_name", middle);
339            }
340        }
341
342        if let Some(last) = self.last_name {
343            if !last.is_empty() {
344                query_args.insert("last_name", last);
345            }
346        }
347
348        let response_content = self.client.finder_get_request(
349            self.client.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args
350        )?;
351
352        let find_email_response = from_str::<FindEmailResponseV2>(&response_content)?;
353        Ok(find_email_response)
354    }
355}
356
357impl<'a> DomainSearchV2Builder<'a> {
358    /// Set the domain name (exactly one of domain or company_name must be provided).
359    pub fn domain(mut self, domain: &'a str) -> Self {
360        self.domain = Some(domain);
361        self
362    }
363
364    /// Set the company name (exactly one of domain or company_name must be provided).
365    pub fn company_name(mut self, company: &'a str) -> Self {
366        self.company_name = Some(company);
367        self
368    }
369
370    /// Execute the API call and return the result.
371    pub fn call(self) -> ZBResult<DomainSearchResponseV2> {
372        // Validate XOR requirement: exactly one of domain or company_name must be provided
373        match (self.domain, self.company_name) {
374            (Some(d), None) => {
375                if d.is_empty() {
376                    return Err(ZBError::explicit("domain cannot be empty"));
377                }
378            }
379            (None, Some(c)) => {
380                if c.is_empty() {
381                    return Err(ZBError::explicit("company_name cannot be empty"));
382                }
383            }
384            (Some(_), Some(_)) => {
385                return Err(ZBError::explicit("exactly one of domain or company_name must be provided, not both"));
386            }
387            (None, None) => {
388                return Err(ZBError::explicit("either domain or company_name must be provided"));
389            }
390        }
391
392        let mut query_args = HashMap::new();
393
394        if let Some(d) = self.domain {
395            query_args.insert("domain", d);
396        }
397
398        if let Some(c) = self.company_name {
399            query_args.insert("company_name", c);
400        }
401
402        let response_content = self.client.finder_get_request(
403            self.client.url_provider.url_of(ENDPOINT_EMAIL_FINDER), query_args
404        )?;
405
406        let domain_search_response = from_str::<DomainSearchResponseV2>(&response_content)?;
407        Ok(domain_search_response)
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use crate::utility::mock_constants::CREDITS_RESPONSE_OK;
414    use crate::utility::mock_constants::CREDITS_RESPONSE_NEGATIVE;
415
416    use super::*;
417
418    #[test]
419    fn test_credits_negative() {
420        let credits = ZeroBounce::get_credits_from_string(CREDITS_RESPONSE_NEGATIVE.to_string());
421        assert!(credits.is_ok());
422
423        let amount = credits.unwrap();
424        assert_eq!(amount, -1);
425    }
426
427    #[test]
428    fn test_credits_ok() {
429        let credits = ZeroBounce::get_credits_from_string(CREDITS_RESPONSE_OK.to_string());
430        assert!(credits.is_ok());
431
432        let amount = credits.unwrap();
433        assert_eq!(amount, 123456);
434    }
435
436}