eb0fca22e2185b12d5c88d1b78e1999336a062dd
[modest] / src / modest-search.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #ifndef _GNU_SOURCE
31 #define _GNU_SOURCE
32 #endif
33
34 #ifdef HAVE_CONFIG_H
35 #include <config.h>
36 #endif
37
38 #include <string.h>
39
40 #include <tny-shared.h>
41 #include <tny-folder.h>
42 #include <tny-folder-store.h>
43 #include <tny-list.h>
44 #include <tny-iterator.h>
45 #include <tny-simple-list.h>
46
47 #include <libmodest-dbus-client/libmodest-dbus-client.h>
48
49 #include "modest-text-utils.h"
50 #include "modest-account-mgr.h"
51 #include "modest-tny-account-store.h"
52 #include "modest-tny-account.h"
53 #include "modest-search.h"
54 #include "modest-runtime.h"
55
56 static gchar *
57 g_strdup_or_null (const gchar *str)
58 {
59         gchar *string = NULL;
60
61         if  (str != NULL) {
62                 string = g_strdup (str);
63         }
64
65         return string;
66 }
67
68
69 static GList*
70 add_hit (GList *list, TnyHeader *header, TnyFolder *folder)
71 {
72         ModestSearchHit *hit;
73         TnyHeaderFlags   flags;
74         char            *furl;
75         char            *msg_url;
76         const char      *uid;
77         const char      *subject;
78         const char      *sender;
79
80         hit = g_slice_new0 (ModestSearchHit);
81
82         furl = tny_folder_get_url_string (folder);
83         printf ("DEBUG: %s: folder URL=%s\n", __FUNCTION__, furl);
84         if (!furl) {
85                 g_warning ("%s: tny_folder_get_url_string(): returned NULL for folder. Folder name=%s\n", __FUNCTION__, tny_folder_get_name (folder));
86         }
87         
88         /* Make sure that we use the short UID instead of the long UID,
89          * and/or find out what UID form is used when finding, in camel_data_cache_get().
90          * so we can find what we get. Philip is working on this.
91          */
92         uid = tny_header_get_uid (header);
93         if (!furl) {
94                 g_warning ("%s: tny_header_get_uid(): returned NULL for message with subject=%s\n", __FUNCTION__, tny_header_get_subject (header));
95         }
96         
97         msg_url = g_strdup_printf ("%s/%s", furl, uid);
98         g_free (furl);
99         
100         subject = tny_header_get_subject (header);
101         sender = tny_header_get_from (header);
102         
103         flags = tny_header_get_flags (header);
104
105         hit->msgid = msg_url;
106         hit->subject = g_strdup_or_null (subject);
107         hit->sender = g_strdup_or_null (sender);
108         hit->folder = g_strdup_or_null (tny_folder_get_name (folder));
109         hit->msize = tny_header_get_message_size (header);
110         hit->has_attachment = flags & TNY_HEADER_FLAG_ATTACHMENTS;
111         hit->is_unread = ! (flags & TNY_HEADER_FLAG_SEEN);
112         hit->timestamp = tny_header_get_date_received (header);
113         
114         return g_list_prepend (list, hit);
115 }
116
117 static gboolean
118 read_chunk (TnyStream *stream, char *buffer, gsize count, gsize *nread)
119 {
120         gsize _nread;
121         gssize res;
122
123         _nread = 0;
124         while (_nread < count) {
125                 res = tny_stream_read (stream,
126                                        buffer + _nread, 
127                                        count - _nread);
128                 if (res == -1) {
129                         *nread = _nread;
130                         return FALSE;
131                 }
132
133                 if (res == 0)
134                         break;
135
136                 _nread += res;
137         }
138
139         *nread = _nread;
140         return TRUE;
141
142
143 }
144
145 #ifdef MODEST_HAVE_OGS
146 static gboolean
147 search_mime_part_ogs (TnyMimePart *part, ModestSearch *search)
148 {
149         TnyStream *stream;
150         char       buffer[4096];
151         gsize      len;
152         gsize      nread;
153         gboolean   is_html = FALSE;
154         gboolean   found;
155         gboolean   res;
156
157
158         if (! tny_mime_part_content_type_is (part, "text/ *") ||
159             ! (is_html = tny_mime_part_content_type_is (part, "text/html"))) {
160                 return FALSE;
161         }
162
163         found = FALSE;
164         len = sizeof (buffer);
165         stream = tny_mime_part_get_stream (part);
166
167         while ((res = read_chunk (stream, buffer, len, &nread))) {
168
169                 if (is_html) {
170
171                         found = ogs_text_searcher_search_html (search->text_searcher,
172                                                                buffer,
173                                                                nread,
174                                                                nread < len);
175                 } else {
176                         found = ogs_text_searcher_search_text (search->text_searcher,
177                                                                buffer,
178                                                                nread);
179                 }
180
181                 if (found) {
182                         break;
183                 }
184
185         }
186
187         if (!found) {
188                 found = ogs_text_searcher_search_done (search->text_searcher);
189         }
190
191         ogs_text_searcher_reset (search->text_searcher);
192
193         return found;
194 }
195 #endif /*MODEST_HAVE_OGS*/
196
197 static gboolean
198 search_mime_part_strcmp (TnyMimePart *part, ModestSearch *search)
199 {
200         TnyStream *stream;
201         char       buffer[8193];
202         char      *chunk[2];
203         gssize     len;
204         gsize     nread;
205         gboolean   found;
206         gboolean   res;
207
208         if (! tny_mime_part_content_type_is (part, "text/ *")) {
209                 return FALSE;
210         }
211
212         found = FALSE;
213         len = (sizeof (buffer) - 1) / 2;
214
215         if (strlen (search->body) > len) {
216                 g_warning ("Search term bigger then chunk."
217                            "We might not find everything");     
218         }
219
220         stream = tny_mime_part_get_stream (part);
221
222         memset (buffer, 0, sizeof (buffer));
223         chunk[0] = buffer;
224         chunk[1] = buffer + len;
225
226         res = read_chunk (stream, chunk[0], len, &nread);
227
228         if (res == FALSE) {
229                 goto done;
230         }
231
232         found = !modest_text_utils_utf8_strcmp (search->body,
233                                                 buffer,
234                                                 TRUE);
235         if (found) {
236                 goto done;
237         }
238
239         /* This works like this:
240          * buffer: [ooooooooooo|xxxxxxxxxxxx|\0] 
241          *          ^chunk[0]  ^chunk[1]
242          * we have prefilled chunk[0] now we always read into chunk[1]
243          * and then move the content of chunk[1] to chunk[0].
244          * The idea is to prevent not finding search terms that are
245          * spread across 2 reads:        
246          * buffer: [ooooooooTES|Txxxxxxxxxxx|\0] 
247          * We should catch that because we always search the whole
248          * buffer not only the chunks.
249          *
250          * Of course that breaks for search terms > sizeof (chunk)
251          * but sizeof (chunk) should be big enough I guess (see
252          * the g_warning in this function)
253          * */   
254         while ((res = read_chunk (stream, chunk[1], len, &nread))) {
255                 buffer[len + nread] = '\0';
256
257                 found = !modest_text_utils_utf8_strcmp (search->body,
258                                                         buffer,
259                                                         TRUE);
260
261                 if (found) {
262                         break;
263                 }
264
265                 /* also move the \0 */
266                 g_memmove (chunk[0], chunk[1], len + 1);
267         }
268
269 done:
270         g_object_unref (stream);
271         return found;
272 }
273
274 static gboolean
275 search_string (const char      *what,
276                const char      *where,
277                ModestSearch    *search)
278 {
279         gboolean found;
280 #ifdef MODEST_HAVE_OGS
281         if (search->flags & MODEST_SEARCH_USE_OGS) {
282                 found = ogs_text_searcher_search_text (search->text_searcher,
283                                                        where,
284                                                        strlen (where));
285
286                 ogs_text_searcher_reset (search->text_searcher);
287         } else {
288 #endif
289                 if (what == NULL || where == NULL) {
290                         return FALSE;
291                 }
292
293                 found = !modest_text_utils_utf8_strcmp (what, where, TRUE);
294 #ifdef MODEST_HAVE_OGS
295         }
296 #endif
297         return found;
298 }
299
300
301
302 /**
303  * modest_search:
304  * @folder: a #TnyFolder instance
305  * @search: a #ModestSearch query
306  *
307  * This operation will search @folder for headers that match the query @search.
308  * It will return a doubly linked list with URIs that point to the message.
309  **/
310 GList *
311 modest_search_folder (TnyFolder *folder, ModestSearch *search)
312 {
313         GList *retval = NULL;
314         TnyIterator *iter;
315         TnyList *list;
316         gboolean (*part_search_func) (TnyMimePart *part, ModestSearch *search);
317
318         part_search_func = search_mime_part_strcmp;
319
320 #ifdef MODEST_HAVE_OGS
321         if (search->flags & MODEST_SEARCH_USE_OGS) {
322         
323                 if (search->text_searcher == NULL && search->query != NULL) {
324                         OgsTextSearcher *text_searcher; 
325
326                         text_searcher = ogs_text_searcher_new (FALSE);
327                         ogs_text_searcher_parse_query (text_searcher, search->query);
328                         search->text_searcher = text_searcher;
329                 }
330
331                 part_search_func = search_mime_part_ogs;
332         }
333 #endif
334
335         list = tny_simple_list_new ();
336         tny_folder_get_headers (folder, list, FALSE, NULL);
337
338         iter = tny_list_create_iterator (list);
339
340         while (!tny_iterator_is_done (iter)) {
341                 TnyHeader *cur = (TnyHeader *) tny_iterator_get_current (iter);
342                 time_t t = tny_header_get_date_sent (cur);
343                 gboolean found = FALSE;
344                 
345                 if (search->flags & MODEST_SEARCH_BEFORE)
346                         if (!(t <= search->before))
347                                 goto go_next;
348
349                 if (search->flags & MODEST_SEARCH_AFTER)
350                         if (!(t >= search->after))
351                                 goto go_next;
352
353                 if (search->flags & MODEST_SEARCH_SIZE)
354                         if (tny_header_get_message_size (cur) < search->minsize)
355                                 goto go_next;
356
357                 if (search->flags & MODEST_SEARCH_SUBJECT) {
358                         const char *str = tny_header_get_subject (cur);
359
360                         if ((found = search_string (search->subject, str, search))) {
361                             retval = add_hit (retval, cur, folder);
362                         }
363                 }
364                 
365                 if (!found && search->flags & MODEST_SEARCH_SENDER) {
366                         char *str = g_strdup (tny_header_get_from (cur));
367
368                         if ((found = search_string (search->from, (const gchar *) str, search))) {
369                                 retval = add_hit (retval, cur, folder);
370                         }
371                         g_free (str);
372                 }
373                 
374                 if (!found && search->flags & MODEST_SEARCH_RECIPIENT) {
375                         const char *str = tny_header_get_to (cur);
376
377                         if ((found = search_string (search->recipient, str, search))) {
378                                 retval = add_hit (retval, cur, folder);
379                         }
380                 }
381         
382                 if (!found && search->flags & MODEST_SEARCH_BODY) {
383                         TnyHeaderFlags flags;
384                         GError      *err = NULL;
385                         TnyMsg      *msg = NULL;
386                         TnyIterator *piter;
387                         TnyList     *parts;
388
389                         flags = tny_header_get_flags (cur);
390
391                         if (!(flags & TNY_HEADER_FLAG_CACHED)) {
392                                 goto go_next;
393                         }
394
395                         msg = tny_folder_get_msg (folder, cur, &err);
396
397                         if (err != NULL || msg == NULL) {
398                                 g_warning ("%s: Could not get message.\n", __FUNCTION__);
399                                 g_error_free (err);
400
401                                 if (msg) {
402                                         g_object_unref (msg);
403                                 }
404                         }       
405
406                         parts = tny_simple_list_new ();
407                         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
408
409                         piter = tny_list_create_iterator (parts);
410                         while (!found && !tny_iterator_is_done (piter)) {
411                                 TnyMimePart *pcur = (TnyMimePart *) tny_iterator_get_current (piter);
412
413                                 if ((found = part_search_func (pcur, search))) {
414                                         retval = add_hit (retval, cur, folder);                         
415                                 }
416
417                                 g_object_unref (pcur);
418                                 tny_iterator_next (piter);
419                         }
420
421                         g_object_unref (piter);
422                         g_object_unref (parts);
423                         g_object_unref (msg);
424
425                 }
426
427 go_next:
428                 g_object_unref (cur);
429                 tny_iterator_next (iter);
430         }
431
432         g_object_unref (iter);
433         g_object_unref (list);
434         return retval;
435 }
436
437 GList *
438 modest_search_account (TnyAccount *account, ModestSearch *search)
439 {
440         TnyFolderStore      *store;
441         TnyIterator         *iter;
442         TnyList             *folders;
443         GList               *hits;
444         GError              *error;
445
446         error = NULL;
447         hits = NULL;
448
449         store = TNY_FOLDER_STORE (account);
450
451         folders = tny_simple_list_new ();
452         tny_folder_store_get_folders (store, folders, NULL, &error);
453         
454         if (error != NULL) {
455                 g_object_unref (folders);
456                 return NULL;
457         }
458
459         iter = tny_list_create_iterator (folders);
460         while (!tny_iterator_is_done (iter)) {
461                 TnyFolder *folder;
462                 GList     *res;
463
464                 folder = TNY_FOLDER (tny_iterator_get_current (iter));
465                 
466                 res = modest_search_folder (folder, search);
467
468                 if (res != NULL) {
469                         if (hits == NULL) {
470                                 hits = res;
471                         } else {
472                                 hits = g_list_concat (hits, res);
473                         }
474                 }
475
476                 g_object_unref (folder);
477                 tny_iterator_next (iter);
478         }
479
480         g_object_unref (iter);
481         g_object_unref (folders);
482
483         return hits;
484 }
485
486 GList *
487 modest_search_all_accounts (ModestSearch *search)
488 {
489         ModestTnyAccountStore *astore;
490         TnyList               *accounts;
491         TnyIterator           *iter;
492         GList                 *hits;
493
494         hits = NULL;
495         astore = modest_runtime_get_account_store ();
496
497         accounts = tny_simple_list_new ();
498         tny_account_store_get_accounts (TNY_ACCOUNT_STORE (astore),
499                                         accounts,
500                                         TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
501
502         iter = tny_list_create_iterator (accounts);
503         while (!tny_iterator_is_done (iter)) {
504                 TnyAccount *account;
505                 GList      *res;
506
507                 account = TNY_ACCOUNT (tny_iterator_get_current (iter));
508
509                 g_debug ("DEBUG: %s: Searching account %s",
510                          __FUNCTION__, tny_account_get_name (account));
511                 res = modest_search_account (account, search);
512                 
513                 if (res != NULL) {
514
515                         if (hits == NULL) {
516                                 hits = res;
517                         } else {
518                                 hits = g_list_concat (hits, res);
519                         }
520                 }
521
522                 g_object_unref (account);
523                 tny_iterator_next (iter);
524         }
525
526         g_object_unref (accounts);
527         g_object_unref (iter);
528
529         return hits;
530 }
531
532