Skip to main content

loops_so/client/
email_messages.rs

1use serde_json::{Map, Value};
2
3use super::{EmailFormat, EmailMessageUpdate, LoopsClient, PreviewOptions, check};
4use crate::error::{LoopsError, Result};
5use crate::generated::{
6    CompleteUploadRequest, CompleteUploadResponse, CompleteUploadResponseEnum, CreateUploadRequest,
7    CreateUploadRequestParams, CreateUploadResponse, CreateUploadResponseEnum,
8    EmailMessageGuardianResponse, EmailMessagePreviewResponse, EmailMessageResponse,
9    GetEmailMessageGuardianRequest, GetEmailMessageGuardianResponse, GetEmailMessageRequest,
10    GetEmailMessageResponse, PreviewEmailMessageRequest, PreviewEmailMessageResponse,
11    UpdateEmailMessageRequest, UpdateEmailMessageRequestParams, UpdateEmailMessageResponse,
12};
13use crate::routes::Route;
14
15impl LoopsClient {
16    /// Get an email message.
17    pub async fn get_email_message(&self, email_message_id: &str) -> Result<EmailMessageResponse> {
18        const ACTION: &str = "get email message";
19        let raw = self
20            .send(Route::GetEmailMessage, &[email_message_id], |r| r)
21            .await?;
22        match raw
23            .parse(ACTION, GetEmailMessageRequest::parse_response)
24            .await?
25        {
26            GetEmailMessageResponse::Ok(message) => Ok(message),
27            _ => Err(raw.unexpected(ACTION)),
28        }
29    }
30
31    /// Update an email message. Only the fields set on `update` change.
32    ///
33    /// # Errors
34    ///
35    /// [`LoopsError::UnsafeEmail`] when safe mode is on and the CC or BCC
36    /// address is outside the allowed domains: those addresses receive every
37    /// email sent from the message. [`LoopsError::Api`] with status 409 when
38    /// `expected_revision_id` is stale.
39    pub async fn update_email_message(
40        &self,
41        email_message_id: &str,
42        update: EmailMessageUpdate,
43    ) -> Result<EmailMessageResponse> {
44        const ACTION: &str = "update email message";
45        self.validate_email(update.cc_email.as_deref())?;
46        self.validate_email(update.bcc_email.as_deref())?;
47        let body = UpdateEmailMessageRequest {
48            expected_revision_id: update.expected_revision_id,
49            subject: update.subject,
50            preview_text: update.preview_text,
51            from_name: update.from_name,
52            from_email: update.from_email,
53            reply_to_email: update.reply_to_email,
54            cc_email: update.cc_email,
55            bcc_email: update.bcc_email,
56            language_code: update.language_code,
57            email_format: update.email_format.map(|format| match format {
58                EmailFormat::Plain => crate::generated::EmailFormat::Plain,
59                EmailFormat::Styled => crate::generated::EmailFormat::Styled,
60            }),
61            lmx: update.lmx,
62            contact_properties_fallbacks: update
63                .contact_properties_fallbacks
64                .map(|m| m.into_iter().collect()),
65            event_properties_fallbacks: update
66                .event_properties_fallbacks
67                .map(|m| m.into_iter().collect()),
68            data_variables_fallbacks: update
69                .data_variables_fallbacks
70                .map(|m| m.into_iter().collect()),
71        };
72        let raw = self
73            .send(Route::UpdateEmailMessage, &[email_message_id], |r| {
74                r.json(&body)
75            })
76            .await?;
77        match raw
78            .parse(ACTION, UpdateEmailMessageRequestParams::parse_response)
79            .await?
80        {
81            UpdateEmailMessageResponse::Ok(message) => Ok(message),
82            _ => Err(raw.unexpected(ACTION)),
83        }
84    }
85
86    /// Run Guardian content checks against a saved email message: missing or
87    /// invalid links, unsupported properties, malformed buttons, missing
88    /// required data variables and the like. MJML messages are not supported.
89    pub async fn get_email_message_guardian(
90        &self,
91        email_message_id: &str,
92    ) -> Result<EmailMessageGuardianResponse> {
93        const ACTION: &str = "get email message guardian checks";
94        let raw = self
95            .send(Route::GetEmailMessageGuardian, &[email_message_id], |r| r)
96            .await?;
97        match raw
98            .parse(ACTION, GetEmailMessageGuardianRequest::parse_response)
99            .await?
100        {
101            GetEmailMessageGuardianResponse::Ok(report) => Ok(report),
102            _ => Err(raw.unexpected(ACTION)),
103        }
104    }
105
106    /// Send a preview of an email message to one or more addresses, each
107    /// checked against safe mode.
108    pub async fn preview_email_message(
109        &self,
110        email_message_id: &str,
111        emails: &[&str],
112        options: PreviewOptions,
113    ) -> Result<EmailMessagePreviewResponse> {
114        const ACTION: &str = "preview email message";
115        for email in emails {
116            self.validate_email(Some(email))?;
117        }
118        if emails.is_empty() {
119            return Err(LoopsError::InvalidInput(
120                "preview_email_message needs at least one recipient".to_owned(),
121            ));
122        }
123        // The generated body only allows string values; Loops renders
124        // numbers and booleans too, so the body is built as JSON.
125        let mut body = Map::new();
126        body.insert("emails".to_owned(), Value::from(emails.to_vec()));
127        for (key, values) in [
128            ("contactProperties", options.contact_properties),
129            ("eventProperties", options.event_properties),
130            ("dataVariables", options.data_variables),
131        ] {
132            if !values.is_empty() {
133                body.insert(key.to_owned(), Value::Object(values));
134            }
135        }
136        let raw = self
137            .send(Route::PreviewEmailMessage, &[email_message_id], |r| {
138                r.json(&body)
139            })
140            .await?;
141        match raw
142            .parse(ACTION, PreviewEmailMessageRequest::parse_response)
143            .await?
144        {
145            PreviewEmailMessageResponse::Ok(preview) => Ok(preview),
146            _ => Err(raw.unexpected(ACTION)),
147        }
148    }
149
150    /// Start an asset upload. Upload the file to the returned presigned URL,
151    /// then call [`complete_upload`](Self::complete_upload).
152    pub async fn create_upload(
153        &self,
154        content_type: &str,
155        content_length: u64,
156    ) -> Result<CreateUploadResponse> {
157        const ACTION: &str = "create upload";
158        let body = CreateUploadRequest {
159            content_type: content_type.to_owned(),
160            content_length: i64::try_from(content_length).map_err(|_| {
161                LoopsError::InvalidInput(format!("content_length {content_length} is too large"))
162            })?,
163        };
164        check(&body)?;
165        let raw = self
166            .send(Route::CreateUpload, &[], |r| r.json(&body))
167            .await?;
168        match raw
169            .parse(ACTION, CreateUploadRequestParams::parse_response)
170            .await?
171        {
172            CreateUploadResponseEnum::Ok(upload) => Ok(upload),
173            _ => Err(raw.unexpected(ACTION)),
174        }
175    }
176
177    /// Mark an upload as complete.
178    ///
179    /// Loops reports an exceeded upload limit as HTTP 429, which surfaces as
180    /// [`LoopsError::RateLimit`].
181    pub async fn complete_upload(&self, upload_id: &str) -> Result<CompleteUploadResponse> {
182        const ACTION: &str = "complete upload";
183        let raw = self
184            .send(Route::CompleteUpload, &[upload_id], |r| r)
185            .await?;
186        match raw
187            .parse(ACTION, CompleteUploadRequest::parse_response)
188            .await?
189        {
190            CompleteUploadResponseEnum::Ok(upload) => Ok(upload),
191            _ => Err(raw.unexpected(ACTION)),
192        }
193    }
194}