mail_parser/mailbox/
maildir.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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
 * Copyright Stalwart Labs Ltd. See the COPYING
 * file at the top-level directory of this distribution.
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
 * option. This file may not be copied, modified, or distributed
 * except according to those terms.
 */

use std::{
    fs, io,
    path::{Path, PathBuf},
};

/// Maildir folder iterator
pub struct FolderIterator<'x> {
    inbox: Option<MessageIterator>,
    it_stack: Vec<fs::ReadDir>,
    name_stack: Vec<String>,
    prefix: Option<&'x str>,
}

/// Maildir message iterator
pub struct MessageIterator {
    name: Option<String>,
    cur_it: fs::ReadDir,
    new_it: fs::ReadDir,
}

/// Maildir message contents and metadata
#[derive(Debug, PartialEq, Eq, Clone, PartialOrd, Ord)]
pub struct Message {
    internal_date: u64,
    flags: Vec<Flag>,
    contents: Vec<u8>,
    path: PathBuf,
}

/// Flags of Maildir message
#[derive(Debug, PartialEq, Eq, Clone, Copy, PartialOrd, Ord)]
pub enum Flag {
    Passed,
    Replied,
    Seen,
    Trashed,
    Draft,
    Flagged,
}

impl FolderIterator<'_> {
    /// Creates a new Maildir folder iterator.
    /// For Maildir++ mailboxes use `Some(".")` as the prefix.
    /// For Dovecot Maildir mailboxes using LAYOUT=fs, use `None` as the prefix.
    pub fn new(
        path: impl Into<PathBuf>,
        sub_folder_prefix: Option<&str>,
    ) -> io::Result<FolderIterator> {
        let path = path.into();

        Ok(FolderIterator {
            it_stack: vec![fs::read_dir(&path)?],
            name_stack: Vec::new(),
            inbox: match MessageIterator::new_(&path, None) {
                Ok(inbox) => inbox.into(),
                Err(err) => {
                    if err.kind() == io::ErrorKind::NotFound {
                        None
                    } else {
                        return Err(err);
                    }
                }
            },
            prefix: sub_folder_prefix,
        })
    }
}

impl MessageIterator {
    /// Creates a new Maildir message iterator
    pub fn new(path: impl Into<PathBuf>) -> io::Result<MessageIterator> {
        MessageIterator::new_(&path.into(), None)
    }

    fn new_(path: &Path, name: Option<String>) -> io::Result<MessageIterator> {
        let mut cur_path = path.to_path_buf();
        cur_path.push("cur");
        if !cur_path.exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "Invalid Maildir format, 'cur' directory not found.",
            ));
        }
        let mut new_path = path.to_path_buf();
        new_path.push("new");
        if !new_path.exists() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "Invalid Maildir format, 'new' directory not found.",
            ));
        }

        Ok(MessageIterator {
            name,
            cur_it: fs::read_dir(cur_path)?,
            new_it: fs::read_dir(new_path)?,
        })
    }

    /// Returns the mailbox name of None for 'INBOX'.
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }
}

impl Iterator for FolderIterator<'_> {
    type Item = io::Result<MessageIterator>;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(inbox) = self.inbox.take() {
            return Some(Ok(inbox));
        }

        loop {
            let entry = match self.it_stack.last_mut().unwrap().next() {
                Some(Ok(entry)) => entry,
                Some(Err(err)) => return Some(Err(err)),
                None => {
                    self.it_stack.pop();
                    self.name_stack.pop();

                    if !self.it_stack.is_empty() {
                        continue;
                    } else {
                        return None;
                    }
                }
            };

            let path = entry.path();
            if path.is_dir() {
                if let Some(name) =
                    path.file_name()
                        .and_then(|name| name.to_str())
                        .and_then(|name| {
                            if !["cur", "new", "tmp"].contains(&name) {
                                if let Some(prefix) = self.prefix {
                                    name.strip_prefix(prefix)
                                } else {
                                    name.into()
                                }
                            } else {
                                None
                            }
                        })
                {
                    match fs::read_dir(&path) {
                        Ok(next_it) => {
                            self.it_stack.push(next_it);
                            self.name_stack.push(name.to_string());
                        }
                        Err(err) => {
                            return Some(Err(err));
                        }
                    }

                    match MessageIterator::new_(
                        &path,
                        self.name_stack.join(self.prefix.unwrap_or("/")).into(),
                    ) {
                        Ok(folder) => return Some(Ok(folder)),
                        Err(err) => {
                            if err.kind() != io::ErrorKind::NotFound {
                                return Some(Err(err));
                            }
                        }
                    }
                }
            }
        }
    }
}

