summaryrefslogtreecommitdiffstats
path: root/melib/src/mailbox/collection.rs
blob: 9298d3ea5c9b34ad640aa7757814dcf4f2aa59bf (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
use super::*;
use crate::mailbox::backends::FolderHash;
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::ops::{Deref, DerefMut};

use fnv::FnvHashMap;

#[derive(Debug, Clone, Deserialize, Default, Serialize)]
pub struct Collection {
    pub envelopes: FnvHashMap<EnvelopeHash, Envelope>,
    message_ids: FnvHashMap<Vec<u8>, EnvelopeHash>,
    date_index: BTreeMap<UnixTimestamp, EnvelopeHash>,
    subject_index: Option<BTreeMap<String, EnvelopeHash>>,
    pub threads: FnvHashMap<FolderHash, Threads>,
    sent_folder: Option<FolderHash>,
}

impl Drop for Collection {
    fn drop(&mut self) {
        let cache_dir: xdg::BaseDirectories =
            xdg::BaseDirectories::with_profile("meli", "threads".to_string()).unwrap();
        if let Ok(cached) = cache_dir.place_cache_file("threads") {
            /* place result in cache directory */
            let f = match fs::File::create(cached) {
                Ok(f) => f,
                Err(e) => {
                    panic!("{}", e);
                }
            };
            let writer = io::BufWriter::new(f);
            bincode::serialize_into(writer, &self.threads).unwrap();
        }
    }
}

impl Collection {
    pub fn new(envelopes: FnvHashMap<EnvelopeHash, Envelope>) -> Collection {
        let date_index = BTreeMap::new();
        let subject_index = None;
        let message_ids = FnvHashMap::with_capacity_and_hasher(2048, Default::default());

        /* Scrap caching for now. When a cached threads file is loaded, we must remove/rehash the
         * thread nodes that shouldn't exist anymore (e.g. because their file moved from /new to
         * /cur, or it was deleted).
         */
        let threads = FnvHashMap::with_capacity_and_hasher(16, Default::default());

        Collection {
            envelopes,
            date_index,
            message_ids,
            subject_index,
            threads,
            sent_folder: None,
        }
    }

    pub fn len(&self) -> usize {
        self.envelopes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.envelopes.is_empty()
    }

    pub fn remove(&mut self, envelope_hash: EnvelopeHash, folder_hash: FolderHash) {
        debug!("DEBUG: Removing {}", envelope_hash);
        self.envelopes.remove(&envelope_hash);
        self.threads
            .entry(folder_hash)
            .or_default()
            .remove(envelope_hash, &mut self.envelopes);
    }

    pub fn rename(
        &mut self,
        old_hash: EnvelopeHash,
        new_hash: EnvelopeHash,
        folder_hash: FolderHash,
    ) {
        if !self.envelopes.contains_key(&old_hash) {
            return;
        }
        let mut env = self.envelopes.remove(&old_hash).unwrap();
        env.set_hash(new_hash);
        self.message_ids
            .insert(env.message_id().raw().to_vec(), new_hash);
        self.envelopes.insert(new_hash, env);
        {
            if self
                .threads
                .entry(folder_hash)
                .or_default()
                .update_envelope(old_hash, new_hash, &self.envelopes)
                .is_ok()
            {
                return;
            }
        }
        /* envelope is not in threads, so insert it */
        let env = self.envelopes.entry(new_hash).or_default() as *mut Envelope;
        unsafe {
            self.threads
                .entry(folder_hash)
                .or_default()
                .insert(&mut (*env), &self.envelopes);
        }
    }

    pub fn merge(
        &mut self,
        mut envelopes: FnvHashMap<EnvelopeHash, Envelope>,
        folder_hash: FolderHash,
        mailbox: &mut Result<Mailbox>,
        sent_folder: Option<FolderHash>,
    ) {
        self.sent_folder = sent_folder;
        envelopes.retain(|&h, e| {
            if self.message_ids.contains_key(e.message_id().raw()) {
                /* skip duplicates until a better way to handle them is found. */
                //FIXME
                if let Ok(mailbox) = mailbox.as_mut() {
                    mailbox.remove(h);
                }
                false
            } else {
                self.message_ids.insert(e.message_id().raw().to_vec(), h);
                true
            }
        });
        let mut threads = Threads::new(&mut envelopes);

        for (h, e) in envelopes {
            self.envelopes.insert(h, e);
        }
        for (t_fh, t) in self.threads.iter_mut() {
            if self.sent_folder.map(|f| f == folder_hash).unwrap_or(false) {
                let mut ordered_hash_set = threads
                    .hash_set
                    .iter()
                    .cloned()
                    .collect::<Vec<EnvelopeHash>>();
                unsafe {
                    /* FIXME NLL
                     * Sorting ordered_hash_set triggers a borrow which should not happen with NLL
                     * probably */
                    let envelopes = &self.envelopes as *const FnvHashMap<EnvelopeHash, Envelope>;
                    ordered_hash_set.sort_by(|a, b| {
                        (*envelopes)[a]
                            .date()
                            .partial_cmp(&(*(envelopes))[b].date())
                            .unwrap()
                    });
                }
                for h in ordered_hash_set {
                    t.insert_reply(&mut self.envelopes, h);
                }
                continue;
            }
            if self.sent_folder.map(|f| f == *t_fh).unwrap_or(false) {
                let mut ordered_hash_set =
                    t.hash_set.iter().cloned().collect::<Vec<EnvelopeHash>>();
                unsafe {
                    /* FIXME NLL
                     * Sorting ordered_hash_set triggers a borrow which should not happen with NLL
                     * probably */
                    let envelopes = &self.envelopes as *const FnvHashMap<EnvelopeHash, Envelope>;
                    ordered_hash_set.sort_by(|a, b| {
                        (*envelopes)[a]
                            .date()
                            .partial_cmp(&(*(envelopes))[b].date())
                            .unwrap()
                    });
                }
                for h in ordered_hash_set {
                    threads.insert_reply(&mut self.envelopes, h);
                }
            }
        }
        self.threads.insert(folder_hash, threads);
    }

    pub fn update(&mut self, old_hash: EnvelopeHash, envelope: Envelope, folder_hash: FolderHash) {
        self.envelopes.remove(&old_hash);
        let new_hash = envelope.hash();
        self.message_ids
            .insert(envelope.message_id().raw().to_vec(), new_hash);
        self.envelopes.insert(new_hash, envelope);
        if self.sent_folder.map(|f| f == folder_hash).unwrap_or(false) {
            for (_, t) in self.threads.iter_mut() {
                t.update_envelope(old_hash, new_hash, &self.envelopes);
            }
        }
        {
            if self
                .threads
                .entry(folder_hash)
                .or_default()
                .update_envelope(old_hash, new_hash, &self.envelopes)
                .is_ok()
            {
                return;
            }
        }
        /* envelope is not in threads, so insert it */
        let env = self.envelopes.entry(new_hash).or_default() as *mut Envelope;
        unsafe {
            self.threads
                .entry(folder_hash)
                .or_default()
                .insert(&mut (*env), &self.envelopes);
        }
    }

    pub fn insert(&mut self, envelope: Envelope, folder_hash: FolderHash) -> &Envelope {
        let hash = envelope.hash();
        self.message_ids
            .insert(envelope.message_id().raw().to_vec(), hash);
        self.envelopes.insert(hash, envelope);
        self.threads
            .entry(folder_hash)
            .or_default()
            .insert_reply(&mut self.envelopes, hash);
        &self.envelopes[&hash]
    }
    pub fn insert_reply(&mut self, env_hash: EnvelopeHash) {
        for (_, t) in self.threads.iter_mut() {
            t.insert_reply(&mut self.envelopes, env_hash);
        }
    }
}

impl Deref for Collection {
    type Target = FnvHashMap<EnvelopeHash, Envelope>;

    fn deref(&self) -> &FnvHashMap<EnvelopeHash, Envelope> {</