libimagmail/
util.rs

1//
2// imag - the personal information management suite for the commandline
3// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
4//
5// This library is free software; you can redistribute it and/or
6// modify it under the terms of the GNU Lesser General Public
7// License as published by the Free Software Foundation; version
8// 2.1 of the License.
9//
10// This library is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13// Lesser General Public License for more details.
14//
15// You should have received a copy of the GNU Lesser General Public
16// License along with this library; if not, write to the Free Software
17// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18//
19
20use std::path::Path;
21use std::fs::OpenOptions;
22use std::io::Read;
23
24use failure::Error;
25use failure::Fallible as Result;
26use failure::ResultExt;
27
28/// Get the message header at a specific key
29///
30/// # WARNING
31///
32/// Key must be all-lowercase
33///
34/// # WARNING
35///
36/// Expensive, as mailfile gets read from disk internally.
37/// TODO: Optimize
38///
39pub(crate) fn get_message_header_at_key<P: AsRef<Path>, K: AsRef<str>>(p: P, k: K) -> Result<String> {
40    let buffer = {
41        let mut buffer = Vec::with_capacity(4096); // allocate new buffer with 4 KB space
42        OpenOptions::new()
43            .read(true)
44            .open(p.as_ref())?
45            .read_to_end(&mut buffer)?;
46        buffer
47    };
48
49    ::mailparse::parse_mail(&buffer)
50        .context(format_err!("Cannot parse Email {}", p.as_ref().display()))?
51        .headers
52        .into_iter()
53        .filter_map(|hdr| match hdr.get_key().context("Cannot get key from mail header").map_err(Error::from) {
54            Ok(key) => {
55                let lower_key = key.to_lowercase();
56                trace!("Test: {} == {}", lower_key, k.as_ref());
57                if lower_key == k.as_ref() {
58                    Some(Ok(hdr))
59                } else {
60                    None
61                }
62            },
63            Err(e) => Some(Err(e))
64        })
65        .next()
66        .ok_or_else(|| format_err!("'{}' not found in {}", k.as_ref(), p.as_ref().display()))?
67        .and_then(|hdr| hdr.get_value().context("Cannot get value from mail header").map_err(Error::from))
68}
69
70pub(crate) fn get_message_id_for_mailfile<P: AsRef<Path>>(p: P) -> Result<String> {
71    get_message_header_at_key(p, "message-id").map(strip_message_delimiters)
72}
73
74/// Strips message delimiters ('<' and '>') from a Message-ID field.
75pub(crate) fn strip_message_delimiters<ID: AsRef<str>>(id: ID) -> String {
76    let len  = id.as_ref().len();
77    // We have to strip the '<' and '>' if there are any, because they do not belong to the
78    // Message-Id at all
79    id.as_ref()
80        .chars()
81        .enumerate()
82        .filter(|(idx, chr)| !(*idx == 0 && *chr == '<' || *idx == len - 1 && *chr == '>'))
83        .map(|tpl| tpl.1)
84        .collect()
85}
86
87pub fn get_mail_text_content<P: AsRef<Path>>(p: P) -> Result<String> {
88    ::mailparse::parse_mail(::std::fs::read_to_string(p.as_ref())?.as_bytes())
89        .context(format_err!("Cannot parse Email {}", p.as_ref().display()))?
90        .get_body()
91        .context("Cannot get body of mail")
92        .map_err(Error::from)
93}
94