message/
address.rs

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
use config::any_err;
use mailparsing::{Address, AddressList, EncodeHeaderValue, Mailbox};
#[cfg(feature = "impl")]
use mlua::{MetaMethod, UserData, UserDataFields, UserDataMethods};
use rfc5321::{ForwardPath, ReversePath};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq)]
#[serde(transparent)]
pub struct EnvelopeAddress(String);

impl EnvelopeAddress {
    pub fn parse(text: &str) -> anyhow::Result<Self> {
        if text.is_empty() {
            Ok(Self::null_sender())
        } else {
            let fields: Vec<&str> = text.split('@').collect();
            anyhow::ensure!(fields.len() == 2, "expected user@domain");
            // TODO: stronger validation of local part and domain
            Ok(Self(text.to_string()))
        }
    }

    pub fn user(&self) -> &str {
        match self.0.find('@') {
            Some(at) => &self.0[..at],
            None => "",
        }
    }

    pub fn domain(&self) -> &str {
        match self.0.find('@') {
            Some(at) => &self.0[at + 1..],
            None => "",
        }
    }

    pub fn null_sender() -> Self {
        Self("".to_string())
    }

    pub fn to_string(&self) -> String {
        self.0.to_string()
    }
}

impl TryInto<ForwardPath> for EnvelopeAddress {
    type Error = &'static str;
    fn try_into(self) -> Result<ForwardPath, Self::Error> {
        ForwardPath::try_from(self.0.as_str())
    }
}

impl TryInto<ReversePath> for EnvelopeAddress {
    type Error = &'static str;
    fn try_into(self) -> Result<ReversePath, Self::Error> {
        ReversePath::try_from(self.0.as_str())
    }
}

#[cfg(feature = "impl")]
impl UserData for EnvelopeAddress {
    fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
        fields.add_field_method_get("user", |_, this| Ok(this.user().to_string()));
        fields.add_field_method_get("domain", |_, this| Ok(this.domain().to_string()));
        fields.add_field_method_get("email", |_, this| Ok(this.0.to_string()));
    }

    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        methods.add_meta_method(MetaMethod::ToString, |_, this, _: ()| {
            Ok(this.0.to_string())
        });
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeaderAddressList(Vec<HeaderAddressEntry>);

impl HeaderAddressList {
    /// If the address list is comprised of a single entry,
    /// returns just the email domain from that entry
    pub fn domain(&self) -> anyhow::Result<&str> {
        let (_local, domain) = self.single_address_cracked()?;
        Ok(domain)
    }

    /// If the address list is comprised of a single entry,
    /// returns just the email domain from that entry
    pub fn user(&self) -> anyhow::Result<&str> {
        let (user, _domain) = self.single_address_cracked()?;
        Ok(user)
    }

    /// If the address list is comprised of a single entry,
    /// returns just the display name portion, if any
    pub fn name(&self) -> anyhow::Result<Option<&str>> {
        let addr = self.single_address()?;
        Ok(addr.name.as_deref())
    }

    pub fn email(&self) -> anyhow::Result<Option<&str>> {
        let addr = self.single_address()?;
        Ok(addr.address.as_deref())
    }

    /// Flattens the groups and list and returns a simple list
    /// of addresses
    pub fn flatten(&self) -> Vec<&HeaderAddress> {
        let mut res = vec![];
        for entry in &self.0 {
            match entry {
                HeaderAddressEntry::Address(a) => res.push(a),
                HeaderAddressEntry::Group(group) => {
                    for addr in &group.addresses {
                        res.push(addr);
                    }
                }
            }
        }
        res
    }

    pub fn single_address_cracked(&self) -> anyhow::Result<(&str, &str)> {
        let addr = self.single_address_string()?;
        let tuple = addr
            .split_once('@')
            .ok_or_else(|| anyhow::anyhow!("no @ in address"))?;
        Ok(tuple)
    }

    pub fn single_address_string(&self) -> anyhow::Result<&str> {
        let addr = self.single_address()?;
        match &addr.address {
            None => anyhow::bail!("no address"),
            Some(addr) => Ok(addr),
        }
    }

