summaryrefslogtreecommitdiffstats
path: root/lib/domain/libimagmail/src/store.rs
blob: 92b85bfef4e17a8f2336cb4524d945e696732797 (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
//
// 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 std::borrow::Cow;
use std::ops::Deref;

use failure::Fallible as Result;
use toml_query::insert::TomlValueInsertExt;
use toml::Value;
use notmuch_rs::Sort as NotmuchSorting;
use notmuch_rs::Query;

use libimagstore::store::Store;
use libimagstore::store::FileLockEntry;
use libimagentryutil::isa::Is;

use crate::notmuch::connection::NotmuchConnection;
use crate::mail::Mail;
use crate::mail::IsMail;
use crate::mailtree::Mailtree;

pub trait MailStore<'a> {
    fn with_connection(&'a self, c: &'a NotmuchConnection) -> MailStoreWithConnection<'a>;
}

impl<'a> MailStore<'a> for Store {
    fn with_connection(&'a self, c: &'a NotmuchConnection) -> MailStoreWithConnection<'a> {
        debug!("Accessing Store with notmuch connection: {:?}", c);
        MailStoreWithConnection {
            store: self,
            connection: c,
        }
    }
}

#[derive(Debug)]
pub struct MailStoreWithConnection<'a> {
    store: &'a Store,
    connection: &'a NotmuchConnection,
}

impl<'a> Deref for MailStoreWithConnection<'a> {
    type Target = Store;

    fn deref(&self) -> &Self::Target {
        self.store
    }
}

impl<'a> MailStoreWithConnection<'a> {
    pub(crate) fn connection(&self) -> &NotmuchConnection {
        &self.connection
    }

    pub fn import_with_query(&self, q: &str) -> Result<Vec<FileLockEntry<'a>>> {
        let mut new_entries = vec![];

        self.connection
            .execute(|db| {
                let query = db.create_query(q)?;
                query
                    .search_messages()?
                    .map(|message| {
                        self.create_entry_for_id(message.id())
                            .map(|entry| new_entries.push(entry))
                    })
                    .collect::<Result<Vec<_>>>()?;

                Ok(())
            })?;

        Ok(new_entries)
    }

    pub fn query(&'a self, q: &str) -> Result<Vec<FileLockEntry<'a>>> {
        let r = self.build_query(q).execute()?;
        Ok(r)
    }

    pub fn query_atomic(&'a self, q: &str) -> Result<Vec<FileLockEntry<'a>>> {
        let r = self.build_query(q).atomic(true).execute()?;
        Ok(r)
    }

    fn execute_query<'d>(&self, q: Query<'d>) -> Result<Vec<FileLockEntry<'a>>> {
        q.search_messages()?
            .map(|msg| {
                self.get_entry_for_id(msg.id())?
                    .ok_or_else(|| format_err!("Message with id '{}' not found", msg.id()))
            })
            .collect::<Result<Vec<_>>>()
    }

    pub fn build_query<'q>(&'a self, q: &'q str) -> QueryBuilder<'q, 'a> {
        QueryBuilder::new(self, q)
    }

    pub fn get_mail_by_id(&self, id: &str) -> Result<Option<FileLockEntry>> {
        self.get_entry_for_id(Cow::from(id))
    }

    pub fn get_mailtree(&self, root_id: &str) -> Result<Mailtree> {
        trace!("Getting mail by id: {}", root_id);
        let root = self.get_mail_by_id(root_id)?
            .ok_or_else(|| format_err!("Cannot find root message: {}", root_id))?;

        trace!("Getting mail from connection: {:?}", root);
        let root = root.load(self.connection())?
            .ok_or_else(|| format_err!("Cannot load root message: {}", root_id))?;

        trace!("Filling mailtree from: {:?}, {:?}", self, root);
        Mailtree::fill_from(self, root)
    }

    fn create_entry_for_id(&self, id: Cow<str>) -> Result<FileLockEntry<'a>> {
        let sid = crate::module_path::new_id(id.as_ref())?;
        self.store
            .retrieve(sid)
            .and_then(|mut entry| {
                entry.get_header_mut().insert("mail.id", Value::String(String::from(id)))?;
                entry.set_isflag::<IsMail>()?;

                Ok(entry)
            })
    }

    fn get_entry_for_id(&self, id: Cow<str>) -> Result<Option<FileLockEntry<'a>>> {
        let sid = crate::module_path::new_id(id.as_ref())?;
        self.store.get(sid)
    }

}

#[derive(Debug)]
pub struct QueryBuilder<'q, 's> {
    store: &'s MailStoreWithConnection<'s>,
    query: &'q str,
    sorting: Sorting,
    atomic: bool,
}

#[derive(Debug)]
pub enum Sorting {
    OldestFirst,
    NewestFirst,
    MessageId,
    Unsorted,
}

impl Default for Sorting {
    fn default() -> Self {
        Sorting::Unsorted
    }
}

impl Into<NotmuchSorting> for Sorting {
    fn into(self) -> NotmuchSorting {
        match self {
            Sorting::OldestFirst => NotmuchSorting::OldestFirst,
            Sorting::NewestFirst => NotmuchSorting::NewestFirst,
            Sorting::MessageId   => NotmuchSorting::MessageID,
            Sorting::Unsorted    => NotmuchSorting::Unsorted,
        }
    }
}

impl<'q, 's> QueryBuilder<'q, 's> {
    fn new(store: &'s MailStoreWithConnection, query: &'q str) -> Self {
        QueryBuilder {
            store,
            query,
            sorting: Sorting::default(),
            atomic: false,
        }
    }

    pub fn sorted(mut self, sorting: Sorting) -> Self {
        self.sorting = sorting;
        self
    }

    pub fn atomic(mut self, atomic: bool) -> Self {
        self.atomic = atomic;
        self
    }

    pub fn execute(self) -> Result<Vec<FileLockEntry<'s>>> {
        if self.atomic {
            self.store
                .connection
                .execute_atomic(|db| {
                    let query = db.create_query(self.query)?;
                    query.set_sort(self.sorting.into());
                    self.store.execute_query(query)
                })
        } else {
            self.store
                .connection
                .execute(|db| {
                    let query = db.create_query(self.query)?;
                    query.set_sort(self.sorting.into());
                    self.store.execute_query(query)
                })
        }
    }
}