1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
use mail_builder::MessageBuilder;
use mail_parser::Message;
use std::{io, path::PathBuf};
use thiserror::Error;

#[cfg(feature = "pgp")]
use crate::Pgp;
use crate::{header, FilterParts, MimeBodyInterpreter, Result};

#[derive(Debug, Error)]
pub enum Error {
    #[error("cannot parse raw email")]
    ParseRawEmailError,
    #[error("cannot build email")]
    BuildEmailError(#[source] io::Error),
}

/// Represents the strategy used to display headers when interpreting
/// emails.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub enum ShowHeadersStrategy {
    /// Transfers all available headers to the interpreted template.
    #[default]
    All,
    /// Transfers only specific headers to the interpreted template.
    Only(Vec<String>),
}

impl ShowHeadersStrategy {
    pub fn contains(&self, header: &String) -> bool {
        match self {
            Self::All => false,
            Self::Only(headers) => headers.contains(header),
        }
    }
}

/// The template interpreter interprets full emails as
/// [`crate::Tpl`]. The interpreter needs to be customized first. The
/// customization follows the builder pattern. When the interpreter is
/// customized, calling any function matching `interpret_*()` consumes
/// the interpreter and generates the final [`crate::Tpl`].
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MimeInterpreter {
    /// Defines the strategy to display headers.
    /// [`ShowHeadersStrategy::All`] transfers all the available
    /// headers to the interpreted template,
    /// [`ShowHeadersStrategy::Only`] only transfers the given headers
    /// to the interpreted template.
    show_headers: ShowHeadersStrategy,

    mime_body_interpreter: MimeBodyInterpreter,
}

impl MimeInterpreter {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_show_headers(mut self, s: ShowHeadersStrategy) -> Self {
        self.show_headers = s;
        self
    }

    pub fn with_show_all_headers(mut self) -> Self {
        self.show_headers = ShowHeadersStrategy::All;
        self
    }

    pub fn with_show_only_headers(
        mut self,
        headers: impl IntoIterator<Item = impl ToString>,
    ) -> Self {
        let headers = headers.into_iter().fold(Vec::new(), |mut headers, header| {
            let header = header.to_string();
            if !headers.contains(&header) {
                headers.push(header)
            }
            headers
        });
        self.show_headers = ShowHeadersStrategy::Only(headers);
        self
    }

    pub fn with_show_additional_headers(
        mut self,
        headers: impl IntoIterator<Item = impl ToString>,
    ) -> Self {
        let next_headers = headers.into_iter().fold(Vec::new(), |mut headers, header| {
            let header = header.to_string();
            if !headers.contains(&header) && !self.show_headers.contains(&header) {
                headers.push(header)
            }
            headers
        });

        match &mut self.show_headers {
            ShowHeadersStrategy::All => {
                self.show_headers = ShowHeadersStrategy::Only(next_headers);
            }
            ShowHeadersStrategy::Only(headers) => {
                headers.extend(next_headers);
            }
        };

        self
    }

    pub fn with_hide_all_headers(mut self) -> Self {
        self.show_headers = ShowHeadersStrategy::Only(Vec::new());
        self
    }

    pub fn with_show_multiparts(mut self, b: bool) -> Self {
        self.mime_body_interpreter = self.mime_body_interpreter.show_multiparts(b);
        self
    }

    pub fn with_filter_parts(mut self, f: FilterParts) -> Self {
        self.mime_body_interpreter = self.mime_body_interpreter.filter_parts(f);
        self
    }

    pub fn with_show_plain_texts_signature(mut self, b: bool) -> Self {
        self.mime_body_interpreter = self.mime_body_interpreter.show_plain_texts_signature(b);
        self
    }

    pub fn with_show_attachments(mut self, b: bool) -> Self {
        self.mime_body_interpreter = self.mime_body_interpreter.show_attachments(b);
        self
    }

    pub fn with_show_inline_attachments(mut self, b: bool) -> Self {
        self.mime_body_interpreter = self.mime_body_interpreter.show_inline_attachments(b);
        self
    }

    pub fn with_save_attachments(mut self, b: bool) -> Self {
        self.mime_body_interpreter = self.mime_body_interpreter.save_attachments(b);
        self
    }