    pub fn single_address(&self) -> anyhow::Result<&HeaderAddress> {
        match self.0.len() {
            0 => anyhow::bail!("no addresses"),
            1 => match &self.0[0] {
                HeaderAddressEntry::Address(a) => Ok(a),
                _ => anyhow::bail!("is not a simple address"),
            },
            _ => anyhow::bail!("is not a simple single address"),
        }
    }
}

impl From<AddressList> for HeaderAddressList {
    fn from(input: AddressList) -> HeaderAddressList {
        let addresses: Vec<HeaderAddressEntry> = input.0.iter().map(Into::into).collect();
        HeaderAddressList(addresses)
    }
}

#[cfg(feature = "impl")]
impl UserData for HeaderAddressList {
    fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
        fields.add_field_method_get("user", |_, this| {
            Ok(this.user().map_err(any_err)?.to_string())
        });
        fields.add_field_method_get("domain", |_, this| {
            Ok(this.domain().map_err(any_err)?.to_string())
        });
        fields.add_field_method_get("email", |_, this| {
            Ok(this.email().map_err(any_err)?.map(|s| s.to_string()))
        });
        fields.add_field_method_get("name", |_, this| {
            Ok(this.name().map_err(any_err)?.map(|s| s.to_string()))
        });
        fields.add_field_method_get("list", |_, this| {
            Ok(this
                .flatten()
                .into_iter()
                .cloned()
                .collect::<Vec<HeaderAddress>>())
        });
    }

    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        methods.add_meta_method(MetaMethod::ToString, |_, this, _: ()| {
            let json = serde_json::to_string(&this.0).map_err(any_err)?;
            Ok(json)
        });
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HeaderAddressEntry {
    Address(HeaderAddress),
    Group(AddressGroup),
}

impl From<&Address> for HeaderAddressEntry {
    fn from(addr: &Address) -> HeaderAddressEntry {
        match addr {
            Address::Mailbox(mbox) => HeaderAddressEntry::Address(mbox.into()),
            Address::Group { name, entries } => {
                let addresses = entries.0.iter().map(Into::into).collect();
                HeaderAddressEntry::Group(AddressGroup {
                    name: if name.is_empty() {
                        None
                    } else {
                        Some(name.to_string())
                    },
                    addresses,
                })
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeaderAddress {
    pub name: Option<String>,
    pub address: Option<String>,
}

impl From<&Mailbox> for HeaderAddress {
    fn from(mbox: &Mailbox) -> HeaderAddress {
        Self {
            name: mbox.name.clone(),
            address: Some(mbox.address.encode_value().to_string()),
        }
    }
}

impl HeaderAddress {
    pub fn user(&self) -> anyhow::Result<&str> {
        let (user, _domain) = self.crack_address().map_err(any_err)?;
        Ok(user)
    }
    pub fn domain(&self) -> anyhow::Result<&str> {
        let (_user, domain) = self.crack_address().map_err(any_err)?;
        Ok(domain)
    }
    pub fn email(&self) -> Option<&str> {
        self.address.as_deref()
    }
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    pub fn crack_address(&self) -> anyhow::Result<(&str, &str)> {
        let address = self
            .address
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("no address"))?;

        Ok(address
            .split_once('@')
            .ok_or_else(|| anyhow::anyhow!("no @ in address"))?)
    }
}

#[cfg(feature = "impl")]
impl UserData for HeaderAddress {
    fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
        fields.add_field_method_get("user", |_, this| {
            Ok(this.user().map_err(any_err)?.to_string())
        });
        fields.add_field_method_get("domain", |_, this| {
            Ok(this.domain().map_err(any_err)?.to_string())
        });
        fields.add_field_method_get("email", |_, this| Ok(this.email().map(|s| s.to_string())));
        fields.add_field_method_get("name", |_, this| Ok(this.name().map(|s| s.to_string())));
    }
    fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
        methods.add_meta_method(MetaMethod::ToString, |_, this, _: ()| {
            let json = serde_json::to_string(&this).map_err(any_err)?;
            Ok(json)
        });
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AddressGroup {
    pub name: Option<String>,
    pub addresses: Vec<HeaderAddress>,
}