Skip to main content

zero_bounce/api/
priority3.rs

1use std::collections::HashMap;
2use std::io::Read;
3
4use reqwest::blocking::multipart::{Form, Part};
5use serde_json::{from_str, Value};
6
7use serde::Deserialize;
8
9use crate::utility::structures::bulk::{ZBBulkResponse, ZBEmailFinderFileOptions, ZBFileFeedback};
10use crate::utility::{ZBError, ZBResult};
11use crate::ZeroBounce;
12
13fn bulk_api_root(bulk_url: &str) -> String {
14    let trimmed = bulk_url.trim_end_matches('/');
15    trimmed.strip_suffix("/v2").unwrap_or(trimmed).to_string()
16}
17
18fn post_bulk_root_form(
19    client: &ZeroBounce,
20    path: &str,
21    fields: HashMap<String, String>,
22) -> ZBResult<ZBFileFeedback> {
23    client.require_key()?;
24    let url = format!(
25        "{}/{}",
26        bulk_api_root(&client.url_provider.bulk_url),
27        path.trim_start_matches('/')
28    );
29    let mut form: HashMap<&str, String> = fields
30        .iter()
31        .map(|(k, v)| (k.as_str(), v.clone()))
32        .collect();
33    form.insert("api_key", client.api_key.clone());
34    let response = client
35        .client
36        .post(crate::parse_request_url(&url)?)
37        .form(&form)
38        .send()?;
39    let body = client.read_api_response(response)?;
40    crate::utility::http_error::parse_json_body(&body)
41}
42
43/// POST one of the documented S3 / SFTP file jobs on the bulkapi root.
44///
45/// LIVE: `file_name` and `return_url` are required on every one of these,
46/// including `validateSFTPfile`, which the docs list `file_name` as optional
47/// for. Without either the API answers "This field is required".
48fn bulk_root_file_job(
49    client: &ZeroBounce,
50    path: &str,
51    file_name: &str,
52    has_header_row: bool,
53    remove_duplicates: Option<bool>,
54    return_url: &str,
55) -> ZBResult<ZBFileFeedback> {
56    if file_name.trim().is_empty() {
57        return Err(ZBError::explicit("empty parameter: file_name"));
58    }
59    if return_url.trim().is_empty() {
60        return Err(ZBError::explicit("empty parameter: return_url"));
61    }
62
63    let mut fields: HashMap<String, String> = HashMap::new();
64    fields.insert("has_header_row".to_string(), has_header_row.to_string());
65    fields.insert("file_name".to_string(), file_name.to_string());
66    fields.insert("return_url".to_string(), return_url.to_string());
67    if let Some(remove_duplicates) = remove_duplicates {
68        fields.insert(
69            "remove_duplicates".to_string(),
70            remove_duplicates.to_string(),
71        );
72    }
73    post_bulk_root_form(client, path, fields)
74}
75
76#[derive(Deserialize, Debug)]
77pub struct S3ListFileEntry {
78    pub name: String,
79    pub size: i64,
80    pub last_modified: String,
81}
82
83fn post_bulk_root_multipart(
84    client: &ZeroBounce,
85    url: String,
86    file_name: &str,
87    file_bytes: Vec<u8>,
88    fields: HashMap<String, String>,
89) -> ZBResult<ZBFileFeedback> {
90    client.require_key()?;
91    let mut form = Form::new()
92        .part(
93            "file",
94            Part::bytes(file_bytes)
95                .file_name(file_name.to_string())
96                .mime_str("text/csv")?,
97        )
98        .text("api_key", client.api_key.clone());
99    for (key, value) in fields {
100        form = form.text(key, value);
101    }
102    let response = client
103        .client
104        .post(crate::parse_request_url(&url)?)
105        .multipart(form)
106        .send()?;
107    let body = client.read_api_response(response)?;
108    crate::utility::http_error::parse_json_body(&body)
109}
110
111/// `{bulk root}/{base}/{endpoint}` for the finder and domain search file APIs,
112/// which sit on the bulk host without the `/v2` path the other bulk APIs use.
113fn bulk_root_url_of(client: &ZeroBounce, base: &str, endpoint: &str) -> String {
114    format!(
115        "{}/{}/{}",
116        bulk_api_root(&client.url_provider.bulk_url),
117        base,
118        endpoint
119    )
120}
121
122fn bulk_root_file_status(client: &ZeroBounce, base: &str, file_id: &str) -> ZBResult<String> {
123    let url = bulk_root_url_of(client, base, "filestatus");
124    client.generic_get_request(url, HashMap::from([("file_id", file_id)]))
125}
126
127fn bulk_root_result_fetch(
128    client: &ZeroBounce,
129    base: &str,
130    file_id: &str,
131) -> ZBResult<ZBBulkResponse> {
132    if file_id.trim().is_empty() {
133        return Err(ZBError::explicit("empty parameter: file_id"));
134    }
135    client.result_fetch_at(
136        bulk_root_url_of(client, base, "getfile"),
137        file_id,
138        None,
139        true,
140    )
141}
142
143fn bulk_root_result_delete(
144    client: &ZeroBounce,
145    base: &str,
146    file_id: &str,
147) -> ZBResult<ZBFileFeedback> {
148    if file_id.trim().is_empty() {
149        return Err(ZBError::explicit("empty parameter: file_id"));
150    }
151    client.result_delete_at(bulk_root_url_of(client, base, "deletefile"), file_id)
152}
153
154impl ZeroBounce {
155    /// Submit a file to the bulk email finder (POST /email-finder/sendfile).
156    ///
157    /// `domain_column` is required and 1-based. Either `first_name_column` or
158    /// `full_name_column` must be set on `options`: the API has no way to guess a
159    /// person from a domain alone and rejects a file that carries neither.
160    pub fn send_email_finder_file(
161        &self,
162        domain_column: u32,
163        options: &ZBEmailFinderFileOptions,
164        file_name: &str,
165        mut reader: impl Read,
166    ) -> ZBResult<ZBFileFeedback> {
167        if domain_column == 0 {
168            return Err(ZBError::explicit("empty parameter: domain_column"));
169        }
170        if options.first_name_column.is_none() && options.full_name_column.is_none() {
171            return Err(ZBError::explicit(
172                "one of first_name_column or full_name_column is required",
173            ));
174        }
175        let mut bytes = Vec::new();
176        reader.read_to_end(&mut bytes)?;
177        let url = format!(
178            "{}/email-finder/sendfile",
179            bulk_api_root(&self.url_provider.bulk_url)
180        );
181        let mut fields = HashMap::from([("domain_column".to_string(), domain_column.to_string())]);
182        for (name, column) in [
183            ("first_name_column", options.first_name_column),
184            ("full_name_column", options.full_name_column),
185            ("middle_name_column", options.middle_name_column),
186            ("last_name_column", options.last_name_column),
187        ] {
188            if let Some(column) = column {
189                fields.insert(name.to_string(), column.to_string());
190            }
191        }
192        if let Some(has_header_row) = options.has_header_row {
193            fields.insert("has_header_row".to_string(), has_header_row.to_string());
194        }
195        post_bulk_root_multipart(self, url, file_name, bytes, fields)
196    }
197
198    pub fn email_finder_file_status(&self, file_id: &str) -> ZBResult<String> {
199        bulk_root_file_status(self, "email-finder", file_id)
200    }
201
202    /// Download a finished bulk email finder file (GET /email-finder/getfile).
203    ///
204    /// On success the bytes come back as [`ZBBulkResponse::Content`]. A JSON body,
205    /// including an HTTP 200 carrying `{"success": false}`, is an error, the same
206    /// as [`bulk_validation_result_fetch`](Self::bulk_validation_result_fetch).
207    pub fn email_finder_result_fetch(&self, file_id: &str) -> ZBResult<ZBBulkResponse> {
208        bulk_root_result_fetch(self, "email-finder", file_id)
209    }
210
211    /// Delete a bulk email finder file and its results (GET /email-finder/deletefile).
212    pub fn email_finder_result_delete(&self, file_id: &str) -> ZBResult<ZBFileFeedback> {
213        bulk_root_result_delete(self, "email-finder", file_id)
214    }
215
216    pub fn domain_search_file_status(&self, file_id: &str) -> ZBResult<String> {
217        bulk_root_file_status(self, "domain-search", file_id)
218    }
219
220    /// Download a finished bulk domain search file (GET /domain-search/getfile).
221    ///
222    /// Same success and error rules as
223    /// [`email_finder_result_fetch`](Self::email_finder_result_fetch).
224    pub fn domain_search_result_fetch(&self, file_id: &str) -> ZBResult<ZBBulkResponse> {
225        bulk_root_result_fetch(self, "domain-search", file_id)
226    }
227
228    /// Delete a bulk domain search file and its results (GET /domain-search/deletefile).
229    pub fn domain_search_result_delete(&self, file_id: &str) -> ZBResult<ZBFileFeedback> {
230        bulk_root_result_delete(self, "domain-search", file_id)
231    }
232
233    /// Submit a finished evaluation for validation. `POST /v2/send-evaluated-file/`
234    ///
235    /// LIVE: this takes the list evaluator's `file_id` as a form field, not the
236    /// file upload the docs describe — an upload is rejected with
237    /// "file_id: This field is required". It returns a new validation job's
238    /// `file_id`, which answers "File cannot be found" for a short while after
239    /// it is accepted.
240    pub fn send_evaluated_file(&self, file_id: &str) -> ZBResult<ZBFileFeedback> {
241        if file_id.trim().is_empty() {
242            return Err(ZBError::explicit("empty parameter: file_id"));
243        }
244        self.require_key()?;
245        let url = format!(
246            "{}/v2/send-evaluated-file/",
247            bulk_api_root(&self.url_provider.bulk_url)
248        );
249        let form = HashMap::from([
250            ("api_key", self.api_key.clone()),
251            ("file_id", file_id.to_string()),
252        ]);
253        let response = self
254            .client
255            .post(crate::parse_request_url(&url)?)
256            .form(&form)
257            .send()?;
258        let body = self.read_api_response(response)?;
259        crate::utility::http_error::parse_json_body(&body)
260    }
261
262    /// Submit a file to bulk domain search (POST /domain-search/sendfile).
263    ///
264    /// `has_header_row` is omitted when `None`, so the account default applies.
265    pub fn send_domain_search_file(
266        &self,
267        domain_column: u32,
268        has_header_row: Option<bool>,
269        file_name: &str,
270        mut reader: impl Read,
271    ) -> ZBResult<ZBFileFeedback> {
272        if domain_column == 0 {
273            return Err(ZBError::explicit("empty parameter: domain_column"));
274        }
275        let mut bytes = Vec::new();
276        reader.read_to_end(&mut bytes)?;
277        let url = format!(
278            "{}/domain-search/sendfile",
279            bulk_api_root(&self.url_provider.bulk_url)
280        );
281        let mut fields = HashMap::from([("domain_column".to_string(), domain_column.to_string())]);
282        if let Some(has_header_row) = has_header_row {
283            fields.insert("has_header_row".to_string(), has_header_row.to_string());
284        }
285        post_bulk_root_multipart(self, url, file_name, bytes, fields)
286    }
287
288    pub fn send_list_evaluator_file(
289        &self,
290        email_address_column: u32,
291        file_name: &str,
292        mut reader: impl Read,
293    ) -> ZBResult<ZBFileFeedback> {
294        if email_address_column == 0 {
295            return Err(ZBError::explicit("empty parameter: email_address_column"));
296        }
297        let mut bytes = Vec::new();
298        reader.read_to_end(&mut bytes)?;
299        let url = format!("{}/", self.url_provider.list_evaluator_url);
300        post_bulk_root_multipart(
301            self,
302            url,
303            file_name,
304            bytes,
305            HashMap::from([(
306                "email_address_column".to_string(),
307                email_address_column.to_string(),
308            )]),
309        )
310    }
311
312    pub fn get_list_evaluator_result(&self, file_id: &str) -> ZBResult<Value> {
313        if file_id.trim().is_empty() {
314            return Err(ZBError::explicit("empty parameter: file_id"));
315        }
316        let url = format!(
317            "{}/{}/",
318            self.url_provider.list_evaluator_url,
319            crate::utility::encode_path_segment(file_id)
320        );
321        let body = self.generic_get_request(url, HashMap::new())?;
322        crate::utility::http_error::parse_json_body(&body)
323    }
324
325    pub fn add_filter(&self, rule: &str, target: &str, value: &str) -> ZBResult<Value> {
326        let body = self.generic_form_post_request(
327            self.url_provider.url_of("/filters/add"),
328            HashMap::from([("rule", rule), ("target", target), ("value", value)]),
329        )?;
330        Ok(from_str(&body)?)
331    }
332
333    pub fn list_filters(&self, use_post: bool) -> ZBResult<Value> {
334        let body = if use_post {
335            self.generic_form_post_request(
336                self.url_provider.url_of("/filters/list"),
337                HashMap::new(),
338            )?
339        } else {
340            self.generic_get_request(self.url_provider.url_of("/filters/list"), HashMap::new())?
341        };
342        Ok(from_str(&body)?)
343    }
344
345    pub fn delete_filter(&self, rule: &str, target: &str, value: &str) -> ZBResult<Value> {
346        let body = self.generic_form_post_request(
347            self.url_provider.url_of("/filters/delete"),
348            HashMap::from([("rule", rule), ("target", target), ("value", value)]),
349        )?;
350        Ok(from_str(&body)?)
351    }
352
353    pub fn list_s3_files(
354        &self,
355        bucket: Option<&str>,
356        search: Option<&str>,
357    ) -> ZBResult<Vec<S3ListFileEntry>> {
358        let url = format!("{}/listS3files", bulk_api_root(&self.url_provider.bulk_url));
359        let mut params: HashMap<&str, &str> = HashMap::new();
360        if let Some(bucket) = bucket {
361            if !bucket.trim().is_empty() {
362                params.insert("bucket", bucket);
363            }
364        }
365        if let Some(search) = search {
366            if !search.trim().is_empty() {
367                params.insert("search", search);
368            }
369        }
370        let body = self.generic_get_request(url, params)?;
371        Ok(from_str(&body)?)
372    }
373
374    /// Validate a file in your Amazon S3 bucket (POST /validateS3file).
375    ///
376    /// `file_name` is the full path as returned by [`list_s3_files`](Self::list_s3_files).
377    pub fn validate_s3_file(
378        &self,
379        file_name: &str,
380        has_header_row: bool,
381        remove_duplicates: Option<bool>,
382        return_url: &str,
383    ) -> ZBResult<ZBFileFeedback> {
384        bulk_root_file_job(
385            self,
386            "validateS3file",
387            file_name,
388            has_header_row,
389            remove_duplicates,
390            return_url,
391        )
392    }
393
394    /// AI score a file in your Amazon S3 bucket (POST /scoreS3file).
395    pub fn score_s3_file(
396        &self,
397        file_name: &str,
398        has_header_row: bool,
399        remove_duplicates: Option<bool>,
400        return_url: &str,
401    ) -> ZBResult<ZBFileFeedback> {
402        bulk_root_file_job(
403            self,
404            "scoreS3file",
405            file_name,
406            has_header_row,
407            remove_duplicates,
408            return_url,
409        )
410    }
411
412    /// Export a validated or scored file back to Amazon S3 (POST /exportS3file).
413    ///
414    /// Pass `None` to use the export bucket from your ZeroBounce settings. Note the
415    /// field name: [`export_sftp_file`](Self::export_sftp_file) takes `export_path`.
416    pub fn export_s3_file(
417        &self,
418        file_id: &str,
419        export_bucket: Option<&str>,
420    ) -> ZBResult<ZBFileFeedback> {
421        if file_id.trim().is_empty() {
422            return Err(ZBError::explicit("empty parameter: file_id"));
423        }
424        let mut fields = HashMap::from([("file_id".to_string(), file_id.to_string())]);
425        if let Some(export_bucket) = export_bucket {
426            if export_bucket.trim().is_empty() {
427                return Err(ZBError::explicit("empty parameter: export_bucket"));
428            }
429            fields.insert("export_bucket".to_string(), export_bucket.to_string());
430        }
431        post_bulk_root_form(self, "exportS3file", fields)
432    }
433
434    /// Run the email finder on a file in your Amazon S3 bucket (POST /emailFinderS3file).
435    ///
436    /// `file_name` is the full path as returned by [`list_s3_files`](Self::list_s3_files).
437    pub fn email_finder_s3_file(
438        &self,
439        file_name: &str,
440        has_header_row: bool,
441        remove_duplicates: Option<bool>,
442        return_url: &str,
443    ) -> ZBResult<ZBFileFeedback> {
444        bulk_root_file_job(
445            self,
446            "emailFinderS3file",
447            file_name,
448            has_header_row,
449            remove_duplicates,
450            return_url,
451        )
452    }
453
454    /// Run domain search on a file in your Amazon S3 bucket (POST /domainSearchS3file).
455    pub fn domain_search_s3_file(
456        &self,
457        file_name: &str,
458        has_header_row: bool,
459        remove_duplicates: Option<bool>,
460        return_url: &str,
461    ) -> ZBResult<ZBFileFeedback> {
462        bulk_root_file_job(
463            self,
464            "domainSearchS3file",
465            file_name,
466            has_header_row,
467            remove_duplicates,
468            return_url,
469        )
470    }
471
472    // SFTP / FTP bulk. The server, path and protocol come from your ZeroBounce settings.
473
474    /// Validate a file from your SFTP/FTP server (POST /validateSFTPfile).
475    ///
476    /// LIVE: `file_name` is required here too, although the docs list it as
477    /// optional for this one endpoint.
478    pub fn validate_sftp_file(
479        &self,
480        file_name: &str,
481        has_header_row: bool,
482        remove_duplicates: Option<bool>,
483        return_url: &str,
484    ) -> ZBResult<ZBFileFeedback> {
485        bulk_root_file_job(
486            self,
487            "validateSFTPfile",
488            file_name,
489            has_header_row,
490            remove_duplicates,
491            return_url,
492        )
493    }
494
495    /// Score a file from your SFTP/FTP server (POST /scoreSFTPfile).
496    ///
497    /// `file_name` is a plain name such as `my_file.txt`.
498    pub fn score_sftp_file(
499        &self,
500        file_name: &str,
501        has_header_row: bool,
502        remove_duplicates: Option<bool>,
503        return_url: &str,
504    ) -> ZBResult<ZBFileFeedback> {
505        bulk_root_file_job(
506            self,
507            "scoreSFTPfile",
508            file_name,
509            has_header_row,
510            remove_duplicates,
511            return_url,
512        )
513    }
514
515    /// Run the email finder on a file from your SFTP/FTP server (POST /emailFinderSFTPfile).
516    pub fn email_finder_sftp_file(
517        &self,
518        file_name: &str,
519        has_header_row: bool,
520        remove_duplicates: Option<bool>,
521        return_url: &str,
522    ) -> ZBResult<ZBFileFeedback> {
523        bulk_root_file_job(
524            self,
525            "emailFinderSFTPfile",
526            file_name,
527            has_header_row,
528            remove_duplicates,
529            return_url,
530        )
531    }
532
533    /// Run domain search on a file from your SFTP/FTP server (POST /domainSearchSFTPfile).
534    pub fn domain_search_sftp_file(
535        &self,
536        file_name: &str,
537        has_header_row: bool,
538        remove_duplicates: Option<bool>,
539        return_url: &str,
540    ) -> ZBResult<ZBFileFeedback> {
541        bulk_root_file_job(
542            self,
543            "domainSearchSFTPfile",
544            file_name,
545            has_header_row,
546            remove_duplicates,
547            return_url,
548        )
549    }
550
551    /// Export a validated or scored file back to your SFTP/FTP server (POST /exportSFTPfile).
552    ///
553    /// Note the field name: this endpoint takes `export_path`, not the `export_bucket`
554    /// that [`export_s3_file`](Self::export_s3_file) uses. Pass `None` to use the export
555    /// path from your ZeroBounce settings.
556    pub fn export_sftp_file(
557        &self,
558        file_id: &str,
559        export_path: Option<&str>,
560    ) -> ZBResult<ZBFileFeedback> {
561        if file_id.trim().is_empty() {
562            return Err(ZBError::explicit("empty parameter: file_id"));
563        }
564        let mut fields = HashMap::from([("file_id".to_string(), file_id.to_string())]);
565        if let Some(export_path) = export_path {
566            if export_path.trim().is_empty() {
567                return Err(ZBError::explicit("empty parameter: export_path"));
568            }
569            fields.insert("export_path".to_string(), export_path.to_string());
570        }
571        post_bulk_root_form(self, "exportSFTPfile", fields)
572    }
573}