summaryrefslogtreecommitdiff
path: root/crates/jmap/src/email/snippet.rs
blob: 05e2653ee4dd1b4ec88da87ad3c52afc56ebeee6 (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
/*
 * Copyright (c) 2023 Stalwart Labs Ltd.
 *
 * This file is part of Stalwart Mail Server.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 * in the LICENSE file at the top-level directory of this distribution.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * You can be released from the requirements of the AGPLv3 license by
 * purchasing a commercial license. Please contact licensing@stalw.art
 * for more details.
*/

use jmap_proto::{
    error::method::MethodError,
    method::{
        query::Filter,
        search_snippet::{GetSearchSnippetRequest, GetSearchSnippetResponse, SearchSnippet},
    },
    types::{acl::Acl, collection::Collection},
};
use mail_parser::{decoders::html::html_to_text, Message, PartType};
use store::{
    fts::{
        builder::MAX_TOKEN_LENGTH,
        search_snippet::generate_snippet,
        stemmer::Stemmer,
        term_index::{self, TermIndex},
        tokenizers::Tokenizer,
        Language,
    },
    BlobKind,
};

use crate::{auth::AccessToken, JMAP};

use super::index::MAX_MESSAGE_PARTS;

impl JMAP {
    pub async fn email_search_snippet(
        &self,
        request: GetSearchSnippetRequest,
        access_token: &AccessToken,
    ) -> Result<GetSearchSnippetResponse, MethodError> {
        let mut filter_stack = vec![];
        let mut include_term = true;
        let mut terms = vec![];
        let mut match_phrase = false;

        for cond in request.filter {
            match cond {
                Filter::Text(text) | Filter::Subject(text) | Filter::Body(text) => {
                    if include_term {
                        let (text, language) = Language::detect(text, self.config.default_language);
                        if (text.starts_with('"') && text.ends_with('"'))
                            || (text.starts_with('\'') && text.ends_with('\''))
                        {
                            terms.push(
                                Tokenizer::new(&text, language, MAX_TOKEN_LENGTH)
                                    .map(|token| (token.word.into_owned(), None))
                                    .collect::<Vec<_>>(),
                            );
                            match_phrase = true;
                        } else {
                            terms.push(
                                Stemmer::new(&text, language, MAX_TOKEN_LENGTH)
                                    .map(|token| {
                                        (
                                            token.word.into_owned(),
                                            token.stemmed_word.map(|w| w.into_owned()),
                                        )
                                    })
                                    .collect::<Vec<_>>(),
                            );
                        }
                    }
                }
                Filter::And | Filter::Or => {
                    filter_stack.push(cond);
                }
                Filter::Not => {
                    filter_stack.push(cond);
                    include_term = !include_term;
                }
                Filter::Close => {
                    if matches!(filter_stack.pop(), Some(Filter::Not)) {
                        include_term = !include_term;
                    }
                }
                _ => (),
            }
        }
        let account_id = request.account_id.document_id();
        let document_ids = self
            .owned_or_shared_messages(access_token, account_id, Acl::ReadItems)
            .await?;
        let email_ids = request.email_ids.unwrap();
        let mut response = GetSearchSnippetResponse {
            account_id: request.account_id,
            list: Vec::with_capacity(email_ids.len()),
            not_found: vec![],
        };

        if email_ids.len() > self.config.get_max_objects {
            return Err(MethodError::RequestTooLarge);
        }

        for email_id in email_ids {
            let document_id = email_id.document_id();
            let mut snippet = SearchSnippet {
                email_id,
                subject: None,
                preview: None,
            };
            if !document_ids.contains(document_id) {
                response.not_found.push(email_id);
                continue;
            } else if terms.is_empty() {
                response.list.push(snippet);
                continue;
            }

            // Obtain the term index and raw message
            let (term_index, raw_message) = if let (Some(term_index), Some(raw_message)) = (
                self.get_term_index::<TermIndex>(account_id, Collection::Email, document_id)
                    .await?,
                self.get_blob(
                    &BlobKind::LinkedMaildir {
                        account_id,
                        document_id,
                    },
                    0..u32::MAX,
                )
                .await?,
            ) {
                (term_index, raw_message)
            } else {
                response.not_found.push(email_id);
                continue;
            };

            // Parse message
            let message = if let Some(message) = Message::parse(&raw_message) {
                message
            } else {
                response.not_found.push(email_id);
                continue;
            };

            // Build the match terms
            let mut match_terms = Vec::new();
            for term in &terms {
                for (word, stemmed_word) in term {
                    match_terms.push(term_index.get_match_term(word, stemmed_word.as_deref()));
                }
            }

            'outer: for term_group in term_index
                .match_terms(&match_terms, None, match_phrase, true, true)
                .map_err(|err| match err {
                    term_index::Error::InvalidArgument => {
                        MethodError::UnsupportedFilter("Too many search terms.".to_string())
                    }
                    err => {
                        tracing::error!(
                            account_id = account_id,
                            document_id = document_id,
                            reason = ?err,
                            "Failed to generate search snippet.");
                        MethodError::UnsupportedFilter(
                            "Failed to generate search snippet.".to_string(),
                        )
                    }
                })?
                .unwrap_or_default()
            {
                if term_group.part_id == 0 {
                    // Generate subject snippent
                    snippet.subject =
                        generate_snippet(&term_group.terms, message.subject().unwrap_or_default());
                } else {
                    let mut part_num = 1;
                    for part in &message.parts {
                        match &part.body {
                            PartType::Text(text) => {
                                if part_num == term_group.part_id {
                                    snippet.preview = generate_snippet(&term_group.terms, text);
                                    break 'outer;
                                } else {
                                    part_num += 1;
                                }
                            }
                            PartType::Html(html) => {
                                if part_num == term_group.part_id {
                                    snippet.preview =
                                        generate_snippet(&term_group.terms, &html_to_text(html));
                                    break 'outer;
                                } else {
                                    part_num += 1;
                                }
                            }
                            PartType::Message(message) => {
                                if let Some(subject) = message.subject() {
                                    if part_num == term_group.part_id {
                                        snippet.preview =
                                            generate_snippet(&term_group.terms, subject);
                                        break 'outer;
                                    } else {
                                        part_num += 1;
                                    }
                                }
                                for sub_part in message.parts.iter().take(MAX_MESSAGE_PARTS) {
                                    match &sub_part.body {
                                        PartType::Text(text) => {
                                            if part_num == term_group.part_id {
                                                snippet.preview =
                                                    generate_snippet(&term_group.terms, text);
                                                break 'outer;
                                            } else {
                                                part_num += 1;
                                            }
                                        }
                                        PartType::Html(html) => {
                                            if part_num == term_group.part_id {
                                                snippet.preview = generate_snippet(
                                                    &term_group.terms,
                                                    &html_to_text(html),
                                                );
                                                break 'outer;
                                            } else {
                                                part_num += 1;
                                            }
                                        }
                                        _ => (),
                                    }
                                }
                            }
                            _ => (),
                        }
                    }
                }
            }

            response.list.push(snippet);
        }

        Ok(response)
    }
}