summaryrefslogtreecommitdiffstats
path: root/lib/domain/libimagmail/src/mail.rs
blob: b33b4f91591668149c636ca91434aac3e0ac474e (plain)
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
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use failure::Fallible as Result;
use failure::ResultExt;
use failure::Error;
use toml_query::read::TomlValueReadExt;

use libimagstore::store::Entry;
use libimagentryutil::isa::Is;
use libimagentryutil::isa::IsKindHeaderPathProvider;
use libimagentryref::reference::Config as RefConfig;
use libimagentryref::reference::{Ref, RefFassade};
use libimagentrylink::linkable::Linkable;
use libimagstore::store::Store;
use libimagstore::storeid::StoreId;
use libimagstore::storeid::StoreIdIterator;
use libimagstore::iter::get::StoreIdGetIteratorExtension;

use crate::mid::MessageId;
use crate::iter::MailIterator;
use crate::iter::IntoMailIterator;

provide_kindflag_path!(pub IsMail, "mail.is_mail");

pub trait Mail : RefFassade + Linkable {
    fn is_mail(&self)                                       -> Result<bool>;
    fn get_field(&self, refconfig: &RefConfig, field: &str) -> Result<Option<String>>;
    fn get_from(&self, refconfig: &RefConfig)               -> Result<Option<String>>;
    fn get_to(&self, refconfig: &RefConfig)                 -> Result<Option<String>>;
    fn get_subject(&self, refconfig: &RefConfig)            -> Result<Option<String>>;
    fn get_message_id(&self, refconfig: &RefConfig)         -> Result<Option<MessageId>>;
    fn get_in_reply_to(&self, refconfig: &RefConfig)        -> Result<Option<MessageId>>;

    fn neighbors(&self) -> Result<StoreIdIterator>;
    fn get_neighbors<'a>(&self, store: &'a Store) -> Result<MailIterator<'a>>;

}

impl Mail for Entry {

    fn is_mail(&self) -> Result<bool> {
        self.is::<IsMail>()
    }

    /// Get a value of a single field of the mail file
    fn get_field(&self, refconfig: &RefConfig, field: &str) -> Result<Option<String>> {
        use std::fs::read_to_string;
        use crate::hasher::MailHasher;

        debug!("Getting field in mail: {:?}", field);
        let mail_file_location = self.as_ref_with_hasher::<MailHasher>().get_path(refconfig)?;

        match ::mailparse::parse_mail(read_to_string(mail_file_location.as_path())?.as_bytes())
            .context(format_err!("Cannot parse Email {}", mail_file_location.display()))?
            .headers
            .into_iter()
            .filter_map(|hdr| {
                match hdr.get_key()
                    .context(format_err!("Cannot fetch key '{}' from Email {}", field, mail_file_location.display()))
                    .map_err(Error::from)
                {
                    Ok(k) => if k == field {
                        Some(Ok(hdr))
                    } else {
                        None
                    },
                    Err(e) => Some(Err(e)),
                }
            })
            .next()
        {
            None          => Ok(None),
            Some(Err(e))  => Err(e),
            Some(Ok(hdr)) => Ok(Some(hdr.get_value()?))
        }
    }

    /// Get a value of the `From` field of the mail file
    ///
    /// # Note
    ///
    /// Use `Mail::mail_header()` if you need to read more than one field.
    fn get_from(&self, refconfig: &RefConfig) -> Result<Option<String>> {
        self.get_field(refconfig, "From")
    }

    /// Get a value of the `To` field of the mail file
    ///
    /// # Note
    ///
    /// Use `Mail::mail_header()` if you need to read more than one field.
    fn get_to(&self, refconfig: &RefConfig) -> Result<Option<String>> {
        self.get_field(refconfig, "To")
    }

    /// Get a value of the `Subject` field of the mail file
    ///
    /// # Note
    ///
    /// Use `Mail::mail_header()` if you need to read more than one field.
    fn get_subject(&self, refconfig: &RefConfig) -> Result<Option<String>> {
        self.get_field(refconfig, "Subject")
    }

