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 = self.url_provider.list_evaluator_url_of("/");
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 = self.url_provider.list_evaluator_url_of(&format!(
317            "/{}/",
318            crate::utility::encode_path_segment(file_id)
319        ));
320        let body = self.generic_get_request(url, HashMap::new())?;
321        crate::utility::http_error::parse_json_body(&body)
322    }
323
324    pub fn add_filter(&self, rule: &str, target: &str, value: &str) -> ZBResult<Value> {
325        let body = self.generic_form_post_request(
326            self.url_provider.url_of("/filters/add"),
327            HashMap::from([("rule", rule), ("target", target), ("value", value)]),
328        )?;
329        Ok(from_str(&body)?)
330    }
331
332    pub fn list_filters(&self, use_post: bool) -> ZBResult<Value> {
333        let body = if use_post {
334            self.generic_form_post_request(
335                self.url_provider.url_of("/filters/list"),
336                HashMap::new(),
337            )?
338        } else {
339            self.generic_get_request(self.url_provider.url_of("/filters/list"), HashMap::new())?
340        };
341        Ok(from_str(&body)?)
342    }
343
344    pub fn delete_filter(&self, rule: &str, target: &str, value: &str) -> ZBResult<Value> {
345        let body = self.generic_form_post_request(
346            self.url_provider.url_of("/filters/delete"),
347            HashMap::from([("rule", rule), ("target", target), ("value", value)]),
348        )?;
349        Ok(from_str(&body)?)
350    }
351
352    pub fn list_s3_files(
353        &self,
354        bucket: Option<&str>,
355        search: Option<&str>,
356    ) -> ZBResult<Vec<S3ListFileEntry>> {
357        let url = format!("{}/listS3files", bulk_api_root(&self.url_provider.bulk_url));
358        let mut params: HashMap<&str, &str> = HashMap::new();
359        if let Some(bucket) = bucket {
360            if !bucket.trim().is_empty() {
361                params.insert("bucket", bucket);
362            }
363        }
364        if let Some(search) = search {
365            if !search.trim().is_empty() {
366                params.insert("search", search);
367            }
368        }
369        let body = self.generic_get_request(url, params)?;
370        Ok(from_str(&body)?)
371    }
372
373    /// Validate a file in your Amazon S3 bucket (POST /validateS3file).
374    ///
375    /// `file_name` is the full path as returned by [`list_s3_files`](Self::list_s3_files).
376    pub fn validate_s3_file(
377        &self,
378        file_name: &str,
379        has_header_row: bool,
380        remove_duplicates: Option<bool>,
381        return_url: &str,
382    ) -> ZBResult<ZBFileFeedback> {
383        bulk_root_file_job(
384            self,
385            "validateS3file",
386            file_name,
387            has_header_row,
388            remove_duplicates,
389            return_url,
390        )
391    }
392
393    /// AI score a file in your Amazon S3 bucket (POST /scoreS3file).
394    pub fn score_s3_file(
395        &self,
396        file_name: &str,
397        has_header_row: bool,
398        remove_duplicates: Option<bool>,
399        return_url: &str,
400    ) -> ZBResult<ZBFileFeedback> {
401        bulk_root_file_job(
402            self,
403            "scoreS3file",
404            file_name,
405            has_header_row,
406            remove_duplicates,
407            return_url,
408        )
409    }
410
411    /// Export a validated or scored file back to Amazon S3 (POST /exportS3file).
412    ///
413    /// Pass `None` to use the export bucket from your ZeroBounce settings. Note the
414    /// field name: [`export_sftp_file`](Self::export_sftp_file) takes `export_path`.
415    pub fn export_s3_file(
416        &self,
417        file_id: &str,
418        export_bucket: Option<&str>,
419    ) -> ZBResult<ZBFileFeedback> {
420        if file_id.trim().is_empty() {
421            return Err(ZBError::explicit("empty parameter: file_id"));
422        }
423        let mut fields = HashMap::from([("file_id".to_string(), file_id.to_string())]);
424        if let Some(export_bucket) = export_bucket {
425            if export_bucket.trim().is_empty() {
426                return Err(ZBError::explicit("empty parameter: export_bucket"));
427            }
428            fields.insert("export_bucket".to_string(), export_bucket.to_string());
429        }
430        post_bulk_root_form(self, "exportS3file", fields)
431    }
432
433    /// Run the email finder on a file in your Amazon S3 bucket (POST /emailFinderS3file).
434    ///
435    /// `file_name` is the full path as returned by [`list_s3_files`](Self::list_s3_files).
436    pub fn email_finder_s3_file(
437        &self,
438        file_name: &str,
439        has_header_row: bool,
440        remove_duplicates: Option<bool>,
441        return_url: &str,
442    ) -> ZBResult<ZBFileFeedback> {
443        bulk_root_file_job(
444            self,
445            "emailFinderS3file",
446            file_name,
447            has_header_row,
448            remove_duplicates,
449            return_url,
450        )
451    }
452
453    /// Run domain search on a file in your Amazon S3 bucket (POST /domainSearchS3file).
454    pub fn domain_search_s3_file(
455        &self,
456        file_name: &str,
457        has_header_row: bool,
458        remove_duplicates: Option<bool>,
459        return_url: &str,
460    ) -> ZBResult<ZBFileFeedback> {
461        bulk_root_file_job(
462            self,
463            "domainSearchS3file",
464            file_name,
465            has_header_row,
466            remove_duplicates,
467            return_url,
468        )
469    }
470
471    // SFTP / FTP bulk. The server, path and protocol come from your ZeroBounce settings.
472
473    /// Validate a file from your SFTP/FTP server (POST /validateSFTPfile).
474    ///
475    /// LIVE: `file_name` is required here too, although the docs list it as
476    /// optional for this one endpoint.
477    pub fn validate_sftp_file(
478        &self,
479        file_name: &str,
480        has_header_row: bool,
481        remove_duplicates: Option<bool>,
482        return_url: &str,
483    ) -> ZBResult<ZBFileFeedback> {
484        bulk_root_file_job(
485            self,
486            "validateSFTPfile",
487            file_name,
488            has_header_row,
489            remove_duplicates,
490            return_url,
491        )
492    }
493
494    /// Score a file from your SFTP/FTP server (POST /scoreSFTPfile).
495    ///
496    /// `file_name` is a plain name such as `my_file.txt`.
497    pub fn score_sftp_file(
498        &self,
499        file_name: &str,
500        has_header_row: bool,
501        remove_duplicates: Option<bool>,
502        return_url: &str,
503    ) -> ZBResult<ZBFileFeedback> {
504        bulk_root_file_job(
505            self,
506            "scoreSFTPfile",
507            file_name,
508            has_header_row,
509            remove_duplicates,
510            return_url,
511        )
512    }
513
514    /// Run the email finder on a file from your SFTP/FTP server (POST /emailFinderSFTPfile).
515    pub fn email_finder_sftp_file(
516        &self,
517        file_name: &str,
518        has_header_row: bool,
519        remove_duplicates: Option<bool>,
520        return_url: &str,
521    ) -> ZBResult<ZBFileFeedback> {
522        bulk_root_file_job(
523            self,
524            "emailFinderSFTPfile",
525            file_name,
526            has_header_row,
527            remove_duplicates,
528            return_url,
529        )
530    }
531
532    /// Run domain search on a file from your SFTP/FTP server (POST /domainSearchSFTPfile).
533    pub fn domain_search_sftp_file(
534        &self,
535        file_name: &str,
536        has_header_row: bool,
537        remove_duplicates: Option<bool>,
538        return_url: &str,
539    ) -> ZBResult<ZBFileFeedback> {
540        bulk_root_file_job(
541            self,
542            "domainSearchSFTPfile",
543            file_name,
544            has_header_row,
545            remove_duplicates,
546            return_url,
547        )
548    }
549
550    /// Export a validated or scored file back to your SFTP/FTP server (POST /exportSFTPfile).
551    ///
552    /// Note the field name: this endpoint takes `export_path`, not the `export_bucket`
553    /// that [`export_s3_file`](Self::export_s3_file) uses. Pass `None` to use the export
554    /// path from your ZeroBounce settings.
555    pub fn export_sftp_file(
556        &self,
557        file_id: &str,
558        export_path: Option<&str>,
559    ) -> ZBResult<ZBFileFeedback> {
560        if file_id.trim().is_empty() {
561            return Err(ZBError::explicit("empty parameter: file_id"));
562        }
563        let mut fields = HashMap::from([("file_id".to_string(), file_id.to_string())]);
564        if let Some(export_path) = export_path {
565            if export_path.trim().is_empty() {
566                return Err(ZBError::explicit("empty parameter: export_path"));
567            }
568            fields.insert("export_path".to_string(), export_path.to_string());
569        }
570        post_bulk_root_form(self, "exportSFTPfile", fields)
571    }
572}