    pub fn with_save_attachments_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.mime_body_interpreter = self.mime_body_interpreter.save_attachments_dir(dir);
        self
    }

    #[cfg(feature = "pgp")]
    pub fn with_pgp(mut self, pgp: impl Into<Pgp>) -> Self {
        self.mime_body_interpreter = self.mime_body_interpreter.with_pgp(pgp.into());
        self
    }

    /// Interprets the given [`mail_parser::Message`] as a MML string.
    pub async fn interpret_msg(self, msg: &Message<'_>) -> Result<String> {
        let mut mml = String::new();

        match self.show_headers {
            ShowHeadersStrategy::All => msg.headers().iter().for_each(|header| {
                let key = header.name.as_str();
                let val = header::display_value(key, &header.value);
                mml.push_str(&format!("{key}: {val}\n"));
            }),
            ShowHeadersStrategy::Only(keys) => keys
                .iter()
                .filter_map(|key| msg.header(key).map(|val| (key, val)))
                .for_each(|(key, val)| {
                    let val = header::display_value(key, val);
                    mml.push_str(&format!("{key}: {val}\n"));
                }),
        };

        if !mml.is_empty() {
            mml.push_str("\n");
        }

        let mime_body_interpreter = self.mime_body_interpreter;

        #[cfg(feature = "pgp")]
        let mime_body_interpreter = mime_body_interpreter
            .with_pgp_sender(header::extract_first_email(msg.from()))
            .with_pgp_recipient(header::extract_first_email(msg.to()));

        let mml_body = mime_body_interpreter.interpret_msg(msg).await?;

        mml.push_str(mml_body.trim_end());
        mml.push('\n');

        Ok(mml)
    }

    /// Interprets the given bytes as a MML string.
    pub async fn interpret_bytes(self, bytes: impl AsRef<[u8]>) -> Result<String> {
        let msg = Message::parse(bytes.as_ref()).ok_or(Error::ParseRawEmailError)?;
        self.interpret_msg(&msg).await
    }

    /// Interprets the given [`mail_builder::MessageBuilder`] as a MML
    /// string.
    pub async fn interpret_msg_builder(self, builder: MessageBuilder<'_>) -> Result<String> {
        let bytes = builder.write_to_vec().map_err(Error::BuildEmailError)?;
        self.interpret_bytes(&bytes).await
    }
}

#[cfg(test)]
mod tests {
    use concat_with::concat_line;
    use mail_builder::MessageBuilder;

    use super::MimeInterpreter;

    fn msg_builder() -> MessageBuilder<'static> {
        MessageBuilder::new()
            .message_id("id@localhost")
            .in_reply_to("reply-id@localhost")
            .date(0 as u64)
            .from("from@localhost")
            .to("to@localhost")
            .subject("subject")
            .text_body("Hello, world!")
    }

    #[tokio::test]
    async fn all_headers() {
        let mml = MimeInterpreter::new()
            .with_show_all_headers()
            .interpret_msg_builder(msg_builder())
            .await
            .unwrap();

        let expected_mml = concat_line!(
            "Message-ID: <id@localhost>",
            "In-Reply-To: <reply-id@localhost>",
            "Date: Thu, 1 Jan 1970 00:00:00 +0000",
            "From: from@localhost",
            "To: to@localhost",
            "Subject: subject",
            "Content-Type: text/plain; charset=utf-8",
            "Content-Transfer-Encoding: 7bit",
            "",
            "Hello, world!",
            "",
        );

        assert_eq!(mml, expected_mml);
    }

    #[tokio::test]
    async fn only_headers() {
        let mml = MimeInterpreter::new()
            .with_show_only_headers(["From", "Subject"])
            .interpret_msg_builder(msg_builder())
            .await
            .unwrap();

        let expected_mml = concat_line!(
            "From: from@localhost",
            "Subject: subject",
            "",
            "Hello, world!",
            "",
        );

        assert_eq!(mml, expected_mml);
    }

    #[tokio::test]
    async fn only_headers_duplicated() {
        let mml = MimeInterpreter::new()
            .with_show_only_headers(["From", "Subject", "From"])
            .interpret_msg_builder(msg_builder())
            .await
            .unwrap();

        let expected_mml = concat_line!(
            "From: from@localhost",
            "Subject: subject",
            "",
            "Hello, world!",
            "",
        );

        assert_eq!(mml, expected_mml);
    }

    #[tokio::test]
    async fn no_headers() {
        let mml = MimeInterpreter::new()
            .with_hide_all_headers()
            .interpret_msg_builder(msg_builder())
            .await
            .unwrap();

        let expected_mml = concat_line!("Hello, world!", "");

        assert_eq!(mml, expected_mml);
    }

    #[tokio::test]
    async fn mml_markup_escaped() {
        let msg_builder = MessageBuilder::new()
            .message_id("id@localhost")
            .in_reply_to("reply-id@localhost")
            .date(0 as u64)
            .from("from@localhost")
            .to("to@localhost")
            .subject("subject")
            .text_body("<#part>Should be escaped.<#/part>");

        let mml = MimeInterpreter::new()
            .with_show_only_headers(["From", "Subject"])
            .interpret_msg_builder(msg_builder)
            .await
            .unwrap();

        let expected_mml = concat_line!(
            "From: from@localhost",
            "Subject: subject",
            "",
            "<#!part>Should be escaped.<#!/part>",
            "",
        );

        assert_eq!(mml, expected_mml);
    }
}