1use std::collections::HashMap;
2use std::io::Read;
3
4use reqwest::blocking::multipart::{Form, Part};
5use serde_json::Value;
6
7use serde::Deserialize;
8
9use crate::utility::structures::bulk::{ZBBulkResponse, ZBEmailFinderFileOptions, ZBFileFeedback};
10use crate::utility::structures::custom_deserialize::null_as_default;
11use crate::utility::{ZBError, ZBResult};
12use crate::ZeroBounce;
13
14fn bulk_api_root(bulk_url: &str) -> String {
15 let trimmed = bulk_url.trim_end_matches('/');
16 trimmed.strip_suffix("/v2").unwrap_or(trimmed).to_string()
17}
18
19fn post_bulk_root_form(
20 client: &ZeroBounce,
21 path: &str,
22 fields: HashMap<String, String>,
23) -> ZBResult<ZBFileFeedback> {
24 client.require_key()?;
25 let url = format!(
26 "{}/{}",
27 bulk_api_root(&client.url_provider.bulk_url),
28 path.trim_start_matches('/')
29 );
30 let mut form: HashMap<&str, String> = fields
31 .iter()
32 .map(|(k, v)| (k.as_str(), v.clone()))
33 .collect();
34 form.insert("api_key", client.api_key.clone());
35 let response = client
36 .client
37 .post(crate::parse_request_url(&url)?)
38 .form(&form)
39 .send()?;
40 let (status, body) = client.read_api_response_with_status(response, false)?;
41 crate::utility::http_error::parse_unless_message_beside_nulls(status, &body, &["success", "file_name", "file_id"])
42}
43
44fn bulk_root_file_job(
50 client: &ZeroBounce,
51 path: &str,
52 file_name: &str,
53 has_header_row: bool,
54 remove_duplicates: Option<bool>,
55 return_url: &str,
56) -> ZBResult<ZBFileFeedback> {
57 if file_name.trim().is_empty() {
58 return Err(ZBError::explicit("empty parameter: file_name"));
59 }
60 if return_url.trim().is_empty() {
61 return Err(ZBError::explicit("empty parameter: return_url"));
62 }
63
64 let mut fields: HashMap<String, String> = HashMap::new();
65 fields.insert("has_header_row".to_string(), has_header_row.to_string());
66 fields.insert("file_name".to_string(), file_name.to_string());
67 fields.insert("return_url".to_string(), return_url.to_string());
68 if let Some(remove_duplicates) = remove_duplicates {
69 fields.insert(
70 "remove_duplicates".to_string(),
71 remove_duplicates.to_string(),
72 );
73 }
74 post_bulk_root_form(client, path, fields)
75}
76
77#[derive(Deserialize, Debug)]
78pub struct S3ListFileEntry {
79 #[serde(deserialize_with = "null_as_default")]
80 pub name: String,
81 #[serde(deserialize_with = "null_as_default")]
82 pub size: i64,
83 #[serde(deserialize_with = "null_as_default")]
84 pub last_modified: String,
85}
86
87fn post_bulk_root_multipart(
88 client: &ZeroBounce,
89 url: String,
90 file_name: &str,
91 file_bytes: Vec<u8>,
92 fields: HashMap<String, String>,
93) -> ZBResult<ZBFileFeedback> {
94 client.require_key()?;
95 let mut form = Form::new()
96 .part(
97 "file",
98 Part::bytes(file_bytes)
99 .file_name(file_name.to_string())
100 .mime_str("text/csv")?,
101 )
102 .text("api_key", client.api_key.clone());
103 for (key, value) in fields {
104 form = form.text(key, value);
105 }
106 let response = client
107 .client
108 .post(crate::parse_request_url(&url)?)
109 .multipart(form)
110 .send()?;
111 let (status, body) = client.read_api_response_with_status(response, false)?;
112 crate::utility::http_error::parse_unless_message_beside_nulls(status, &body, &["success", "file_name", "file_id"])
113}
114
115fn bulk_root_url_of(client: &ZeroBounce, base: &str, endpoint: &str) -> String {
118 format!(
119 "{}/{}/{}",
120 bulk_api_root(&client.url_provider.bulk_url),
121 base,
122 endpoint
123 )
124}
125
126fn bulk_root_file_status(client: &ZeroBounce, base: &str, file_id: &str) -> ZBResult<String> {
127 let url = bulk_root_url_of(client, base, "filestatus");
128 let (status, body) =
129 client.get_request_with_status(url, HashMap::from([("file_id", file_id)]), false)?;
130 crate::utility::http_error::require_status_object_body(status, "", &body)
133 .map_err(|error| client.redact_error(error))?;
134 Ok(body)
135}
136
137fn bulk_root_result_fetch(
138 client: &ZeroBounce,
139 base: &str,
140 file_id: &str,
141) -> ZBResult<ZBBulkResponse> {
142 if file_id.trim().is_empty() {
143 return Err(ZBError::explicit("empty parameter: file_id"));
144 }
145 client.result_fetch_at(
146 bulk_root_url_of(client, base, "getfile"),
147 file_id,
148 None,
149 true,
150 )
151}
152
153fn bulk_root_result_delete(
154 client: &ZeroBounce,
155 base: &str,
156 file_id: &str,
157) -> ZBResult<ZBFileFeedback> {
158 if file_id.trim().is_empty() {
159 return Err(ZBError::explicit("empty parameter: file_id"));
160 }
161 client.result_delete_at(bulk_root_url_of(client, base, "deletefile"), file_id)
162}
163
164impl ZeroBounce {
165 pub fn send_email_finder_file(
171 &self,
172 domain_column: u32,
173 options: &ZBEmailFinderFileOptions,
174 file_name: &str,
175 mut reader: impl Read,
176 ) -> ZBResult<ZBFileFeedback> {
177 if domain_column == 0 {
178 return Err(ZBError::explicit("empty parameter: domain_column"));
179 }
180 if options.first_name_column.is_none() && options.full_name_column.is_none() {
181 return Err(ZBError::explicit(
182 "one of first_name_column or full_name_column is required",
183 ));
184 }
185 let mut bytes = Vec::new();
186 reader.read_to_end(&mut bytes)?;
187 let url = format!(
188 "{}/email-finder/sendfile",
189 bulk_api_root(&self.url_provider.bulk_url)
190 );
191 let mut fields = HashMap::from([("domain_column".to_string(), domain_column.to_string())]);
192 for (name, column) in [
193 ("first_name_column", options.first_name_column),
194 ("full_name_column", options.full_name_column),
195 ("middle_name_column", options.middle_name_column),
196 ("last_name_column", options.last_name_column),
197 ] {
198 if let Some(column) = column {
199 fields.insert(name.to_string(), column.to_string());
200 }
201 }
202 if let Some(has_header_row) = options.has_header_row {
203 fields.insert("has_header_row".to_string(), has_header_row.to_string());
204 }
205 post_bulk_root_multipart(self, url, file_name, bytes, fields)
206 }
207
208 pub fn email_finder_file_status(&self, file_id: &str) -> ZBResult<String> {
209 bulk_root_file_status(self, "email-finder", file_id)
210 }
211
212 pub fn email_finder_result_fetch(&self, file_id: &str) -> ZBResult<ZBBulkResponse> {
218 bulk_root_result_fetch(self, "email-finder", file_id)
219 }
220
221 pub fn email_finder_result_delete(&self, file_id: &str) -> ZBResult<ZBFileFeedback> {
223 bulk_root_result_delete(self, "email-finder", file_id)
224 }
225
226 pub fn domain_search_file_status(&self, file_id: &str) -> ZBResult<String> {
227 bulk_root_file_status(self, "domain-search", file_id)
228 }
229
230 pub fn domain_search_result_fetch(&self, file_id: &str) -> ZBResult<ZBBulkResponse> {
235 bulk_root_result_fetch(self, "domain-search", file_id)
236 }
237
238 pub fn domain_search_result_delete(&self, file_id: &str) -> ZBResult<ZBFileFeedback> {
240 bulk_root_result_delete(self, "domain-search", file_id)
241 }
242
243 pub fn send_evaluated_file(&self, file_id: &str) -> ZBResult<ZBFileFeedback> {
251 if file_id.trim().is_empty() {
252 return Err(ZBError::explicit("empty parameter: file_id"));
253 }
254 self.require_key()?;
255 let url = format!(
256 "{}/v2/send-evaluated-file/",
257 bulk_api_root(&self.url_provider.bulk_url)
258 );
259 let form = HashMap::from([
260 ("api_key", self.api_key.clone()),
261 ("file_id", file_id.to_string()),
262 ]);
263 let response = self
264 .client
265 .post(crate::parse_request_url(&url)?)
266 .form(&form)
267 .send()?;
268 let (status, body) = self.read_api_response_with_status(response, false)?;
269 crate::utility::http_error::parse_unless_message_beside_nulls(status, &body, &["success", "file_name", "file_id"])
270 }
271
272 pub fn send_domain_search_file(
276 &self,
277 domain_column: u32,
278 has_header_row: Option<bool>,
279 file_name: &str,
280 mut reader: impl Read,
281 ) -> ZBResult<ZBFileFeedback> {
282 if domain_column == 0 {
283 return Err(ZBError::explicit("empty parameter: domain_column"));
284 }
285 let mut bytes = Vec::new();
286 reader.read_to_end(&mut bytes)?;
287 let url = format!(
288 "{}/domain-search/sendfile",
289 bulk_api_root(&self.url_provider.bulk_url)
290 );
291 let mut fields = HashMap::from([("domain_column".to_string(), domain_column.to_string())]);
292 if let Some(has_header_row) = has_header_row {
293 fields.insert("has_header_row".to_string(), has_header_row.to_string());
294 }
295 post_bulk_root_multipart(self, url, file_name, bytes, fields)
296 }
297
298 pub fn send_list_evaluator_file(
299 &self,
300 email_address_column: u32,
301 file_name: &str,
302 mut reader: impl Read,
303 ) -> ZBResult<ZBFileFeedback> {
304 if email_address_column == 0 {
305 return Err(ZBError::explicit("empty parameter: email_address_column"));
306 }
307 let mut bytes = Vec::new();
308 reader.read_to_end(&mut bytes)?;
309 let url = self.url_provider.list_evaluator_url_of("/");
310 post_bulk_root_multipart(
311 self,
312 url,
313 file_name,
314 bytes,
315 HashMap::from([(
316 "email_address_column".to_string(),
317 email_address_column.to_string(),
318 )]),
319 )
320 }
321
322 pub fn get_list_evaluator_result(&self, file_id: &str) -> ZBResult<Value> {
323 if file_id.trim().is_empty() {
324 return Err(ZBError::explicit("empty parameter: file_id"));
325 }
326 let url = self.url_provider.list_evaluator_url_of(&format!(
327 "/{}/",
328 crate::utility::encode_path_segment(file_id)
329 ));
330 let (status, body) = self.get_request_with_status(url, HashMap::new(), false)?;
331 crate::utility::http_error::parse_json_body_with_status(status, &body)
332 }
333
334 pub fn add_filter(&self, rule: &str, target: &str, value: &str) -> ZBResult<Value> {
335 let (status, body) = self.form_post_request_with_status(
336 self.url_provider.url_of("/filters/add"),
337 HashMap::from([("rule", rule), ("target", target), ("value", value)]),
338 )?;
339 crate::utility::http_error::parse_json_body_with_status(status, &body)
340 }
341
342 pub fn list_filters(&self, use_post: bool) -> ZBResult<Value> {
343 let (status, body) = if use_post {
344 self.form_post_request_with_status(
345 self.url_provider.url_of("/filters/list"),
346 HashMap::new(),
347 )?
348 } else {
349 self.get_request_with_status(
350 self.url_provider.url_of("/filters/list"),
351 HashMap::new(),
352 false,
353 )?
354 };
355 crate::utility::http_error::parse_json_body_with_status(status, &body)
356 }
357
358 pub fn delete_filter(&self, rule: &str, target: &str, value: &str) -> ZBResult<Value> {
359 let (status, body) = self.form_post_request_with_status(
360 self.url_provider.url_of("/filters/delete"),
361 HashMap::from([("rule", rule), ("target", target), ("value", value)]),
362 )?;
363 crate::utility::http_error::parse_json_body_with_status(status, &body)
364 }
365
366 pub fn list_s3_files(
367 &self,
368 bucket: Option<&str>,
369 search: Option<&str>,
370 ) -> ZBResult<Vec<S3ListFileEntry>> {
371 let url = format!("{}/listS3files", bulk_api_root(&self.url_provider.bulk_url));
372 let mut params: HashMap<&str, &str> = HashMap::new();
373 if let Some(bucket) = bucket {
374 if !bucket.trim().is_empty() {
375 params.insert("bucket", bucket);
376 }
377 }
378 if let Some(search) = search {
379 if !search.trim().is_empty() {
380 params.insert("search", search);
381 }
382 }
383 let (status, body) = self.get_request_with_status(url, params, false)?;
384 crate::utility::http_error::parse_json_body_with_status(status, &body)
385 }
386
387 pub fn validate_s3_file(
391 &self,
392 file_name: &str,
393 has_header_row: bool,
394 remove_duplicates: Option<bool>,
395 return_url: &str,
396 ) -> ZBResult<ZBFileFeedback> {
397 bulk_root_file_job(
398 self,
399 "validateS3file",
400 file_name,
401 has_header_row,
402 remove_duplicates,
403 return_url,
404 )
405 }
406
407 pub fn score_s3_file(
409 &self,
410 file_name: &str,
411 has_header_row: bool,
412 remove_duplicates: Option<bool>,
413 return_url: &str,
414 ) -> ZBResult<ZBFileFeedback> {
415 bulk_root_file_job(
416 self,
417 "scoreS3file",
418 file_name,
419 has_header_row,
420 remove_duplicates,
421 return_url,
422 )
423 }
424
425 pub fn export_s3_file(
430 &self,
431 file_id: &str,
432 export_bucket: Option<&str>,
433 ) -> ZBResult<ZBFileFeedback> {
434 if file_id.trim().is_empty() {
435 return Err(ZBError::explicit("empty parameter: file_id"));
436 }
437 let mut fields = HashMap::from([("file_id".to_string(), file_id.to_string())]);
438 if let Some(export_bucket) = export_bucket {
439 if export_bucket.trim().is_empty() {
440 return Err(ZBError::explicit("empty parameter: export_bucket"));
441 }
442 fields.insert("export_bucket".to_string(), export_bucket.to_string());
443 }
444 post_bulk_root_form(self, "exportS3file", fields)
445 }
446
447 pub fn email_finder_s3_file(
451 &self,
452 file_name: &str,
453 has_header_row: bool,
454 remove_duplicates: Option<bool>,
455 return_url: &str,
456 ) -> ZBResult<ZBFileFeedback> {
457 bulk_root_file_job(
458 self,
459 "emailFinderS3file",
460 file_name,
461 has_header_row,
462 remove_duplicates,
463 return_url,
464 )
465 }
466
467 pub fn domain_search_s3_file(
469 &self,
470 file_name: &str,
471 has_header_row: bool,
472 remove_duplicates: Option<bool>,
473 return_url: &str,
474 ) -> ZBResult<ZBFileFeedback> {
475 bulk_root_file_job(
476 self,
477 "domainSearchS3file",
478 file_name,
479 has_header_row,
480 remove_duplicates,
481 return_url,
482 )
483 }
484
485 pub fn validate_sftp_file(
492 &self,
493 file_name: &str,
494 has_header_row: bool,
495 remove_duplicates: Option<bool>,
496 return_url: &str,
497 ) -> ZBResult<ZBFileFeedback> {
498 bulk_root_file_job(
499 self,
500 "validateSFTPfile",
501 file_name,
502 has_header_row,
503 remove_duplicates,
504 return_url,
505 )
506 }
507
508 pub fn score_sftp_file(
512 &self,
513 file_name: &str,
514 has_header_row: bool,
515 remove_duplicates: Option<bool>,
516 return_url: &str,
517 ) -> ZBResult<ZBFileFeedback> {
518 bulk_root_file_job(
519 self,
520 "scoreSFTPfile",
521 file_name,
522 has_header_row,
523 remove_duplicates,
524 return_url,
525 )
526 }
527
528 pub fn email_finder_sftp_file(
530 &self,
531 file_name: &str,
532 has_header_row: bool,
533 remove_duplicates: Option<bool>,
534 return_url: &str,
535 ) -> ZBResult<ZBFileFeedback> {
536 bulk_root_file_job(
537 self,
538 "emailFinderSFTPfile",
539 file_name,
540 has_header_row,
541 remove_duplicates,
542 return_url,
543 )
544 }
545
546 pub fn domain_search_sftp_file(
548 &self,
549 file_name: &str,
550 has_header_row: bool,
551 remove_duplicates: Option<bool>,
552 return_url: &str,
553 ) -> ZBResult<ZBFileFeedback> {
554 bulk_root_file_job(
555 self,
556 "domainSearchSFTPfile",
557 file_name,
558 has_header_row,
559 remove_duplicates,
560 return_url,
561 )
562 }
563
564 pub fn export_sftp_file(
570 &self,
571 file_id: &str,
572 export_path: Option<&str>,
573 ) -> ZBResult<ZBFileFeedback> {
574 if file_id.trim().is_empty() {
575 return Err(ZBError::explicit("empty parameter: file_id"));
576 }
577 let mut fields = HashMap::from([("file_id".to_string(), file_id.to_string())]);
578 if let Some(export_path) = export_path {
579 if export_path.trim().is_empty() {
580 return Err(ZBError::explicit("empty parameter: export_path"));
581 }
582 fields.insert("export_path".to_string(), export_path.to_string());
583 }
584 post_bulk_root_form(self, "exportSFTPfile", fields)
585 }
586}