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
64pub struct ZeroBounceWarmup {
65 api_key: String,
66 root: String,
67 client: reqwest::blocking::Client,
68}
69
70impl std::fmt::Debug for ZeroBounceWarmup {
72 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73 f.debug_struct("ZeroBounceWarmup")
74 .field("api_key", &crate::utility::redacted_key(&self.api_key))
75 .field("root", &self.root)
76 .field("client", &self.client)
77 .finish()
78 }
79}
80
81impl ZeroBounceWarmup {
82 pub fn new(api_key: &str) -> ZBResult<Self> {
84 Self::with_base_url(api_key, DEFAULT_BASE_URL)
85 }
86
87 pub fn with_base_url(api_key: &str, base_url: &str) -> ZBResult<Self> {
89 if api_key.trim().is_empty() {
90 return Err(ZBError::explicit("api_key is required"));
91 }
92 crate::utility::check_key_text(api_key)?;
93 crate::parse_request_url(base_url)
96 .map_err(|_| ZBError::explicit("base_url must be an https:// URL"))?;
97 Ok(ZeroBounceWarmup {
98 api_key: api_key.to_string(),
99 root: format!("{}{BASE_PATH}", base_url.trim_end_matches('/')),
100 client: reqwest::blocking::Client::builder()
101 .timeout(Duration::from_secs(120))
102 .redirect(reqwest::redirect::Policy::none())
103 .build()
104 .unwrap_or_else(|_| reqwest::blocking::Client::default()),
105 })
106 }
107
108 fn redact(&self, text: &str, secrets: &[&str]) -> String {
112 let mut value = text.to_string();
113 for secret in std::iter::once(self.api_key.as_str()).chain(secrets.iter().copied()) {
114 if secret.is_empty() {
115 continue;
116 }
117 value = value.replace(secret, "***");
118 }
119 value
120 }
121
122 fn send(
123 &self,
124 method: &str,
125 path: &str,
126 query: &HashMap<&str, String>,
127 body: Option<&Value>,
128 secrets: &[&str],
129 ) -> ZBResult<(u16, String, String)> {
130 let url = crate::parse_request_url(&format!("{}{path}", self.root))?;
131 let mut request = match method {
132 "POST" => self.client.post(url),
133 "PUT" => self.client.put(url),
134 "DELETE" => self.client.delete(url),
135 _ => self.client.get(url),
136 }
137 .header("API-Key", self.api_key.as_str())
138 .header(reqwest::header::ACCEPT, "application/json")
139 .query(query);
140
141 if let Some(body) = body {
142 let encoded = serde_json::to_string(body)
145 .map_err(|_| ZBError::explicit("Invalid parameter: request body"))?;
146 request = request
147 .header(reqwest::header::CONTENT_TYPE, "application/json")
148 .body(encoded);
149 }
150
151 let response = request
152 .send()
153 .map_err(|error| ZBError::ExplicitError(self.redact(&error.to_string(), secrets)))?;
154 let status = response.status().as_u16();
155 let content_type = response
156 .headers()
157 .get(reqwest::header::CONTENT_TYPE)
158 .and_then(|value| value.to_str().ok())
159 .unwrap_or("")
160 .to_string();
161 let max_bytes = if content_type.starts_with("text/csv") {
162 crate::utility::MAX_GETFILE_BYTES
163 } else {
164 crate::utility::MAX_JSON_RESPONSE_BYTES
165 };
166 let body = crate::utility::read_limited(
167 response,
168 max_bytes,
169 "response body exceeds size limit",
170 )
171 .map_err(|error| ZBError::ExplicitError(self.redact(&error.to_string(), secrets)))?;
172 let text = String::from_utf8_lossy(&body).into_owned();
173
174 if (300..400).contains(&status) {
175 return Err(ZBError::api(
176 status,
177 crate::utility::http_error::REDIRECT_REFUSED_MESSAGE,
178 ));
179 }
180 if status > 299 {
181 return Err(ZBError::api(
182 status,
183 self.redact(&message_from_body(status, &content_type, &text), secrets),
184 ));
185 }
186 Ok((status, content_type, text))
187 }
188
189 fn json(
192 &self,
193 method: &str,
194 path: &str,
195 query: &HashMap<&str, String>,
196 body: Option<&Value>,
197 secrets: &[&str],
198 ) -> ZBResult<Option<Value>> {
199 let (status, content_type, text) = self.send(method, path, query, body, secrets)?;
200 if status == 204 || text.trim().is_empty() {
201 return Ok(None);
202 }
203 match serde_json::from_str::<Value>(&text) {
204 Ok(value) => Ok(Some(value)),
205 Err(_) => Err(ZBError::api(
206 status,
207 self.redact(&message_from_body(status, &content_type, &text), secrets),
208 )),
209 }
210 }
211
212 fn get(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<Option<Value>> {
213 self.json("GET", path, query, None, &[])
214 }
215
216 fn write(&self, method: &str, path: &str, body: Value) -> ZBResult<Option<Value>> {
217 self.json(method, path, &HashMap::new(), Some(&body), &[])
218 }
219
220 fn csv(&self, path: &str, query: &HashMap<&str, String>) -> ZBResult<String> {
222 let (status, content_type, text) = self.send("GET", path, query, None, &[])?;
223 if text.trim().is_empty() || content_type.to_ascii_lowercase().contains("application/json")
224 {
225 return Err(ZBError::api(
226 status,
227 message_from_body(status, &content_type, &text),
228 ));
229 }
230 Ok(text)
231 }
232
233 fn required<'a>(value: &'a str, name: &str) -> ZBResult<&'a str> {
236 if value.trim().is_empty() {
237 return Err(ZBError::ExplicitError(format!("{name} is required")));
238 }
239 Ok(value)
240 }
241
242 fn in_range(value: i64, low: i64, high: i64, name: &str) -> ZBResult<i64> {
243 if !(low..=high).contains(&value) {
244 return Err(ZBError::ExplicitError(format!(
245 "{name} must be {low} to {high}"
246 )));
247 }
248 Ok(value)
249 }
250
251 fn engagement_body(
252 c_from: &str,
253 reply_pct: i64,
254 important_pct: i64,
255 click_pct: i64,
256 ) -> ZBResult<Value> {
257 Self::required(c_from, "c_from")?;
258 Self::in_range(reply_pct, 5, 45, "reply_pct")?;
259 Self::in_range(important_pct, 5, 40, "important_pct")?;
260 Self::in_range(click_pct, 0, 70, "click_pct")?;
261 if (click_pct as f64) > important_pct as f64 * 1.75 {
262 return Err(ZBError::explicit(
263 "click_pct must be at most important_pct x 1.75",
264 ));
265 }
266 Ok(Value::Object(Map::from_iter([
267 ("c_from".into(), Value::String(c_from.to_string())),
268 ("reply_pct".into(), Value::from(reply_pct)),
269 ("important_pct".into(), Value::from(important_pct)),
270 ("click_pct".into(), Value::from(click_pct)),
271 ])))
272 }
273
274 pub fn list_sending_accounts(&self) -> ZBResult<Option<Value>> {
278 self.get("/sending-accounts", &HashMap::new())
279 }
280
281 pub fn get_sending_account(&self, from_address: &str) -> ZBResult<Option<Value>> {
283 Self::required(from_address, "from_address")?;
284 self.get(
285 "/sending-account",
286 &HashMap::from([("from_address", from_address.to_string())]),
287 )
288 }
289
290 pub fn add_sending_account(
297 &self,
298 from_address: &str,
299 onboarding_model: OnboardingModel,
300 engagement_rule_id: Option<i64>,
301 ignore_conflict: Option<bool>,
302 email_content: Option<&EmailContent>,
303 managed_sending: Option<&ManagedSending>,
304 ) -> ZBResult<Option<Value>> {
305 Self::required(from_address, "from_address")?;
306 let mut body = Map::from_iter([
307 ("from_address".into(), Value::String(from_address.into())),
308 (
309 "onboarding_model".into(),
310 Value::String(onboarding_model.as_str().into()),
311 ),
312 ]);
313
314 if onboarding_model == OnboardingModel::SelfManaged {
315 let Some(rule) = engagement_rule_id else {
316 return Err(ZBError::explicit(
317 "engagement_rule_id is required for self_managed",
318 ));
319 };
320 body.insert(
321 "engagement_rule_id".into(),
322 Value::from(Self::in_range(rule, 0, 4, "engagement_rule_id")?),
323 );
324 if email_content.is_some() || managed_sending.is_some() {
325 return Err(ZBError::explicit(
326 "email_content and managed_sending are for zb_managed",
327 ));
328 }
329 }
330 if let Some(flag) = ignore_conflict {
331 body.insert("ignore_conflict".into(), Value::Bool(flag));
332 }
333 if let Some(content) = email_content {
334 let mut object = Map::new();
335 if !content.types_of_emails.is_empty() {
336 for kind in &content.types_of_emails {
337 if !EMAIL_TYPES.contains(&kind.as_str()) {
338 return Err(ZBError::explicit(
339 "types_of_emails must be transactional, newsletter and/or marketing",
340 ));
341 }
342 }
343 object.insert(
344 "types_of_emails".into(),
345 Value::Array(
346 content
347 .types_of_emails
348 .iter()
349 .map(|kind| Value::String(kind.clone()))
350 .collect(),
351 ),
352 );
353 }
354 for (key, value) in [
355 ("industry", &content.industry),
356 ("company_name", &content.company_name),
357 ("website", &content.website),
358 ] {
359 if let Some(value) = value {
360 object.insert(key.into(), Value::String(value.clone()));
361 }
362 }
363 body.insert("email_content".into(), Value::Object(object));
364 }
365 if let Some(sending) = managed_sending {
366 let mut object = Map::new();
367 if let Some(offset) = sending.timezone_offset {
368 Self::in_range(offset as i64, -11, 14, "timezone_offset")?;
369 object.insert("timezone_offset".into(), Value::from(offset));
370 }
371 if let Some(date) = sending.warmup_start_date {
372 object.insert(
373 "warmup_start_date".into(),
374 Value::String(date.format("%F").to_string()),
375 );
376 }
377 if let Some(limit) = sending.daily_limit {
378 object.insert("daily_limit".into(), Value::from(limit));
379 }
380 body.insert("managed_sending".into(), Value::Object(object));
381 }
382 self.write("POST", "/sending-accounts", Value::Object(body))
383 }
384
385 pub fn update_sending_account(
388 &self,
389 from_address: &str,
390 engagement_rule_id: i64,
391 status_id: i64,
392 auto_enable: bool,
393 ) -> ZBResult<Option<Value>> {
394 Self::required(from_address, "from_address")?;
395 let body = Value::Object(Map::from_iter([
396 ("team_id".into(), Value::from(ANY_TEAM_ID)),
397 ("from_address".into(), Value::String(from_address.into())),
398 (
399 "engagement_rule_id".into(),
400 Value::from(Self::in_range(engagement_rule_id, 0, 4, "engagement_rule_id")?),
401 ),
402 (
403 "status_id".into(),
404 Value::from(Self::in_range(status_id, 0, 8, "status_id")?),
405 ),
406 ("auto_enable".into(), Value::Bool(auto_enable)),
407 ]));
408 self.write("PUT", "/sending-accounts", body)
409 }
410
411 pub fn delete_sending_account(&self, from_address: &str) -> ZBResult<Option<Value>> {
413 Self::required(from_address, "from_address")?;
414 self.json(
415 "DELETE",
416 "/sending-accounts",
417 &HashMap::from([("from_address", from_address.to_string())]),
418 None,
419 &[],
420 )
421 }
422
423 pub fn change_from_address(
426 &self,
427 old_from_address: &str,
428 new_from_address: &str,
429 ) -> ZBResult<Option<Value>> {
430 Self::required(old_from_address, "old_from_address")?;
431 Self::required(new_from_address, "new_from_address")?;
432 let body = Value::Object(Map::from_iter([
433 ("team_id".into(), Value::from(ANY_TEAM_ID)),
434 (
435 "old_from_address".into(),
436 Value::String(old_from_address.into()),
437 ),
438 (
439 "new_from_address".into(),
440 Value::String(new_from_address.into()),
441 ),
442 ]));
443 self.write("PUT", "/smtp-credentials", body)
444 }
445
446 pub fn list_from_addresses(
451 &self,
452 search_from: Option<&str>,
453 offset: Option<u32>,
454 limit: Option<u32>,
455 ) -> ZBResult<Option<Value>> {
456 let mut query = HashMap::new();
457 if let Some(search) = search_from {
458 if !search
459 .chars()
460 .all(|c| c.is_ascii_alphanumeric() || ".-_@+".contains(c))
461 {
462 return Err(ZBError::explicit(
463 "search_from takes letters, digits and . - _ @ + only",
464 ));
465 }
466 query.insert("search_from", search.to_string());
467 }
468 if let Some(offset) = offset {
469 query.insert("offset", offset.to_string());
470 }
471 if let Some(limit) = limit {
472 query.insert("limit", limit.to_string());
473 }
474 self.get("/from-addresses", &query)
475 }
476
477 pub fn get_engagement_rules(&self) -> ZBResult<Option<Value>> {
481 self.get("/engagement-rules", &HashMap::new())
482 }
483
484 pub fn set_engagement_rule(&self, c_from: &str, rule_id: i64) -> ZBResult<Option<Value>> {
486 Self::required(c_from, "c_from")?;
487 let body = Value::Object(Map::from_iter([(
488 "rule_id".to_string(),
489 Value::from(Self::in_range(rule_id, 0, 4, "rule_id")?),
490 )]));
491 self.json(
492 "PUT",
493 "/engagement-rule",
494 &HashMap::from([("c_from", c_from.to_string())]),
495 Some(&body),
496 &[],
497 )
498 }
499
500 pub fn get_custom_engagement(&self, c_from: &str) -> ZBResult<Option<Value>> {
502 Self::required(c_from, "c_from")?;
503 let path = format!(
504 "/custom-engagement/{}",
505 crate::utility::encode_path_segment(c_from.trim())
506 );
507 if c_from.trim() == "." || c_from.trim() == ".." {
508 return Err(ZBError::explicit("c_from is invalid"));
509 }
510 self.get(&path, &HashMap::new())
511 }
512
513 pub fn create_custom_engagement(
515 &self,
516 c_from: &str,
517 reply_pct: i64,
518 important_pct: i64,
519 click_pct: i64,
520 ) -> ZBResult<Option<Value>> {
521 let body = Self::engagement_body(c_from, reply_pct, important_pct, click_pct)?;
522 self.write("POST", "/custom-engagement", body)
523 }
524
525 pub fn update_custom_engagement(
527 &self,
528 c_from: &str,
529 reply_pct: i64,
530 important_pct: i64,
531 click_pct: i64,
532 ) -> ZBResult<Option<Value>> {
533 let body = Self::engagement_body(c_from, reply_pct, important_pct, click_pct)?;
534 self.write("PUT", "/custom-engagement", body)
535 }
536
537 pub fn delete_custom_engagement(
539 &self,
540 c_from: &str,
541 engagement_rule_id: i64,
542 ) -> ZBResult<Option<Value>> {
543 Self::required(c_from, "c_from")?;
544 let body = Value::Object(Map::from_iter([
545 ("c_from".to_string(), Value::String(c_from.into())),
546 (
547 "engagement_rule_id".to_string(),
548 Value::from(Self::in_range(engagement_rule_id, 1, 4, "engagement_rule_id")?),
549 ),
550 ]));
551 self.write("DELETE", "/custom-engagement", body)
552 }
553
554 pub fn get_seeds(&self) -> ZBResult<Option<Value>> {
558 self.get("/seeds", &HashMap::new())
559 }
560
561 pub fn download_seeds(&self) -> ZBResult<String> {
563 self.csv("/seeds/download", &HashMap::new())
564 }
565
566 pub fn get_seed_count(&self) -> ZBResult<Option<Value>> {
568 self.get("/seed-count", &HashMap::new())
569 }
570
571 pub fn get_progress_today(&self) -> ZBResult<Option<Value>> {
573 self.get("/progress-today", &HashMap::new())
574 }
575
576 pub fn get_sent_today(&self) -> ZBResult<Option<Value>> {
578 self.get("/sent-today", &HashMap::new())
579 }
580
581 pub fn get_emails_per_day(&self) -> ZBResult<Option<Value>> {
583 self.get("/emails-per-day", &HashMap::new())
584 }
585
586 pub fn get_statistics(&self, from_address: &str) -> ZBResult<Option<Value>> {
588 Self::required(from_address, "from_address")?;
589 self.get(
590 "/statistics",
591 &HashMap::from([("from_address", from_address.to_string())]),
592 )
593 }
594
595 pub fn get_statistics_per_day(
597 &self,
598 from_address: &str,
599 start_date: NaiveDate,
600 end_date: NaiveDate,
601 ) -> ZBResult<Option<Value>> {
602 Self::required(from_address, "from_address")?;
603 if start_date > end_date {
604 return Err(ZBError::explicit("start_date is later than end_date"));
605 }
606 self.get(
607 "/statistics-per-day",
608 &HashMap::from([
609 ("from_address", from_address.to_string()),
610 ("start_date", start_date.format("%F").to_string()),
611 ("end_date", end_date.format("%F").to_string()),
612 ]),
613 )
614 }
615
616 pub fn get_statistics_detailed(&self, c_from: &str) -> ZBResult<Option<Value>> {
618 Self::required(c_from, "c_from")?;
619 self.get(
620 "/statistics-detailed",
621 &HashMap::from([("c_from", c_from.to_string())]),
622 )
623 }
624
625 pub fn download_statistics(&self, c_from: &str) -> ZBResult<String> {
627 Self::required(c_from, "c_from")?;
628 self.csv(
629 "/statistics/download",
630 &HashMap::from([("c_from", c_from.to_string())]),
631 )
632 }
633
634 pub fn get_from_address_statistics(&self, from_address: &str) -> ZBResult<Option<Value>> {
636 Self::required(from_address, "from_address")?;
637 self.get(
638 "/from-address-statistics",
639 &HashMap::from([("from_address", from_address.to_string())]),
640 )
641 }
642
643 pub fn check_domain_dmarc(
649 &self,
650 from_address: &str,
651 dkim_selector: Option<&str>,
652 ) -> ZBResult<Option<Value>> {
653 Self::required(from_address, "from_address")?;
654 if !from_address.contains('@') {
655 return Err(ZBError::explicit(
656 "from_address must be an email address, e.g. sender@example.com",
657 ));
658 }
659 let mut query = HashMap::from([("from_address", from_address.to_string())]);
660 if let Some(selector) = dkim_selector {
661 Self::required(selector, "dkim_selector")?;
662 query.insert("dkim_selector", selector.to_string());
663 }
664 self.get("/check-domain-dmarc", &query)
665 }
666
667 pub fn test_smtp_configuration(
676 &self,
677 from_address: &str,
678 username: &str,
679 password: &str,
680 server: &str,
681 port: u16,
682 ) -> ZBResult<Option<Value>> {
683 Self::required(from_address, "from_address")?;
684 Self::required(username, "username")?;
685 Self::required(password, "password")?;
686 Self::required(server, "server")?;
687 if port == 0 {
688 return Err(ZBError::explicit("port must be 1 to 65535"));
689 }
690 let body = Value::Object(Map::from_iter([
691 ("from_address".to_string(), Value::String(from_address.into())),
692 ("username".to_string(), Value::String(username.into())),
693 ("password".to_string(), Value::String(password.into())),
694 ("server".to_string(), Value::String(server.into())),
695 ("port".to_string(), Value::from(port)),
696 ]));
697 self.json(
698 "POST",
699 "/test-smtp-configuration",
700 &HashMap::new(),
701 Some(&body),
702 &[password, username],
703 )
704 }
705}