Skip to main content

utopia_emails/
canonicals.rs

1//! Canonical forms of addresses per mail provider.
2//!
3//! PHP: `Utopia\Emails\Canonicals\Providers\*`, as `Email` consults them.
4
5use php_std::string;
6
7use crate::Error;
8
9/// The canonical form of an address: its local part and domain with a
10/// provider's aliases removed.
11///
12/// PHP: the array `['local' => ..., 'domain' => ...]` of `getCanonical()`.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct Canonical {
15    /// The part before the `@`.
16    pub local: Vec<u8>,
17    /// The part after the `@`.
18    pub domain: Vec<u8>,
19}
20
21impl Canonical {
22    /// The address, `local@domain`.
23    pub fn address(&self) -> Vec<u8> {
24        [self.local.as_slice(), b"@", self.domain.as_slice()].concat()
25    }
26}
27
28/// A mail provider's aliasing rules.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct Provider {
31    /// The domain of its canonical addresses (`gmail.com`), empty for
32    /// [`Provider::GENERIC`].
33    ///
34    /// PHP: `getCanonicalDomain()`.
35    pub canonical_domain: &'static str,
36    /// The domains that belong to it.
37    ///
38    /// PHP: `getSupportedDomains()`.
39    pub domains: &'static [&'static str],
40    /// Drops a `+tag`.
41    plus: bool,
42    /// Drops every dot.
43    dots: bool,
44    /// Refuses a local part left empty (or `"0"`).
45    required: bool,
46    /// Keeps the address's own domain instead of the canonical one.
47    own_domain: bool,
48}
49
50impl Provider {
51    /// Gmail: drops `+tags` and all dots; `googlemail.com` is `gmail.com`.
52    pub const GMAIL: Provider = Provider {
53        canonical_domain: "gmail.com",
54        domains: &["gmail.com", "googlemail.com"],
55        plus: true,
56        dots: true,
57        required: true,
58        own_domain: false,
59    };
60
61    /// Outlook, Hotmail, Live, MSN and Passport: drops `+tags`, keeps dots.
62    pub const OUTLOOK: Provider = Provider {
63        canonical_domain: "outlook.com",
64        domains: &[
65            "outlook.com",
66            "outlook.at",
67            "outlook.be",
68            "outlook.cl",
69            "outlook.co.il",
70            "outlook.co.nz",
71            "outlook.co.th",
72            "outlook.co.uk",
73            "outlook.com.ar",
74            "outlook.com.au",
75            "outlook.com.br",
76            "outlook.com.gr",
77            "outlook.com.pe",
78            "outlook.com.tr",
79            "outlook.com.vn",
80            "outlook.cz",
81            "outlook.de",
82            "outlook.dk",
83            "outlook.es",
84            "outlook.fr",
85            "outlook.hu",
86            "outlook.id",
87            "outlook.ie",
88            "outlook.in",
89            "outlook.it",
90            "outlook.jp",
91            "outlook.kr",
92            "outlook.lv",
93            "outlook.my",
94            "outlook.ph",
95            "outlook.pt",
96            "outlook.sa",
97            "outlook.sg",
98            "outlook.sk",
99            "hotmail.com",
100            "hotmail.at",
101            "hotmail.be",
102            "hotmail.ca",
103            "hotmail.cl",
104            "hotmail.co.il",
105            "hotmail.co.nz",
106            "hotmail.co.th",
107            "hotmail.co.uk",
108            "hotmail.com.ar",
109            "hotmail.com.au",
110            "hotmail.com.br",
111            "hotmail.com.gr",
112            "hotmail.com.mx",
113            "hotmail.com.pe",
114            "hotmail.com.tr",
115            "hotmail.com.vn",
116            "hotmail.cz",
117            "hotmail.de",
118            "hotmail.dk",
119            "hotmail.es",
120            "hotmail.fr",
121            "hotmail.hu",
122            "hotmail.id",
123            "hotmail.ie",
124            "hotmail.in",
125            "hotmail.it",
126            "hotmail.jp",
127            "hotmail.kr",
128            "hotmail.lv",
129            "hotmail.my",
130            "hotmail.ph",
131            "hotmail.pt",
132            "hotmail.sa",
133            "hotmail.sg",
134            "hotmail.sk",
135            "live.com",
136            "live.be",
137            "live.co.uk",
138            "live.com.ar",
139            "live.com.mx",
140            "live.de",
141            "live.es",
142            "live.eu",
143            "live.fr",
144            "live.it",
145            "live.nl",
146            "msn.com",
147            "passport.com",
148        ],
149        plus: true,
150        dots: false,
151        required: true,
152        own_domain: false,
153    };
154
155    /// Yahoo, Ymail and Rocketmail: keeps the local part (a `-keyword` is a
156    /// separate address, not an alias).
157    pub const YAHOO: Provider = Provider {
158        canonical_domain: "yahoo.com",
159        domains: &[
160            "yahoo.com",
161            "yahoo.co.uk",
162            "yahoo.ca",
163            "yahoo.de",
164            "yahoo.fr",
165            "yahoo.in",
166            "yahoo.it",
167            "ymail.com",
168            "rocketmail.com",
169        ],
170        plus: false,
171        dots: false,
172        required: false,
173        own_domain: false,
174    };
175
176    /// iCloud, me.com and mac.com: drops `+tags`, keeps dots.
177    pub const ICLOUD: Provider = Provider {
178        canonical_domain: "icloud.com",
179        domains: &["icloud.com", "me.com", "mac.com"],
180        plus: true,
181        dots: false,
182        required: true,
183        own_domain: false,
184    };
185
186    /// Proton Mail: drops `+tags`, keeps dots and the domain (each Proton
187    /// domain is a separate address).
188    pub const PROTONMAIL: Provider = Provider {
189        canonical_domain: "protonmail.com",
190        domains: &["protonmail.com", "proton.me", "pm.me", "protonmail.ch"],
191        plus: true,
192        dots: false,
193        required: false,
194        own_domain: true,
195    };
196
197    /// Fastmail: keeps the local part.
198    pub const FASTMAIL: Provider = Provider {
199        canonical_domain: "fastmail.com",
200        domains: &["fastmail.com", "fastmail.fm"],
201        plus: false,
202        dots: false,
203        required: false,
204        own_domain: false,
205    };
206
207    /// Walla: keeps the local part; `walla.com` is `walla.co.il`.
208    pub const WALLA: Provider = Provider {
209        canonical_domain: "walla.co.il",
210        domains: &["walla.co.il", "walla.com"],
211        plus: false,
212        dots: false,
213        required: false,
214        own_domain: false,
215    };
216
217    /// Any other domain: only lower-cases the local part.
218    pub const GENERIC: Provider =
219        Provider { canonical_domain: "", domains: &[], plus: false, dots: false, required: false, own_domain: true };
220
221    /// The provider of [`PROVIDERS`] the domain belongs to, else
222    /// [`Provider::GENERIC`].
223    ///
224    /// PHP: `getProviderForDomain()`.
225    pub fn of(domain: &[u8]) -> &'static Provider {
226        PROVIDERS.iter().find(|provider| provider.supports(domain)).unwrap_or(&Provider::GENERIC)
227    }
228
229    /// Whether the domain belongs to this provider; any domain belongs to
230    /// [`Provider::GENERIC`].
231    ///
232    /// PHP: `supports($domain)`.
233    pub fn supports(&self, domain: &[u8]) -> bool {
234        self.domains.is_empty() || self.domains.iter().any(|own| own.as_bytes() == domain)
235    }
236
237    /// The address with this provider's aliases removed.
238    ///
239    /// # Errors
240    ///
241    /// [`Error::EmptyLocal`] when Gmail, Outlook or iCloud's rules leave
242    /// nothing (or `"0"`) of the local part.
243    ///
244    /// PHP: `getCanonical($local, $domain)`.
245    pub fn canonical(&self, local: &[u8], domain: &[u8]) -> Result<Canonical, Error> {
246        let mut local = string::strtolower(local).into_owned();
247        if self.plus
248            && let Some(plus) = local.iter().position(|&byte| byte == b'+')
249            && plus > 0
250        {
251            local.truncate(plus);
252        }
253        if self.dots {
254            local.retain(|&byte| byte != b'.');
255        }
256        if self.required && (local.is_empty() || local == b"0") {
257            return Err(Error::EmptyLocal);
258        }
259        let domain = if self.own_domain { domain.to_vec() } else { self.canonical_domain.as_bytes().to_vec() };
260        Ok(Canonical { local, domain })
261    }
262}
263
264/// The providers `Email` consults, in order.
265///
266/// PHP: `Email::initializeProviders()`; `Yandex` is not among them.
267pub static PROVIDERS: &[Provider] = &[
268    Provider::GMAIL,
269    Provider::OUTLOOK,
270    Provider::YAHOO,
271    Provider::ICLOUD,
272    Provider::PROTONMAIL,
273    Provider::FASTMAIL,
274    Provider::WALLA,
275];
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    fn canonical(local: &str, domain: &str) -> Result<String, Error> {
282        Provider::of(domain.as_bytes())
283            .canonical(local.as_bytes(), domain.as_bytes())
284            .map(|canonical| String::from_utf8(canonical.address()).unwrap())
285    }
286
287    #[test]
288    fn providers() {
289        assert_eq!(canonical("John.Doe+tag", "googlemail.com").unwrap(), "johndoe@gmail.com");
290        assert_eq!(canonical("a.b+c", "hotmail.co.uk").unwrap(), "a.b@outlook.com");
291        assert_eq!(canonical("a.b+c", "pm.me").unwrap(), "a.b@pm.me");
292        assert_eq!(canonical("a-b+c", "ymail.com").unwrap(), "a-b+c@yahoo.com");
293        assert_eq!(canonical("+a", "me.com").unwrap(), "+a@icloud.com");
294        assert_eq!(canonical("A+b", "yandex.ru").unwrap(), "a+b@yandex.ru");
295        assert_eq!(canonical("0+x", "gmail.com"), Err(Error::EmptyLocal));
296        assert_eq!(canonical("..", "gmail.com"), Err(Error::EmptyLocal));
297        assert_eq!(canonical("0", "yahoo.com").unwrap(), "0@yahoo.com");
298        assert_eq!(Provider::of(b"me.com").canonical_domain, "icloud.com");
299        assert_eq!(Provider::of(b"GMAIL.com"), &Provider::GENERIC);
300    }
301}