2007-06-13 Murray Cumming <murrayc@murrayc.com>
[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 static GList*
69 add_hit (GList *list, TnyHeader *header, TnyFolder *folder)
70 {
71         ModestSearchHit *hit;
72         TnyHeaderFlags   flags;
73         char            *furl;
74         char            *msg_url;
75         const char      *uid;
76         const char      *subject;
77         const char      *sender;
78
79         hit = g_slice_new0 (ModestSearchHit);
80
81         furl = tny_folder_get_url_string (folder);
82         if (!furl) {
83                 g_warning ("%s: tny_folder_get_url_string(): returned NULL for folder. Folder name=%s\n", __FUNCTION__, tny_folder_get_name (folder));
84         }
85         
86         /* Make sure that we use the short UID instead of the long UID,
87          * and/or find out what UID form is used when finding, in camel_data_cache_get().
88          * so we can find what we get. Philip is working on this.
89          */
90         uid = tny_header_get_uid (header);
91         if (!furl) {
92                 g_warning ("%s: tny_header_get_uid(): returned NULL for message with subject=%s\n", __FUNCTION__, tny_header_get_subject (header));
93         }
94         
95         msg_url = g_strdup_printf ("%s/%s", furl, uid);
96         
97         subject = tny_header_get_subject (header);
98         sender = tny_header_get_from (header);
99
100         flags = tny_header_get_flags (header);
101
102         hit->msgid = msg_url;
103         hit->subject = g_strdup_or_null (subject);
104         hit->sender = g_strdup_or_null (sender);
105         hit->folder = furl; /* We just provide our new instance instead of copying it and freeing it. */
106         hit->msize = tny_header_get_message_size (header);
107         hit->has_attachment = flags & TNY_HEADER_FLAG_ATTACHMENTS;
108         hit->is_unread = ! (flags & TNY_HEADER_FLAG_SEEN);
109         hit->timestamp = tny_header_get_date_received (header);
110         
111         return g_list_prepend (list, hit);
112 }
113
114 static gboolean
115 read_chunk (TnyStream *stream, char *buffer, gsize count, gsize *nread)
116 {
117         gsize _nread;
118         gssize res;
119
120         _nread = 0;
121         while (_nread < count) {
122                 res = tny_stream_read (stream,
123                                        buffer + _nread, 
124                                        count - _nread);
125                 if (res == -1) {
126                         *nread = _nread;
127                         return FALSE;
128                 }
129
130                 if (res == 0)
131                         break;
132
133                 _nread += res;
134         }
135
136         *nread = _nread;
137         return TRUE;
138
139
140 }
141
142 #ifdef MODEST_HAVE_OGS
143 static gboolean
144 search_mime_part_ogs (TnyMimePart *part, ModestSearch *search)
145 {
146         TnyStream *stream;
147         char       buffer[4096];
148         gsize      len;
149         gsize      nread;
150         gboolean   is_html = FALSE;
151         gboolean   found;
152         gboolean   res;
153
154
155         if (! tny_mime_part_content_type_is (part, "text/ *") ||
156             ! (is_html = tny_mime_part_content_type_is (part, "text/html"))) {
157                 return FALSE;
158         }
159
160         found = FALSE;
161         len = sizeof (buffer);
162         stream = tny_mime_part_get_stream (part);
163
164         while ((res = read_chunk (stream, buffer, len, &nread))) {
165
166                 if (is_html) {
167
168                         found = ogs_text_searcher_search_html (search->text_searcher,
169                                                                buffer,
170                                                                nread,
171                                                                nread < len);
172                 } else {
173                         found = ogs_text_searcher_search_text (search->text_searcher,
174                                                                buffer,
175                                                                nread);
176                 }
177
178                 if (found) {
179                         break;
180                 }
181
182         }
183
184         if (!found) {
185                 found = ogs_text_searcher_search_done (search->text_searcher);
186         }
187
188         ogs_text_searcher_reset (search->text_searcher);
189
190         return found;
191 }
192 #endif /*MODEST_HAVE_OGS*/
193
194 static gboolean
195 search_mime_part_strcmp (TnyMimePart *part, ModestSearch *search)
196 {
197         TnyStream *stream;
198         char       buffer[8193];
199         char      *chunk[2];
200         gsize      len;
201         gssize     nread;
202         gboolean   found;
203         gboolean   res;
204
205         if (! tny_mime_part_content_type_is (part, "text/ *")) {
206                 return FALSE;
207         }
208
209         found = FALSE;
210         len = (sizeof (buffer) - 1) / 2;
211
212         if (strlen (search->body) > len) {
213                 g_warning ("Search term bigger then chunk."
214                            "We might not find everything");     
215         }
216
217         stream = tny_mime_part_get_stream (part);
218
219         memset (buffer, 0, sizeof (buffer));
220         chunk[0] = buffer;
221         chunk[1] = buffer + len;
222
223         res = read_chunk (stream, chunk[0], len, &nread);
224
225         if (res == FALSE) {
226                 goto done;
227         }
228
229         found = !modest_text_utils_utf8_strcmp (search->body,
230                                                 buffer,
231                                                 TRUE);
232         if (found) {
233                 goto done;
234         }
235
236         /* This works like this:
237          * buffer: [ooooooooooo|xxxxxxxxxxxx|\0] 
238          *          ^chunk[0]  ^chunk[1]
239          * we have prefilled chunk[0] now we always read into chunk[1]
240          * and then move the content of chunk[1] to chunk[0].
241          * The idea is to prevent not finding search terms that are
242          * spread across 2 reads:        
243          * buffer: [ooooooooTES|Txxxxxxxxxxx|\0] 
244          * We should catch that because we always search the whole
245          * buffer not only the chunks.
246          *
247          * Of course that breaks for search terms > sizeof (chunk)
248          * but sizeof (chunk) should be big enough I guess (see
249          * the g_warning in this function)
250          * */   
251         while ((res = read_chunk (stream, chunk[1], len, &nread))) {
252                 buffer[len + nread] = '\0';
253
254                 found = !modest_text_utils_utf8_strcmp (search->body,
255                                                         buffer,
256                                                         TRUE);
257
258                 if (found) {
259                         break;
260                 }
261
262                 /* also move the \0 */
263                 g_memmove (chunk[0], chunk[1], len + 1);
264         }
265
266 done:
267         g_object_unref (stream);
268         return found;
269 }
270
271 static gboolean
272 search_string (const char      *what,
273                const char      *where,
274                ModestSearch    *search)
275 {
276         gboolean found;
277 #ifdef MODEST_HAVE_OGS
278         if (search->flags & MODEST_SEARCH_USE_OGS) {
279                 found = ogs_text_searcher_search_text (search->text_searcher,
280                                                        where,
281                                                        strlen (where));
282
283                 ogs_text_searcher_reset (search->text_searcher);
284         } else {
285 #endif
286                 if (what == NULL || where == NULL) {
287                         return FALSE;
288                 }
289
290                 found = !modest_text_utils_utf8_strcmp (what, where, TRUE);
291 #ifdef MODEST_HAVE_OGS
292         }
293 #endif
294         return found;
295 }
296
297
298
299 /**
300  * modest_search:
301  * @folder: a #TnyFolder instance
302  * @search: a #ModestSearch query
303  *
304  * This operation will search @folder for headers that match the query @search.
305  * It will return a doubly linked list with URIs that point to the message.
306  **/
307 GList *
308 modest_search_folder (TnyFolder *folder, ModestSearch *search)
309 {
310         GList *retval = NULL;
311         TnyIterator *iter;
312         TnyList *list;
313         gboolean (*part_search_func) (TnyMimePart *part, ModestSearch *search);
314
315         part_search_func = search_mime_part_strcmp;
316
317 #ifdef MODEST_HAVE_OGS
318         if (search->flags & MODEST_SEARCH_USE_OGS) {
319         
320                 if (search->text_searcher == NULL && search->query != NULL) {
321                         OgsTextSearcher *text_searcher; 
322
323                         text_searcher = ogs_text_searcher_new (FALSE);
324                         ogs_text_searcher_parse_query (text_searcher, search->query);
325                         search->text_searcher = text_searcher;
326                 }
327
328                 part_search_func = search_mime_part_ogs;
329         }
330 #endif
331
332         list = tny_simple_list_new ();
333         tny_folder_get_headers (folder, list, FALSE, NULL);
334
335         iter = tny_list_create_iterator (list);
336
337         while (!tny_iterator_is_done (iter)) {
338                 TnyHeader *cur = (TnyHeader *) tny_iterator_get_current (iter);
339                 time_t t = tny_header_get_date_sent (cur);
340                 gboolean found = FALSE;
341                 
342                 if (search->flags & MODEST_SEARCH_BEFORE)
343                         if (!(t <= search->before))
344                                 goto go_next;
345
346                 if (search->flags & MODEST_SEARCH_AFTER)
347                         if (!(t >= search->after))
348                                 goto go_next;
349
350                 if (search->flags & MODEST_SEARCH_SIZE)
351                         if (tny_header_get_message_size (cur) < search->minsize)
352                                 goto go_next;
353
354                 if (search->flags & MODEST_SEARCH_SUBJECT) {
355                         const char *str = tny_header_get_subject (cur);
356
357                         if ((found = search_string (search->subject, str, search))) {
358                             retval = add_hit (retval, cur, folder);
359                         }
360                 }
361                 
362                 if (!found && search->flags & MODEST_SEARCH_SENDER) {
363                         const char *str = tny_header_get_from (cur);
364
365                         if ((found = search_string (search->from, str, search))) {
366                                 retval = add_hit (retval, cur, folder);
367                         }
368                 }
369                 
370                 if (!found && search->flags & MODEST_SEARCH_RECIPIENT) {
371                         const char *str = tny_header_get_to (cur);
372
373                         if ((found = search_string (search->recipient, str, search))) {
374                                 retval = add_hit (retval, cur, folder);
375                         }
376                 }
377         
378                 if (!found && search->flags & MODEST_SEARCH_BODY) {
379                         TnyHeaderFlags flags;
380                         GError      *err = NULL;
381                         TnyMsg      *msg = NULL;
382                         TnyIterator *piter;
383                         TnyList     *parts;
384
385                         flags = tny_header_get_flags (cur);
386
387                         if (!(flags & TNY_HEADER_FLAG_CACHED)) {
388                                 goto go_next;
389                         }
390
391                         msg = tny_folder_get_msg (folder, cur, &err);
392
393                         if (err != NULL || msg == NULL) {
394                                 g_warning ("%s: Could not get message.\n", __FUNCTION__);
395                                 g_error_free (err);
396
397                                 if (msg) {
398                                         g_object_unref (msg);
399                                 }
400                         }       
401
402                         parts = tny_simple_list_new ();
403                         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
404
405                         piter = tny_list_create_iterator (parts);
406                         while (!found && !tny_iterator_is_done (piter)) {
407                                 TnyMimePart *pcur = (TnyMimePart *) tny_iterator_get_current (piter);
408
409                                 if ((found = part_search_func (pcur, search))) {
410                                         retval = add_hit (retval, cur, folder);                         
411                                 }
412
413                                 g_object_unref (pcur);
414                                 tny_iterator_next (piter);
415                         }
416
417                         g_object_unref (piter);
418                         g_object_unref (parts);
419                         g_object_unref (msg);
420
421                 }
422
423 go_next:
424                 g_object_unref (cur);
425                 tny_iterator_next (iter);
426         }
427
428         g_object_unref (iter);
429         g_object_unref (list);
430         return retval;
431 }
432
433 GList *
434 modest_search_account (TnyAccount *account, ModestSearch *search)
435 {
436         TnyFolderStore      *store;
437         TnyIterator         *iter;
438         TnyList             *folders;
439         GList               *hits;
440         GError              *error;
441
442         error = NULL;
443         hits = NULL;
444
445         store = TNY_FOLDER_STORE (account);
446
447         folders = tny_simple_list_new ();
448         tny_folder_store_get_folders (store, folders, NULL, &error);
449         
450         if (error != NULL) {
451                 g_object_unref (folders);
452                 return NULL;
453         }
454
455         iter = tny_list_create_iterator (folders);
456         while (!tny_iterator_is_done (iter)) {
457                 TnyFolder *folder;
458                 GList     *res;
459
460                 folder = TNY_FOLDER (tny_iterator_get_current (iter));
461                 
462                 res = modest_search_folder (folder, search);
463
464                 if (res != NULL) {
465                         if (hits == NULL) {
466                                 hits = res;
467                         } else {
468                                 hits = g_list_concat (hits, res);
469                         }
470                 }
471
472                 g_object_unref (folder);
473                 tny_iterator_next (iter);
474         }
475
476         g_object_unref (iter);
477         g_object_unref (folders);
478
479         return hits;
480 }
481
482 GList *
483 modest_search_all_accounts (ModestSearch *search)
484 {
485         ModestTnyAccountStore *astore;
486         TnyList               *accounts;
487         TnyIterator           *iter;
488         GList                 *hits;
489
490         hits = NULL;
491         astore = modest_runtime_get_account_store ();
492
493         accounts = tny_simple_list_new ();
494         tny_account_store_get_accounts (TNY_ACCOUNT_STORE (astore),
495                                         accounts,
496                                         TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
497
498         iter = tny_list_create_iterator (accounts);
499         while (!tny_iterator_is_done (iter)) {
500                 TnyAccount *account;
501                 GList      *res;
502
503                 account = TNY_ACCOUNT (tny_iterator_get_current (iter));
504
505                 g_debug ("DEBUG: %s: Searching account %s",
506                          __FUNCTION__, tny_account_get_name (account));
507                 res = modest_search_account (account, search);
508                 
509                 if (res != NULL) {
510
511                         if (hits == NULL) {
512                                 hits = res;
513                         } else {
514                                 hits = g_list_concat (hits, res);
515                         }
516                 }
517
518                 g_object_unref (account);
519                 tny_iterator_next (iter);
520         }
521
522         g_object_unref (accounts);
523         g_object_unref (iter);
524
525         return hits;
526 }
527
528