summaryrefslogtreecommitdiffstats
path: root/lib/domain/libimagmail/src/mail.rs
blob: bdcee6a2086ddf20bbfe2b39f17a8c5f5e653916 (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
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
//
// 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 resiter::Filter;

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>>;
    fn get_thread<'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()
            })
    }

    /// Get the full thread starting from this Mail
    ///
    /// This function recursively traverses the linked mails, assumes them all to be in the same
    /// thread and returns an iterator over all Mails it finds in this way.
    ///
    /// # Warning
    ///
    /// If a Mail is linked to this mail (even transitively!) but is _not_ in the same thread, it
    /// is considered to be in the same thread.
    ///
    /// This function works recursively. Keep that in mind for large threads. Because it needs to
    /// collect() internally, it might take a lot of memory for large threads.
    ///
    /// # Return value
    ///
    /// This function returns an Iterator over StoreIds in the same thread as this mail itself.
    /// It does not yield any qualification about the distance between a mail in this thread and
    /// this very mail.
    ///
    fn get_thread<'a>(&self, store: &'a Store) -> Result<MailIterator<'a>> {
        trace!("Getting thread, starting point at: {}", self.get_location());
        let mut thread = vec![self.get_location().clone()];

        fn traverse<'a>(entry: &'a Entry, thread: &mut Vec<StoreId>, store: &Store) -> Result<()> {
            // Helper function to get neighbors of a Mail, but filtered
            fn get_filtered_neighbors<'a>(entry: &'a Entry, skiplist: &[StoreId]) -> Result<Vec<StoreId>> {
                trace!("Getting filtered neighbors of {}", entry.get_location());
                entry.neighbors()?.filter_ok(|id| !skiplist.contains(id)).collect()
            }

            // Get the neighbors, filtered by StoreIds which are already in the thread
            // Then iterate over them
            for n in get_filtered_neighbors(entry, thread)? {
                trace!("Fetching {}", n);

                // Get the FileLockEntry for the StoreId, or fail if it cannot be found
                let next_entry = store.get(n.clone())?.ok_or_else(|| format_err!("Cannot find {}", n))?;

                // if the FileLockEntry is a Mail
                if next_entry.is_mail()? {
                    trace!("{} is a Mail", n);
                    thread.push(n); // it belongs to the thread

                    // And then traverse further starting from the current Mail
                    traverse(&next_entry, thread, store)?;
                }
            }

            Ok(())
        }

        trace!("Starting traversing...");
        traverse(self, &mut thread, store)?;
        trace