summaryrefslogtreecommitdiffstats
path: root/lib/domain/libimagmail/src/mailtree.rs
blob: f2474b792be51959902070fb4b3493089bc0b9bf (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
//
// 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::path::PathBuf;

use failure::Fallible as Result;
use failure::ResultExt;
use indextree::Arena;
use indextree::NodeId;
use indextree::Node;
use itertools::Itertools;

use libimagstore::storeid::StoreId;

use crate::store::MailStoreWithConnection;
use crate::mail::Mail;
use crate::mail::LoadedMail;


#[derive(Debug)]
pub struct Mailtree {
    arena: Arena<String>,
    root: NodeId,
}

impl Mailtree {
    pub(crate) fn fill_from<'a>(store: &'a MailStoreWithConnection<'a>, root: LoadedMail)
        -> Result<Self>
    {
        let mut arena = Arena::<String>::new();
        let root = fill_arena_with(&mut arena, store, root)?;
        trace!("Arena = {:?}", root);
        Ok(Mailtree { arena, root })
    }

    pub fn root(&self) -> Option<&String> {
        self.arena.get(self.root).map(|node| node.get())
    }

    pub fn traverse(&self) -> Traverse {
        Traverse::with(self)
    }
}

fn fill_arena_with<'a>(arena: &mut Arena<String>, store: &'a MailStoreWithConnection<'a>, root: LoadedMail) -> Result<NodeId> {
    trace!("Filling arena starting at: {}", root.get_id());

    let root_id = root.get_id().clone();
    trace!("root_id        = {:?}", root_id);

    let root_node = arena.new_node(root_id);
    trace!("root_node      = {:?}", root_node);

    let root_thread_id = root.get_thread_id().to_owned();
    trace!("root_thread_id = {:?}", root_thread_id);
    drop(root);


    store.connection().execute(|db| {
        let q = format!("thread:{}", root_thread_id);
        trace!("Executing query: {}", q);
        let query = db.create_query(&q)?;
        let r = query.search_threads()?
            .map(|thread| {
                trace!("Found thread: {}", thread.id());
                thread.messages()
                    .map(|msg| {
                        let id = msg.id();
                        trace!("Found Message: {}", id);

                        let id = id.into_owned();
                        let new_node_id = arena.new_node(id.clone());
                        root_node.append(new_node_id, arena);
                        id
                    })
                    .collect::<Vec<String>>()
            })
            .flat_map(|v| v.into_iter())
            .unique()
            .map(Ok)
            .collect::<Result<Vec<String>>>();
        r
    })?
    .into_iter()
    .map(|id: String| {
        let sid = StoreId::new(PathBuf::from(id.clone()))?;
        if store.is_borrowed(sid)? {
            return Ok(())
        }
        let mail = store.get_mail_by_id(&id)
            .context("Getting mail by id")?
            .ok_or_else(|| format_err!("Cannot find mail for id {}", id))?;
        trace!("Fetched from store: {}", mail.get_location());


        let reply = mail
            .load(store.connection())?
            .ok_or_else(|| format_err!("Tried to load unavailable mail: {}", mail.get_location()))?;
        trace!("Loaded from store: {}", reply.get_id());

        trace!("Recursing with: {}", reply.get_id());
        fill_arena_with(arena, store, reply).map(|_| ())
    })
    .collect::<Result<Vec<_>>>()
    .map(|_| root_node)
}

/// A type for traversing the Mailtree
///
/// Implements an iterator that yields the Message IDs combined with an "indentation", which marks
/// how deep the yielded node is in the tree.
#[derive(Debug)]
pub struct Traverse<'a> {
    tree: &'a Mailtree,
    next_node: Option<NodeId>,
    next_indent: usize,
}

impl<'a> Traverse<'a> {
    fn with(tree: &'a Mailtree) -> Self {
        Traverse {
            tree,
            next_node: Some(tree.root),
            next_indent: 0,
        }
    }

    fn get_node(&self, nodeid: NodeId) -> Option<String> {
        self.tree.arena.get(nodeid).map(|n| n.get()).map(ToOwned::to_owned)
    }

    fn get_current_node(&self) -> Option<&Node<String>> {
        self.next_node
            .and_then(|nodeid| self.tree.arena.get(nodeid))
    }

    fn current_node_next_sibling(&self) -> Option<NodeId> {
        self.get_current_node()
            .and_then(|node| node.next_sibling())
    }

    fn current_node_first_child(&self) -> Option<NodeId> {
        self.get_current_node()
            .and_then(|node| node.first_child())
    }

    fn current_node_parent(&self) -> Option<NodeId> {
        self.get_current_node()
            .and_then(|node| node.parent())
    }
}

impl<'a> Iterator for Traverse<'a> {
    type Item = (usize, String); // (Indention, Message Id)

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(current_node) = self.next_node.and_then(|n| self.get_node(n)) {
            let current_indent = self.next_indent;
            trace!("Iterating: {:?}", self);

            if let Some(sibling) = self.current_node_next_sibling() {
                trace!("Sibling found: {:?}", sibling);
                // do not alter indent
                self.next_node = Some(sibling);
                return Some((current_indent, current_node));
            } else {
                trace!("No sibling found");
                if let Some(child) = self.current_node_first_child() {
                    trace!("Child found: {:?}", child);

                    // We have a child, make that the current node and return it
                    self.next_indent += 1;
                    self.next_node = Some(child);
                    return Some((current_indent, current_node));
                } else {
                    trace!("No child found");
                    // We have no siblings and
                    // We have no children
                    // We might have to go back up one level

                    if let Some(parent) = self.current_node_parent() {
                        trace!("Parent found: {:?}", parent);
                        // We have a parent
                        if let Some(parents_sibling) = self.tree.arena.get(parent).and_then(|n| n.next_sibling()) {
                            trace!("Parents sibling found: {:?}", parents_sibling);
                            // And the parent has a sibling
                            //
                            // Make that the next current node and go from there
                            self.next_indent -= 1;
                            self.next_node = Some(parents_sibling);
                            return Some((current_indent, current_node));
                        } else {
                            trace!("No parents sibling found");
                            // We are the last node:
                            // - We have no sibling
                            // - We have no child
                            // - Our parent has no sibling
                            self.next_node = None;
                            return Some((current_indent, current_node))
                        }
                    } else {
                        trace!("No parent found");
                        self.next_node = None;
                        return Some((current_indent, current_node))
                    }
                }
            }
        } else {
            return None;
        }
    }
}