impl Iterator for MessageIterator {
    type Item = io::Result<Message>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let entry = match self.cur_it.next().or_else(|| self.new_it.next()) {
                Some(Ok(entry)) => entry,
                Some(Err(err)) => return Some(Err(err)),
                None => return None,
            };
            let path = entry.path();
            if path.is_file() {
                if let Some(name) = path.file_name().and_then(|name| name.to_str()) {
                    if !name.starts_with('.') {
                        let internal_date =
                            match fs::metadata(&path).and_then(|m| m.created()).and_then(|d| {
                                d.duration_since(std::time::UNIX_EPOCH)
                                    .map(|d| d.as_secs())
                                    .map_err(|e| {
                                        io::Error::new(io::ErrorKind::InvalidData, e.to_string())
                                    })
                            }) {
                                Ok(metadata) => metadata,
                                Err(err) => return Some(Err(err)),
                            };
                        let contents = match fs::read(&path) {
                            Ok(contents) => contents,
                            Err(err) => return Some(Err(err)),
                        };
                        let mut flags = Vec::new();
                        if let Some((_, part)) = name.rsplit_once("2,") {
                            for &ch in part.as_bytes() {
                                match ch {
                                    b'P' => flags.push(Flag::Passed),
                                    b'R' => flags.push(Flag::Replied),
                                    b'S' => flags.push(Flag::Seen),
                                    b'T' => flags.push(Flag::Trashed),
                                    b'D' => flags.push(Flag::Draft),
                                    b'F' => flags.push(Flag::Flagged),
                                    _ => {
                                        if !ch.is_ascii_alphanumeric() {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        return Some(Ok(Message {
                            contents,
                            internal_date,
                            flags,
                            path: path.to_path_buf(),
                        }));
                    }
                }
            }
        }
    }
}

impl Message {
    /// Returns the message creation date in seconds since UNIX epoch
    pub fn internal_date(&self) -> u64 {
        self.internal_date
    }

    /// Returns the message flags
    pub fn flags(&self) -> &[Flag] {
        &self.flags
    }

    /// Returns the path to the message file
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Returns the message contents
    pub fn contents(&self) -> &[u8] {
        &self.contents
    }

    /// Unwraps the message contents
    pub fn unwrap_contents(self) -> Vec<u8> {
        self.contents
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use crate::mailbox::maildir::{Flag, Message};

    use super::FolderIterator;

    #[test]
    fn parse_maildir() {
        let mut test_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        test_dir.push("tests");
        test_dir.push("maildir");

        let mut messages = Vec::new();
        let expected_messages = vec![
            (
                "INBOX".to_string(),
                Message {
                    internal_date: 0,
                    flags: vec![Flag::Seen],
                    contents: vec![98, 10],
                    path: "unknown".into(),
                },
            ),
            (
                "INBOX".to_string(),
                Message {
                    internal_date: 0,
                    flags: vec![Flag::Seen, Flag::Trashed],
                    contents: vec![97, 10],
                    path: "unknown".into(),
                },
            ),
            (
                "My Folder".to_string(),
                Message {
                    internal_date: 0,
                    flags: vec![],
                    contents: vec![100, 10],
                    path: "unknown".into(),
                },
            ),
            (
                "My Folder".to_string(),
                Message {
                    internal_date: 0,
                    flags: vec![Flag::Trashed, Flag::Draft, Flag::Replied],
                    contents: vec![99, 10],
                    path: "unknown".into(),
                },
            ),
            (
                "My Folder.Nested Folder".to_string(),
                Message {
                    internal_date: 0,
                    flags: vec![Flag::Replied, Flag::Draft, Flag::Flagged],
                    contents: vec![102, 10],
                    path: "unknown".into(),
                },
            ),
            (
                "My Folder.Nested Folder".to_string(),
                Message {
                    internal_date: 0,
                    flags: vec![Flag::Flagged, Flag::Passed],
                    contents: vec![101, 10],
                    path: "unknown".into(),
                },
            ),
        ];

        for folder in FolderIterator::new(test_dir, ".".into()).unwrap() {
            let folder = folder.unwrap();
            let name = folder.name().unwrap_or("INBOX").to_string();

            for message in folder {
                let mut message = message.unwrap();
                assert_ne!(message.internal_date(), 0);
                assert!(message.path.exists());
                message.internal_date = 0;
                message.path = PathBuf::from("unknown");
                messages.push((name.clone(), message));
            }
        }

        messages.sort_unstable();
        assert_eq!(messages, expected_messages);
    }
}