1use std::collections::HashMap;
9use std::time::Duration;
10
11use chrono::NaiveDate;
12use serde_json::{Map, Value};
13
14use crate::utility::http_error::message_from_body;
15use crate::utility::{ZBError, ZBResult};
16
17const DEFAULT_BASE_URL: &str = "https://warmup-api.zerobounce.net";
18const BASE_PATH: &str = "/api/v1/warmup";
19
20const ANY_TEAM_ID: i64 = 1;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26#[non_exhaustive]
27pub enum OnboardingModel {
28 SelfManaged,
30 ZbManaged,
32}
33
34impl OnboardingModel {
35 fn as_str(self) -> &'static str {
36 match self {
37 OnboardingModel::SelfManaged => "self_managed",
38 OnboardingModel::ZbManaged => "zb_managed",
39 }
40 }
41}
42
43#[derive(Debug, Clone, Default)]
45pub struct EmailContent {
46 pub types_of_emails: Vec<String>,
48 pub industry: Option<String>,
49 pub company_name: Option<String>,
50 pub website: Option<String>,
51}
52
53#[derive(Debug, Clone, Default)]
55pub struct ManagedSending {
56 pub timezone_offset: Option<i32>,
58 pub warmup_start_date: Option<NaiveDate>,
59 pub daily_limit: Option<u32>,
60}
61
62const EMAIL_TYPES: [&str; 3] = ["transactional", "newsletter", "marketing"];
63
64#[derive(Debug)]
65pub struct ZeroBounceWarmup {
66 api_key: String,
67 root: String,
68 client: reqwest::blocking::Client,
69}
70
71impl ZeroBounceWarmup {
72 pub fn new(api_key: &str) -> ZBResult<Self> {
74 Self::with_base_url(api_key, DEFAULT_BASE_URL)
75 }
76
77 pub fn with_base_url(api_key: &str, base_url: &str) -> ZBResult<Self> {
79 if api_key.trim().is_empty() {
80 return Err(ZBError::explicit("api_key is required"));
81 }
82 if api_key != api_key.trim() || api_key.chars().any(|c| c.is_control()) {
85 return Err(ZBError::explicit(
86 "api_key has surrounding whitespace or control characters",
87 ));
88 }
89 crate::parse_request_url(base_url)
92 .map_err(|_| ZBError::explicit("base_url must be an https:// URL"))?;
93 Ok(ZeroBounceWarmup {
94 api_key: api_key.to_string(),
95 root: format!("{}{BASE_PATH}", base_url.trim_end_matches('/')),
96 client: reqwest::blocking::Client::builder()
97 .timeout(Duration::from_secs(120))
98 .redirect(reqwest::redirect::Policy::none())
99 .build()
100 .unwrap_or_else(|_| reqwest::blocking::Client::default()),
101 })
102 }
103
104 fn redact(&self, text: &str, secrets: &[&str]) -> String {
108 let mut value = text.to_string();
109 for secret in std::iter::once(self.api_key.as_str()).chain(secrets.iter().copied()) {
110 if secret.is_empty() {
111 continue;
112 }
113 value = value.replace(secret, "***");
114 }
115 value
116 }
117
118 fn send(
119 &self,
120 method: &str,
121 path: &str,
122 query: &HashMap<&str, String>,
123 body: Option<&Value>,
124 secrets: &[&str],
125 ) -> ZBResult<(u16, String, String)> {
126 let url = crate::parse_request_url(&format!("{}{path}", self.root))?;
127 let mut request = match method {
128 "POST" => self.client.post(url),
129 "PUT" => self.client.put(url),
130 "DELETE" => self.client.delete(url),
131 _ => self.client.get(url),
132 }
133 .header("API-Key", self.api_key.as_str())
134 .header(reqwest::header::ACCEPT, "application/json")
135 .query(query);
136
137 if let Some(body) = body {
138 let encoded = serde_json::to_string(body)
141 .map_err(|_| ZBError::explicit("Invalid parameter: request body"))?;
142 request = request
143 .header(reqwest::header::CONTENT_TYPE, "application/json")
144 .body(encoded);
145 }
146
147 let response = request
148 .send()
149 .map_err(|error| ZBError::ExplicitError(self.redact(&error.to_string(), secrets)))?;
150 let status = response.status().as_u16();
151 let content_type = response
152 .headers()
153 .get(reqwest::header::CONTENT_TYPE)
154 .and_then(|value| value.to_str().ok())
155 .unwrap_or("")
156 .to_string();
157 let max_bytes = if content_type.starts_with("text/csv") {
158 crate::utility::MAX_GETFILE_BYTES
159 } else {
160 crate::utility::MAX_JSON_RESPONSE_BYTES
161 };
162 let body = crate::utility::read_limited(
163 response,
164 max_bytes,
165 "response body exceeds size limit",
166 )
167 .map_err(|error| ZBError::ExplicitError(self.redact(&error.to_string(), secrets)))?;
168 let text = String::from_utf8_lossy(&body).into_owned();
169
170 if (300..400).contains(&status) {
171 return Err(ZBError::api(
172 status,
173 "ZeroBounce returned a redirect, which this client does not follow.",
174 ));
175 }
176 if status > 299 {
177 return Err(ZBError::api(
178 status,
179 self.redact(&message_from_body(status, &content_type, &text), secrets),
180 ));
181 }
182 Ok((status, content_type, text))
183 }
184
185 fn json(
188 &self,
189 method: &str,
190 path: &str,
191 query: &HashMap<&str, String>,
192 body: Option<&Value>,
193 secrets: &[&str],
194 ) -> ZBResult<Option<Value>> {
195 let (status, content_type, text) = self.send(method, path, query, body, secrets)?;
196 if status == 204 || text.trim().is_empty() {
197 return Ok(None);
198 }
199 match serde_json::from_str::<Value>(&text) {
200 Ok(value) => Ok(Some(value)),
201 Err(_) => Err(ZBError::api(
202 status,
203 self.redact(&message_from_body(status, &content_type, &text), secrets),
204 )),
205 }
206 }
207
208 fn get(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<Option<Value>> {
209 self.json("GET", path, query, None, &[])
210 }
211
212 fn write(&self, method: &str, path: &str, body: Value) -> ZBResult<Option<Value>> {
213 self.json(method, path, &HashMap::new(), Some(&body), &[])
214 }
215
216 fn csv(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<String> {
218 let (status, content_type, text) = self.send("GET", path, query, None, &[])?;
219 if text.trim().is_empty() || content_type.to_ascii_lowercase().contains("application/json")
220 {
221 return Err(ZBError::api(
222 status,
223 message_from_body(status, &content_type, &text),
224 ));
225 }
226 Ok(text)
227 }
228
229 fn required<'a>(value: &'a str, name: &str) -> ZBResult<&'a str> {
232 if value.trim().is_empty() {
233 return Err(ZBError::ExplicitError(format!("{name} is required")));
234 }
235 Ok(value)
236 }
237
238 fn in_range(value: i64, low: i64, high: i64, name: &str) -> ZBResult<i64> {
239 if !(low..=high).contains(&value) {
240 return Err(ZBError::ExplicitError(format!(
241 "{name} must be {low} to {high}"
242 )));
243 }
244 Ok(value)
245 }
246
247 fn engagement_body(
248 c_from: &str,
249 reply_pct: i64,
250 important_pct: i64,
251 click_pct: i64,
252 ) -> ZBResult<Value> {
253 Self::required(c_from, "c_from")?;
254 Self::in_range(reply_pct, 5, 45, "reply_pct")?;
255 Self::in_range(important_pct, 5, 40, "important_pct")?;
256 Self::in_range(click_pct, 0, 70, "click_pct")?;
257 if (click_pct as f64) > important_pct as f64 * 1.75 {
258 return Err(ZBError::explicit(
259 "click_pct must be at most important_pct x 1.75",
260 ));
261 }
262 Ok(Value::Object(Map::from_iter([
263 ("c_from".into(), Value::String(c_from.to_string())),
264 ("reply_pct".into(), Value::from(reply_pct)),
265 ("important_pct".into(), Value::from(important_pct)),
266 ("click_pct".into(), Value::from(click_pct)),
267 ])))
268 }
269
270 pub fn list_sending_accounts(&self) -> ZBResult<Option<Value>> {
274 self.get("/sending-accounts", &HashMap::new())
275 }
276
277 pub fn get_sending_account(&self, from_address: &str) -> ZBResult<Option<Value>> {
279 Self::required(from_address, "from_address")?;
280 self.get(
281 "/sending-account",
282 &HashMap::from([("from_address", from_address.to_string())]),
283 )
284 }
285
286 pub fn add_sending_account(
293 &self,
294 from_address: &str,
295 onboarding_model: OnboardingModel,
296 engagement_rule_id: Option<i64>,
297 ignore_conflict: Option<bool>,
298 email_content: Option<&EmailContent>,
299 managed_sending: Option<&ManagedSending>,
300 ) -> ZBResult<Option<Value>> {
301 Self::required(from_address, "from_address")?;
302 let mut body = Map::from_iter([
303 ("from_address".into(), Value::String(from_address.into())),
304 (
305 "onboarding_model".into(),
306 Value::String(onboarding_model.as_str().into()),
307 ),
308 ]);
309
310 if onboarding_model == OnboardingModel::SelfManaged {
311 let Some(rule) = engagement_rule_id else {
312 return Err(ZBError::explicit(
313 "engagement_rule_id is required for self_managed",
314 ));
315 };
316 body.insert(
317 "engagement_rule_id".into(),
318 Value::from(Self::in_range(rule, 0, 4, "engagement_rule_id")?),
319 );
320 if email_content.is_some() || managed_sending.is_some() {
321 return Err(ZBError::explicit(
322 "email_content and managed_sending are for zb_managed",
323 ));
324 }
325 }
326 if let Some(flag) = ignore_conflict {
327 body.insert("ignore_conflict".into(), Value::Bool(flag));
328 }
329 if let Some(content) = email_content {
330 let mut object = Map::new();
331 if !content.types_of_emails.is_empty() {
332 for kind in &content.types_of_emails {
333 if !EMAIL_TYPES.contains(&kind.as_str()) {
334 return Err(ZBError::explicit(
335 "types_of_emails must be transactional, newsletter and/or marketing",
336 ));
337 }
338 }
339 object.insert(
340 "types_of_emails".into(),
341 Value::Array(
342 content
343 .types_of_emails
344 .iter()
345 .map(|kind| Value::String(kind.clone()))
346 .collect(),
347 ),
348 );
349 }
350 for (key, value) in [
351 ("industry", &content.industry),
352 ("company_name", &content.company_name),
353 ("website", &content.website),
354 ] {
355 if let Some(value) = value {
356 object.insert(key.into(), Value::String(value.clone()));
357 }
358 }
359 body.insert("email_content".into(), Value::Object(object));
360 }
361 if let Some(sending) = managed_sending {
362 let mut object = Map::new();
363 if let Some(offset) = sending.timezone_offset {
364 Self::in_range(offset as i64, -11, 14, "timezone_offset")?;
365 object.insert("timezone_offset".into(), Value::from(offset));
366 }
367 if let Some(date) = sending.warmup_start_date {
368 object.insert(
369 "warmup_start_date".into(),
370 Value::String(date.format("%F").to_string()),
371 );
372 }
373 if let Some(limit) = sending.daily_limit {
374 object.insert("daily_limit".into(), Value::from(limit));
375 }
376 body.insert("managed_sending".into(), Value::Object(object));
377 }
378 self.write("POST", "/sending-accounts", Value::Object(body))
379 }
380
381 pub fn update_sending_account(
384 &self,
385 from_address: &str,
386 engagement_rule_id: i64,
387 status_id: i64,
388 auto_enable: bool,
389 ) -> ZBResult<Option<Value>> {
390 Self::required(from_address, "from_address")?;
391 let body = Value::Object(Map::from_iter([
392 ("team_id".into(), Value::from(ANY_TEAM_ID)),
393 ("from_address".into(), Value::String(from_address.into())),
394 (
395 "engagement_rule_id".into(),
396 Value::from(Self::in_range(engagement_rule_id, 0, 4, "engagement_rule_id")?),
397 ),
398 (
399 "status_id".into(),
400 Value::from(Self::in_range(status_id, 0, 8, "status_id")?),
401 ),
402 ("auto_enable".into(), Value::Bool(auto_enable)),
403 ]));
404 self.write("PUT", "/sending-accounts", body)
405 }
406
407 pub fn delete_sending_account(&self, from_address: &str) -> ZBResult<Option<Value>> {
409 Self::required(from_address, "from_address")?;
410 self.json(
411 "DELETE",
412 "/sending-accounts",
413 &HashMap::from([("from_address", from_address.to_string())]),
414 None,
415 &[],
416 )
417 }
418
419 pub fn change_from_address(
422 &self,
423 old_from_address: &str,
424 new_from_address: &str,
425 ) -> ZBResult<Option<Value>> {
426 Self::required(old_from_address, "old_from_address")?;
427 Self::required(new_from_address, "new_from_address")?;
428 let body = Value::Object(Map::from_iter([
429 ("team_id".into(), Value::from(ANY_TEAM_ID)),
430 (
431 "old_from_address".into(),
432 Value::String(old_from_address.into()),
433 ),
434 (
435 "new_from_address".into(),
436 Value::String(new_from_address.into()),
437 ),
438 ]));
439 self.write("PUT", "/smtp-credentials", body)
440 }
441
442 pub fn list_from_addresses(
447 &self,
448 search_from: Option<&str>,
449 offset: Option<u32>,
450 limit: Option<u32>,
451 ) -> ZBResult<Option<Value>> {
452 let mut query = HashMap::new();
453 if let Some(search) = search_from {
454 if !search
455 .chars()
456 .all(|c| c.is_ascii_alphanumeric() || ".-_@+".contains(c))
457 {
458 return Err(ZBError::explicit(
459 "search_from takes letters, digits and . - _ @ + only",
460 ));
461 }
462 query.insert("search_from", search.to_string());
463 }
464 if let Some(offset) = offset {
465 query.insert("offset", offset.to_string());
466 }
467 if let Some(limit) = limit {
468 query.insert("limit", limit.to_string());
469 }
470 self.get("/from-addresses", &query)
471 }
472
473 pub fn get_engagement_rules(&self) -> ZBResult<Option<Value>> {
477 self.get("/engagement-rules", &HashMap::new())
478 }
479
480 pub fn set_engagement_rule(&self, c_from: &str, rule_id: i64) -> ZBResult<Option<Value>> {
482 Self::required(c_from, "c_from")?;
483 let body = Value::Object(Map::from_iter([(
484 "rule_id".to_string(),
485 Value::from(Self::in_range(rule_id, 0, 4, "rule_id")?),
486 )]));
487 self.json(
488 "PUT",
489 "/engagement-rule",
490 &HashMap::from([("c_from", c_from.to_string())]),
491 Some(&body),
492 &[],
493 )
494 }
495
496 pub fn get_custom_engagement(&self, c_from: &str) -> ZBResult<Option<Value>> {
498 Self::required(c_from, "c_from")?;
499 let path = format!(
500 "/custom-engagement/{}",
501 crate::utility::encode_path_segment(c_from.trim())
502 );
503 if c_from.trim() == "." || c_from.trim() == ".." {
504 return Err(ZBError::explicit("c_from is invalid"));
505 }
506 self.get(&path, &HashMap::new())
507 }
508
509 pub fn create_custom_engagement(
511 &self,
512 c_from: &str,
513 reply_pct: i64,
514 important_pct: i64,
515 click_pct: i64,
516 ) -> ZBResult<Option<Value>> {
517 let body = Self::engagement_body(c_from, reply_pct, important_pct, click_pct)?;
518 self.write("POST", "/custom-engagement", body)
519 }
520
521 pub fn update_custom_engagement(
523 &self,
524 c_from: &str,
525 reply_pct: i64,
526 important_pct: i64,
527 click_pct: i64,
528 ) -> ZBResult<Option<Value>> {
529 let body = Self::engagement_body(c_from, reply_pct, important_pct, click_pct)?;
530 self.write("PUT", "/custom-engagement", body)
531 }
532
533 pub fn delete_custom_engagement(
535 &self,
536 c_from: &str,
537 engagement_rule_id: i64,
538 ) -> ZBResult<Option<Value>> {
539 Self::required(c_from, "c_from")?;
540 let body = Value::Object(Map::from_iter([
541 ("c_from".to_string(), Value::String(c_from.into())),
542 (
543 "engagement_rule_id".to_string(),
544 Value::from(Self::in_range(engagement_rule_id, 1, 4, "engagement_rule_id")?),
545 ),
546 ]));
547 self.write("DELETE", "/custom-engagement", body)
548 }
549
550 pub fn get_seeds(&self) -> ZBResult<Option<Value>> {
554 self.get("/seeds", &HashMap::new())
555 }
556
557 pub fn download_seeds(&self) -> ZBResult<String> {
559 self.csv("/seeds/download", &HashMap::new())
560 }
561
562 pub fn get_seed_count(&self) -> ZBResult<Option<Value>> {
564 self.get("/seed-count", &HashMap::new())
565 }
566
567 pub fn get_progress_today(&self) -> ZBResult<Option<Value>> {
569 self.get("/progress-today", &HashMap::new())
570 }
571
572 pub fn get_sent_today(&self) -> ZBResult<Option<Value>> {
574 self.get("/sent-today", &HashMap::new())
575 }
576
577 pub fn get_emails_per_day(&self) -> ZBResult<Option<Value>> {
579 self.get("/emails-per-day", &HashMap::new())
580 }
581
582 pub fn get_statistics(&self, from_address: &str) -> ZBResult<Option<Value>> {
584 Self::required(from_address, "from_address")?;
585 self.get(
586 "/statistics",
587 &HashMap::from([("from_address", from_address.to_string())]),
588 )
589 }
590
591 pub fn get_statistics_per_day(
593 &self,
594 from_address: &str,
595 start_date: NaiveDate,
596 end_date: NaiveDate,
597 ) -> ZBResult<Option<Value>> {
598 Self::required(from_address, "from_address")?;
599 if start_date > end_date {
600 return Err(ZBError::explicit("start_date is later than end_date"));
601 }
602 self.get(
603 "/statistics-per-day",
604 &HashMap::from([
605 ("from_address", from_address.to_string()),
606 ("start_date", start_date.format("%F").to_string()),
607 ("end_date", end_date.format("%F").to_string()),
608 ]),
609 )
610 }
611
612 pub fn get_statistics_detailed(&self, c_from: &str) -> ZBResult<Option<Value>> {
614 Self::required(c_from, "c_from")?;
615 self.get(
616 "/statistics-detailed",
617 &HashMap::from([("c_from", c_from.to_string())]),
618 )
619 }
620
621 pub fn download_statistics(&self, c_from: &str) -> ZBResult<String> {
623 Self::required(c_from, "c_from")?;
624 self.csv(
625 "/statistics/download",
626 &HashMap::from([("c_from", c_from.to_string())]),
627 )
628 }
629
630 pub fn get_from_address_statistics(&self, from_address: &str) -> ZBResult<Option<Value>> {
632 Self::required(from_address, "from_address")?;
633 self.get(
634 "/from-address-statistics",
635 &HashMap::from([("from_address", from_address.to_string())]),
636 )
637 }
638
639 pub fn check_domain_dmarc(
645 &self,
646 from_address: &str,
647 dkim_selector: Option<&str>,
648 ) -> ZBResult<Option<Value>> {
649 Self::required(from_address, "from_address")?;
650 if !from_address.contains('@') {
651 return Err(ZBError::explicit(
652 "from_address must be an email address, e.g. sender@example.com",
653 ));
654 }
655 let mut query = HashMap::from([("from_address", from_address.to_string())]);
656 if let Some(selector) = dkim_selector {
657 Self::required(selector, "dkim_selector")?;
658 query.insert("dkim_selector", selector.to_string());
659 }
660 self.get("/check-domain-dmarc", &query)
661 }
662
663 pub fn test_smtp_configuration(
672 &self,
673 from_address: &str,
674 username: &str,
675 password: &str,
676 server: &str,
677 port: u16,
678 ) -> ZBResult<Option<Value>> {
679 Self::required(from_address, "from_address")?;
680 Self::required(username, "username")?;
681 Self::required(password, "password")?;
682 Self::required(server, "server")?;
683 if port == 0 {
684 return Err(ZBError::explicit("port must be 1 to 65535"));
685 }
686 let body = Value::Object(Map::from_iter([
687 ("from_address".to_string(), Value::String(from_address.into())),
688 ("username".to_string(), Value::String(username.into())),
689 ("password".to_string(), Value::String(password.into())),
690 ("server".to_string(), Value::String(server.into())),
691 ("port".to_string(), Value::from(port)),
692 ]));
693 self.json(
694 "POST",
695 "/test-smtp-configuration",
696 &HashMap::new(),
697 Some(&body),
698 &[password, username],
699 )
700 }
701}