    /// Get a value of the `Message-ID` field of the mail file
    ///
    /// # Note
    ///
    /// Use `Mail::mail_header()` if you need to read more than one field.
    fn get_message_id(&self, refconfig: &RefConfig) -> Result<Option<MessageId>> {
        if let Some(s) = self.get_header().read("mail.message-id")? {
            let s = s.as_str()
                .ok_or_else(|| format_err!("'mail.message-id' is not a String in {}", self.get_location()))?;
            Ok(Some(MessageId::from(String::from(s))))
        } else {
            self.get_field(refconfig, "Message-ID")
                .map(|o| o.map(crate::util::strip_message_delimiters).map(MessageId::from))
        }
    }

    /// Get a value of the `In-Reply-To` field of the mail file
    ///
    /// # Note
    ///
    /// Use `Mail::mail_header()` if you need to read more than one field.
    fn get_in_reply_to(&self, refconfig: &RefConfig) -> Result<Option<MessageId>> {
        self.get_field(refconfig, "In-Reply-To")
            .map(|o| o.map(crate::util::strip_message_delimiters).map(MessageId::from))
    }

    /// Get all direct neighbors for the Mail
    ///
    /// # Note
    ///
    /// This fetches only the neighbors which are linked. So it basically only checks the entries
    /// which this entry is linked to and filters them for Mail::is_mail()
    ///
    /// # Warning
    ///
    /// Might yield store entries which are not a Mail in the Mail::is_mail() sence but are simply
    /// stored in /mail in the store.
    ///
    /// To be sure, you should filter this iterator after getting the FileLockEntries from Store.
    /// Or use `Mail::get_neighbors(&store)`.
    ///
    fn neighbors(&self) -> Result<StoreIdIterator> {
        let iter = self
            .links()?
            .map(|link| link.into())
            .filter(|id: &StoreId| id.is_in_collection(&["mail"]))
            .map(Ok);

        Ok(StoreIdIterator::new(Box::new(iter)))
    }

    /// Get alldirect neighbors for the Mail (as FileLockEntry)
    ///
    /// # See also
    ///
    /// Documentation of `Mail::neighbors()`.
    fn get_neighbors<'a>(&self, store: &'a Store) -> Result<MailIterator<'a>> {
        self.links()
            .map(|iter| {
                iter.map(|link| link.into())
                    .map(Ok)
                    .into_get_iter(store)
                    .into_mail_iterator()
            })
    }
}

#[derive(Debug)]
pub struct MailHeader<'a>(Vec<::mailparse::MailHeader<'a>>);

impl<'a> From<Vec<::mailparse::MailHeader<'a>>> for MailHeader<'a> {
    fn from(mh: Vec<::mailparse::MailHeader<'a>>) -> Self {
        MailHeader(mh)
    }
}

impl<'a> MailHeader<'a> {
    /// Get a value of a single field of the mail file
    pub fn get_field(&self, field: &str) -> Result<Option<String>> {
        match self.0
            .iter()
            .filter_map(|hdr| {
                match hdr.get_key()
                    .context(format_err!("Cannot get field {}", field))
                    .map_err(Error::from)
                {
                    Ok(key) => if key == field {
                        Some(Ok(hdr))
                    } else {
                        None
                    },
                    Err(e) => Some(Err(e))
                }
            })
            .next()
        {
            None          => Ok(None),
            Some(Err(e))  => Err(e),
            Some(Ok(hdr)) => Ok(Some(hdr.get_value()?))
        }
    }

    /// Get a value of the `From` field of the mail file
    pub fn get_from(&self) -> Result<Option<String>> {
        self.get_field("From")
    }

    /// Get a value of the `To` field of the mail file
    pub fn get_to(&self) -> Result<Option<String>> {
        self.get_field("To")
    }

    /// Get a value of the `Subject` field of the mail file
    pub fn get_subject(&self) -> Result<Option<String>> {
        self.get_field("Subject")
    }

    /// Get a value of the `Message-ID` field of the mail file
    pub fn get_message_id(&self) -> Result<Option<String>> {
        self.get_field("Message-ID")
    }

    /// Get a value of the `In-Reply-To` field of the mail file
    pub fn get_in_reply_to(&self) -> Result<Option<MessageId>> {
        self.get_field("In-Reply-To")
            .map(|o| o.map(crate::util::strip_message_delimiters).map(MessageId::from))
    }

    // TODO: Offer functionality to load and parse mail _once_ from disk, and then use helper object
    // to offer access to header fields and content.
    //
    // With the existing functionality, one has to open-parse-close the file all the time, which is
    // _NOT_ optimal.
}