Skip to main content

zero_bounce/api/
bulk.rs

1use std::collections::HashMap;
2
3use crate::utility::bulk_get_file::should_treat_get_file_body_as_error;
4use crate::utility::format_get_file_error_message;
5use crate::utility::structures::bulk::{
6    ZBBulkResponse, ZBFile, ZBFileFeedback, ZBFileStatus, ZBGetFileOptions,
7};
8use crate::utility::{ZBError, ZBResult};
9use crate::utility::{
10    ENDPOINT_FILE_DELETE, ENDPOINT_FILE_RESULT, ENDPOINT_FILE_SEND, ENDPOINT_FILE_STATUS,
11};
12use crate::utility::{
13    ENDPOINT_SCORING_DELETE, ENDPOINT_SCORING_RESULT, ENDPOINT_SCORING_SEND,
14    ENDPOINT_SCORING_STATUS,
15};
16use crate::ZeroBounce;
17
18impl ZeroBounce {
19    fn generic_file_submit(&self, endpoint: &str, zb_file: &ZBFile) -> ZBResult<ZBFileFeedback> {
20        self.require_key()?;
21        let include_person_columns = endpoint == ENDPOINT_FILE_SEND;
22        let mut multi_part_form = zb_file
23            .generate_multipart_with(include_person_columns)?
24            .text("api_key", self.api_key.clone());
25
26        if endpoint == ENDPOINT_FILE_SEND {
27            if let Some(v) = zb_file.allow_phase_2 {
28                multi_part_form = multi_part_form.text("allow_phase_2", v.to_string());
29            }
30        }
31
32        let url = crate::parse_request_url(&self.url_provider.bulk_url_of(endpoint))?;
33        let response = self.client.post(url).multipart(multi_part_form).send()?;
34
35        let response_content = self.read_api_response(response)?;
36        crate::utility::http_error::parse_json_body(&response_content)
37    }
38
39    fn generic_file_status_check(&self, endpoint: &str, file_id: &str) -> ZBResult<ZBFileStatus> {
40        let query_args = HashMap::from([("file_id", file_id)]);
41
42        let response_content =
43            self.generic_get_request(self.url_provider.bulk_url_of(endpoint), query_args)?;
44
45        crate::utility::http_error::parse_json_body(&response_content)
46    }
47
48    /// Bulk `getfile` against a full URL.
49    ///
50    /// The bulk email finder and domain search live on the bulk host without the
51    /// `/v2` path, so they build their own URL and share this body.
52    pub(crate) fn result_fetch_at(
53        &self,
54        url: String,
55        file_id: &str,
56        options: Option<&ZBGetFileOptions>,
57        is_scoring: bool,
58    ) -> ZBResult<ZBBulkResponse> {
59        self.require_key()?;
60        let mut query: Vec<(&str, String)> = vec![
61            ("api_key", self.api_key.clone()),
62            ("file_id", file_id.to_string()),
63        ];
64        if let Some(opts) = options {
65            if let Some(dt) = &opts.download_type {
66                query.push(("download_type", dt.clone()));
67            }
68            if !is_scoring {
69                if let Some(ad) = opts.activity_data {
70                    query.push((
71                        "activity_data",
72                        if ad { "true".into() } else { "false".into() },
73                    ));
74                }
75            }
76        }
77
78        let url = crate::parse_request_url(&url)?;
79        let response = self.client.get(url).query(&query).send()?;
80
81        // From here on a response arrived, so every error carries its status
82        // (`ZBError::ApiError`) and `status_code()` can tell a Cloudflare 403
83        // from an API 400/404.
84        let status = response.status();
85        let content_type = response
86            .headers()
87            .get(reqwest::header::CONTENT_TYPE)
88            .ok_or_else(|| ZBError::api(status.as_u16(), "content type not specified in response"))?
89            .to_str()
90            .map_err(|e| ZBError::api(status.as_u16(), e.to_string()))?
91            .to_string();
92
93        let body_bytes = crate::utility::read_limited(
94            response,
95            crate::utility::MAX_GETFILE_BYTES,
96            "getfile response exceeds size limit",
97        )?;
98        let body_str = String::from_utf8_lossy(&body_bytes).into_owned();
99
100        if crate::utility::http_error::body_looks_like_html(&body_str)
101            || crate::utility::http_error::content_type_is_html(&content_type)
102            || !status.is_success()
103        {
104            return Err(ZBError::api(
105                status.as_u16(),
106                crate::utility::http_error::message_from_body(
107                    status.as_u16(),
108                    &content_type,
109                    &body_str,
110                ),
111            ));
112        }
113
114        if should_treat_get_file_body_as_error(&body_str, &content_type) {
115            let message = crate::utility::http_error::strip_error_prefix(
116                &format_get_file_error_message(body_str.trim()),
117            );
118            if message.is_empty()
119                || message.len() > 500
120                || crate::utility::http_error::body_looks_like_html(&message)
121            {
122                return Err(ZBError::api(
123                    status.as_u16(),
124                    crate::utility::http_error::message_from_body(
125                        status.as_u16(),
126                        &content_type,
127                        &body_str,
128                    ),
129                ));
130            }
131            return Err(ZBError::api(status.as_u16(), message));
132        }
133
134        Ok(ZBBulkResponse::Content(body_bytes.into()))
135    }
136
137    fn generic_result_fetch(
138        &self,
139        endpoint: &str,
140        file_id: &str,
141        options: Option<&ZBGetFileOptions>,
142        is_scoring: bool,
143    ) -> ZBResult<ZBBulkResponse> {
144        self.result_fetch_at(
145            self.url_provider.bulk_url_of(endpoint),
146            file_id,
147            options,
148            is_scoring,
149        )
150    }
151
152    /// Bulk `deletefile` against a full URL. See [`result_fetch_at`](Self::result_fetch_at).
153    pub(crate) fn result_delete_at(&self, url: String, file_id: &str) -> ZBResult<ZBFileFeedback> {
154        let query_args = HashMap::from([("file_id", file_id)]);
155
156        let response_content = self.generic_get_request(url, query_args)?;
157
158        crate::utility::http_error::parse_json_body(&response_content)
159    }
160
161    fn generic_result_delete(&self, endpoint: &str, file_id: &str) -> ZBResult<ZBFileFeedback> {
162        self.result_delete_at(self.url_provider.bulk_url_of(endpoint), file_id)
163    }
164
165    pub fn bulk_validation_file_submit(&self, zb_file: &ZBFile) -> ZBResult<ZBFileFeedback> {
166        self.generic_file_submit(ENDPOINT_FILE_SEND, zb_file)
167    }
168
169    pub fn bulk_validation_file_status_check(&self, file_id: &str) -> ZBResult<ZBFileStatus> {
170        self.generic_file_status_check(ENDPOINT_FILE_STATUS, file_id)
171    }
172
173    pub fn bulk_validation_result_fetch(&self, file_id: &str) -> ZBResult<ZBBulkResponse> {
174        self.generic_result_fetch(ENDPOINT_FILE_RESULT, file_id, None, false)
175    }
176
177    /// Bulk validation getfile with optional v2 query parameters (`download_type`, `activity_data`).
178    pub fn bulk_validation_result_fetch_with_options(
179        &self,
180        file_id: &str,
181        options: &ZBGetFileOptions,
182    ) -> ZBResult<ZBBulkResponse> {
183        self.generic_result_fetch(ENDPOINT_FILE_RESULT, file_id, Some(options), false)
184    }
185
186    pub fn bulk_validation_result_delete(&self, file_id: &str) -> ZBResult<ZBFileFeedback> {
187        self.generic_result_delete(ENDPOINT_FILE_DELETE, file_id)
188    }
189
190    pub fn ai_scoring_file_submit(&self, zb_file: &ZBFile) -> ZBResult<ZBFileFeedback> {
191        self.generic_file_submit(ENDPOINT_SCORING_SEND, zb_file)
192    }
193
194    pub fn ai_scoring_file_status_check(&self, file_id: &str) -> ZBResult<ZBFileStatus> {
195        self.generic_file_status_check(ENDPOINT_SCORING_STATUS, file_id)
196    }
197
198    pub fn ai_scoring_result_fetch(&self, file_id: &str) -> ZBResult<ZBBulkResponse> {
199        self.generic_result_fetch(ENDPOINT_SCORING_RESULT, file_id, None, true)
200    }
201
202    /// AI scoring getfile with optional `download_type` (`activity_data` is not sent).
203    pub fn ai_scoring_result_fetch_with_options(
204        &self,
205        file_id: &str,
206        options: &ZBGetFileOptions,
207    ) -> ZBResult<ZBBulkResponse> {
208        self.generic_result_fetch(ENDPOINT_SCORING_RESULT, file_id, Some(options), true)
209    }
210
211    pub fn ai_scoring_result_delete(&self, file_id: &str) -> ZBResult<ZBFileFeedback> {
212        self.generic_result_delete(ENDPOINT_SCORING_DELETE, file_id)
213    }
214}