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
use mail_builder::{headers::text::Text, MessageBuilder};
use mail_parser::Message;
use std::io;
use thiserror::Error;

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

#[derive(Debug, Error)]
pub enum Error {
    #[error("cannot build message from template")]
    CreateMessageBuilderError,
    #[error("cannot compile template")]
    WriteTplToStringError(#[source] io::Error),
    #[error("cannot compile template")]
    WriteTplToVecError(#[source] io::Error),
    // #[error("cannot compile mime meta language")]
    // CompileMmlError(#[source] mml::compiler::Error),
    // #[error("cannot interpret email as a template")]
    // InterpretError(#[source] mml::interpreter::Error),
    #[error("cannot parse template")]
    ParseMessageError,
}

#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MmlCompiler {
    mml_body_compiler: MmlBodyCompiler,
}

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

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

    pub async fn compile<'a>(self, mime_msg: impl AsRef<[u8]>) -> Result<MessageBuilder<'a>> {
        let mime_msg = Message::parse(mime_msg.as_ref()).ok_or(Error::ParseMessageError)?;

        let mml_body = mime_msg
            .text_bodies()
            .into_iter()
            .filter_map(|part| part.text_contents())
            .fold(String::new(), |mut contents, content| {
                if !contents.is_empty() {
                    contents.push_str("\n\n");
                }
                contents.push_str(content.trim());
                contents
            });

        let mml_body_compiler = self.mml_body_compiler;

        #[cfg(feature = "pgp")]
        let mml_body_compiler = mml_body_compiler
            .with_pgp_recipients(header::extract_emails(mime_msg.to()))
            .with_pgp_sender(header::extract_first_email(mime_msg.from()));

        let mut mime_msg_builder = mml_body_compiler.compile(&mml_body).await?;

        mime_msg_builder = mime_msg_builder.header("MIME-Version", Text::new("1.0"));

        for header in mime_msg.headers() {
            let key = header.name.as_str().to_owned();
            let val = crate::header::to_builder_val(header);
            mime_msg_builder = mime_msg_builder.header(key, val);
        }

        Ok(mime_msg_builder)
    }
}

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

    use crate::{MimeInterpreter, MmlCompiler};

    #[tokio::test]
    async fn non_ascii_headers() {
        let mml = concat_line!(
            "Message-ID: <id@localhost>",
            "Date: Thu, 1 Jan 1970 00:00:00 +0000",
            "From: Frȯm <from@localhost>",
            "To: Tó <to@localhost>",
            "Subject: Subjêct",
            "",
            "Hello, world!",
            "",
        );

        let mime_msg = MmlCompiler::new().compile(mml).await.unwrap();

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

        let expected_mml = concat_line!(
            "From: Frȯm <from@localhost>",
            "To: Tó <to@localhost>",
            "Subject: Subjêct",
            "",
            "Hello, world!",
            "",
        );

        assert_eq!(mml, expected_mml);
    }

    #[tokio::test]
    async fn message_id_with_angles() {
        let mml = concat_line!(
            "From: Hugo Osvaldo Barrera <hugo@localhost>",
            "To: Hugo Osvaldo Barrera <hugo@localhost>",
            "Cc:",
            "Subject: Blah",
            "Message-ID: <bfb64e12-b7d4-474c-a658-8a221365f8ca@localhost>",
            "",
            "Test message",
            "",
        );

        let mime_msg = MmlCompiler::new().compile(mml).await.unwrap();

        let mml = MimeInterpreter::new()
            .with_show_only_headers(["Message-ID"])
            .interpret_msg_builder(mime_msg)
            .await
            .unwrap();

        let expected_mml = concat_line!(
            "Message-ID: <bfb64e12-b7d4-474c-a658-8a221365f8ca@localhost>",
            "",
            "Test message",
            "",
        );

        assert_eq!(mml, expected_mml);
    }

    #[tokio::test]
    async fn message_id_without_angles() {
        let mml = concat_line!(
            "From: Hugo Osvaldo Barrera <hugo@localhost>",
            "To: Hugo Osvaldo Barrera <hugo@localhost>",
            "Cc:",
            "Subject: Blah",
            "Message-ID: bfb64e12-b7d4-474c-a658-8a221365f8ca@localhost",
            "",
            "Test message",
            "",
        );

        let mime_msg = MmlCompiler::new().compile(mml).await.unwrap();

        let mml = MimeInterpreter::new()
            .with_show_only_headers(["Message-ID"])
            .interpret_msg_builder(mime_msg)
            .await
            .unwrap();

        let expected_mml = concat_line!(
            "Message-ID: <bfb64e12-b7d4-474c-a658-8a221365f8ca@localhost>",
            "",
            "Test message",
            "",
        );

        assert_eq!(mml, expected_mml);
    }

    #[tokio::test]
    async fn mml_markup_unescaped() {
        let mml = concat_line!(
            "Message-ID: <id@localhost>",
            "Date: Thu, 1 Jan 1970 00:00:00 +0000",
            "From: from@localhost",
            "To: to@localhost",
            "Subject: subject",
            "",
            "<#!part>This should be unescaped<#!/part>",
            "",
        );

        let mime_msg = MmlCompiler::new().compile(mml).await.unwrap();
        let mime_msg_str = mime_msg.clone().write_to_string().unwrap();

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

        let expected_mml = concat_line!(
            "From: from@localhost",
            "To: to@localhost",
            "Subject: subject",
            "",
            "<#!part>This should be unescaped<#!/part>",
            "",
        );

        assert!(!mime_msg_str.contains("<#!part>"));
        assert!(mime_msg_str.contains("<#part>"));

        assert!(!mime_msg_str.contains("<#!/part>"));
        assert!(mime_msg_str.contains("<#/part>"));

        assert_eq!(mml, expected_mml);
    }
}