* src/modest-search.c
[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 typedef struct
69 {
70         GMainLoop* loop;
71         TnyAccount *account;
72         gboolean is_online;
73         gint count_tries;
74 } UtilIdleData;
75
76 #define NUMBER_OF_TRIES 10 /* Try approx every second, ten times. */
77
78 static gboolean 
79 on_timeout_check_account_is_online(gpointer user_data)
80 {
81         printf ("DEBUG: %s:\n", __FUNCTION__);
82         UtilIdleData *data = (UtilIdleData*)user_data;
83         
84         gboolean stop_trying = FALSE;
85         if (data && data->account && 
86                 (tny_account_get_connection_status (data->account) == TNY_CONNECTION_STATUS_CONNECTED) )
87         {
88                 data->is_online = TRUE;
89                 
90                 stop_trying = TRUE;
91         }
92         else {
93                 /* Give up if we have tried too many times: */
94                 if (data->count_tries >= NUMBER_OF_TRIES)
95                 {
96                         stop_trying = TRUE;
97                 }
98                 else {
99                         /* Wait for another timeout: */
100                         ++(data->count_tries);
101                 }
102         }
103         
104         if (stop_trying) {
105                 /* Allow the function that requested this idle callback to continue: */
106                 if (data->loop)
107                         g_main_loop_quit (data->loop);
108                 
109                 return FALSE; /* Don't call this again. */
110         } else {
111                 return TRUE; /* Call this timeout callback again. */
112         }
113 }
114
115 /* Return TRUE immediately if the account is already online,
116  * otherwise check every second for NUMBER_OF_TRIES seconds and return TRUE as 
117  * soon as the account is online, or FALSE if the account does 
118  * not become online in the NUMBER_OF_TRIES seconds.
119  * This is useful when the D-Bus method was run immediately after 
120  * the application was started (when using D-Bus activation), 
121  * because the account usually takes a short time to go online.
122  */
123 static gboolean
124 check_and_wait_for_account_is_online(TnyAccount *account)
125 {
126         if (tny_account_get_connection_status (account) == TNY_CONNECTION_STATUS_CONNECTED)
127                 return TRUE;
128                 
129         /* This blocks on the result: */
130         UtilIdleData *data = g_slice_new0 (UtilIdleData);
131         data->is_online = FALSE;
132                 
133         GMainContext *context = NULL; /* g_main_context_new (); */
134         data->loop = g_main_loop_new (context, FALSE /* not running */);
135
136         g_timeout_add (1000, &on_timeout_check_account_is_online, data);
137
138         /* This main loop will run until the idle handler has stopped it: */
139         g_main_loop_run (data->loop);
140
141         g_main_loop_unref (data->loop);
142         /* g_main_context_unref (context); */
143
144         g_slice_free (UtilIdleData, data);
145         
146         return data->is_online; 
147 }
148
149 static GList*
150 add_hit (GList *list, TnyHeader *header, TnyFolder *folder)
151 {
152         ModestSearchHit *hit;
153         TnyHeaderFlags   flags;
154         char            *furl;
155         char            *msg_url;
156         const char      *uid;
157         const char      *subject;
158         const char      *sender;
159
160         hit = g_slice_new0 (ModestSearchHit);
161
162         furl = tny_folder_get_url_string (folder);
163         printf ("DEBUG: %s: folder URL=%s\n", __FUNCTION__, furl);
164         if (!furl) {
165                 g_warning ("%s: tny_folder_get_url_string(): returned NULL for folder. Folder name=%s\n", __FUNCTION__, tny_folder_get_name (folder));
166         }
167         
168         /* Make sure that we use the short UID instead of the long UID,
169          * and/or find out what UID form is used when finding, in camel_data_cache_get().
170          * so we can find what we get. Philip is working on this.
171          */
172         uid = tny_header_get_uid (header);
173         if (!furl) {
174                 g_warning ("%s: tny_header_get_uid(): returned NULL for message with subject=%s\n", __FUNCTION__, tny_header_get_subject (header));
175         }
176         
177         msg_url = g_strdup_printf ("%s/%s", furl, uid);
178         g_free (furl);
179         
180         subject = tny_header_get_subject (header);
181         sender = tny_header_get_from (header);
182         
183         flags = tny_header_get_flags (header);
184
185         hit->msgid = msg_url;
186         hit->subject = g_strdup_or_null (subject);
187         hit->sender = g_strdup_or_null (sender);
188         hit->folder = g_strdup_or_null (tny_folder_get_name (folder));
189         hit->msize = tny_header_get_message_size (header);
190         hit->has_attachment = flags & TNY_HEADER_FLAG_ATTACHMENTS;
191         hit->is_unread = ! (flags & TNY_HEADER_FLAG_SEEN);
192         hit->timestamp = tny_header_get_date_received (header);
193         
194         return g_list_prepend (list, hit);
195 }
196
197 /** Call this until it returns FALSE or nread is set to 0.
198  * 
199  * @result: FALSE is something failed. */
200 static gboolean
201 read_chunk (TnyStream *stream, char *buffer, gsize count, gsize *nread)
202 {
203         gsize _nread = 0;
204         gssize res = 0;
205
206         while (_nread < count) {
207                 res = tny_stream_read (stream,
208                                        buffer + _nread, 
209                                        count - _nread);
210                 if (res == -1) { /* error */
211                         *nread = _nread;
212                         return FALSE;
213                 }
214
215                 _nread += res;
216                 
217                 if (res == 0) { /* no more bytes read. */
218                         *nread = _nread;
219                         return TRUE;
220                 }
221         }
222
223         *nread = _nread;
224         return TRUE;
225 }
226
227 #ifdef MODEST_HAVE_OGS
228 static gboolean
229 search_mime_part_ogs (TnyMimePart *part, ModestSearch *search)
230 {
231         TnyStream *stream = NULL;
232         char       buffer[4096];
233         const gsize len = sizeof (buffer);
234         gsize      nread = 0;
235         gboolean   is_text_html = FALSE;
236         gboolean   found = FALSE;
237         gboolean   res = FALSE;
238
239         gboolean is_text = tny_mime_part_content_type_is (part, "text/*");
240         if (!is_text) {
241                 g_debug ("%s: tny_mime_part_content_type_is() failed to find a "
242                         "text/* MIME part. Content type is %s", 
243                 __FUNCTION__, "Unknown (calling tny_mime_part_get_content_type(part) causes a deadlock)");
244                 
245             /* Retry with specific MIME types, because the wildcard seems to fail
246              * in tinymail.
247              * Actually I'm not sure anymore that it fails, so we could probalby 
248              * remove this later: murrayc */
249             is_text = (
250                 tny_mime_part_content_type_is (part, "text/plain") ||
251                 tny_mime_part_content_type_is (part, "text/html") );
252                 
253                 if (is_text) {
254                   g_debug ("%s: Retryting with text/plain or text/html succeeded", 
255                         __FUNCTION__);  
256                 }
257         }
258         
259         if (!is_text) {
260             return FALSE;
261         }
262         
263         is_text_html = tny_mime_part_content_type_is (part, "text/html");
264
265         stream = tny_mime_part_get_stream (part);
266
267         res = read_chunk (stream, buffer, len, &nread);
268         while (res && (nread > 0)) {
269                 /* search->text_searcher was instantiated in modest_search_folder(). */
270                 
271                 if (is_text_html) {
272
273                         found = ogs_text_searcher_search_html (search->text_searcher,
274                                                                buffer,
275                                                                nread,
276                                                                nread < len);
277                 } else {
278                         found = ogs_text_searcher_search_text (search->text_searcher,
279                                                                buffer,
280                                                                nread);
281                 }
282
283                 if (found) {
284                         break;
285                 }
286                 
287                 nread = 0;
288                 res = read_chunk (stream, buffer, len, &nread);
289         }
290
291         if (!found) {
292                 found = ogs_text_searcher_search_done (search->text_searcher);
293         }
294
295         ogs_text_searcher_reset (search->text_searcher);
296         
297         /* debug stuff:
298         if (!found) {
299                 buffer[len -1] = 0;
300                 printf ("DEBUG: %s: query %s was not found in message text: %s\n", 
301                         __FUNCTION__, search->query, buffer);   
302                 
303         } else {
304                 printf ("DEBUG: %s: found.\n", __FUNCTION__);   
305         }
306         */
307
308         return found;
309 }
310
311 #else
312
313 static gboolean
314 search_mime_part_strcmp (TnyMimePart *part, ModestSearch *search)
315 {
316         TnyStream *stream;
317         char       buffer[8193];
318         char      *chunk[2];
319         gssize     len;
320         gsize     nread;
321         gboolean   found;
322         gboolean   res;
323
324         if (! tny_mime_part_content_type_is (part, "text/*")) {
325                 g_debug ("%s: No text MIME part found.\n", __FUNCTION__);
326                 return FALSE;
327         }
328
329         found = FALSE;
330         len = (sizeof (buffer) - 1) / 2;
331
332         if (strlen (search->body) > len) {
333                 g_warning ("Search term bigger then chunk."
334                            "We might not find everything");     
335         }
336
337         stream = tny_mime_part_get_stream (part);
338
339         memset (buffer, 0, sizeof (buffer));
340         chunk[0] = buffer;
341         chunk[1] = buffer + len;
342
343         res = read_chunk (stream, chunk[0], len, &nread);
344
345         if (res == FALSE) {
346                 goto done;
347         }
348
349         found = !modest_text_utils_utf8_strcmp (search->body,
350                                                 buffer,
351                                                 TRUE);
352         if (found) {
353                 goto done;
354         }
355
356         /* This works like this:
357          * buffer: [ooooooooooo|xxxxxxxxxxxx|\0] 
358          *          ^chunk[0]  ^chunk[1]
359          * we have prefilled chunk[0] now we always read into chunk[1]
360          * and then move the content of chunk[1] to chunk[0].
361          * The idea is to prevent not finding search terms that are
362          * spread across 2 reads:        
363          * buffer: [ooooooooTES|Txxxxxxxxxxx|\0] 
364          * We should catch that because we always search the whole
365          * buffer not only the chunks.
366          *
367          * Of course that breaks for search terms > sizeof (chunk)
368          * but sizeof (chunk) should be big enough I guess (see
369          * the g_warning in this function)
370          * */   
371         while ((res = read_chunk (stream, chunk[1], len, &nread))) {
372                 buffer[len + nread] = '\0';
373
374                 found = !modest_text_utils_utf8_strcmp (search->body,
375                                                         buffer,
376                                                         TRUE);
377
378                 if (found) {
379                         break;
380                 }
381
382                 /* also move the \0 */
383                 g_memmove (chunk[0], chunk[1], len + 1);
384         }
385
386 done:
387         g_object_unref (stream);
388         return found;
389 }
390 #endif /*MODEST_HAVE_OGS*/
391
392 static gboolean
393 search_string (const char      *what,
394                const char      *where,
395                ModestSearch    *search)
396 {
397         gboolean found;
398 #ifdef MODEST_HAVE_OGS
399         if (search->flags & MODEST_SEARCH_USE_OGS) {
400                 found = ogs_text_searcher_search_text (search->text_searcher,
401                                                        where,
402                                                        strlen (where));
403
404                 ogs_text_searcher_reset (search->text_searcher);
405         } else {
406 #endif
407                 if (what == NULL || where == NULL) {
408                         return FALSE;
409                 }
410
411                 found = !modest_text_utils_utf8_strcmp (what, where, TRUE);
412 #ifdef MODEST_HAVE_OGS
413         }
414 #endif
415         return found;
416 }
417
418
419 static gboolean search_mime_part_and_child_parts (TnyMimePart *part, ModestSearch *search)
420 {
421         gboolean found = FALSE;
422         #ifdef MODEST_HAVE_OGS
423         found = search_mime_part_ogs (part, search);
424         #else
425         found = search_mime_part_strcmp (part, search);
426         #endif
427
428         if (found) {    
429                 return found;           
430         }
431         
432         /* Check the child part too, recursively: */
433         TnyList *child_parts = tny_simple_list_new ();
434         tny_mime_part_get_parts (TNY_MIME_PART (part), child_parts);
435
436         TnyIterator *piter = tny_list_create_iterator (child_parts);
437         while (!found && !tny_iterator_is_done (piter)) {
438                 TnyMimePart *pcur = (TnyMimePart *) tny_iterator_get_current (piter);
439                 if (pcur) {
440                         found = search_mime_part_and_child_parts (pcur, search);
441
442                         g_object_unref (pcur);
443                 }
444
445                 tny_iterator_next (piter);
446         }
447
448         g_object_unref (piter);
449         g_object_unref (child_parts);
450         
451         return found;
452 }
453
454 /**
455  * modest_search:
456  * @folder: a #TnyFolder instance
457  * @search: a #ModestSearch query
458  *
459  * This operation will search @folder for headers that match the query @search,
460  * if the folder itself matches the query.
461  * It will return a doubly linked list with URIs that point to the message.
462  **/
463 GList *
464 modest_search_folder (TnyFolder *folder, ModestSearch *search)
465 {
466         /* Check that we should be searching this folder. */
467         /* Note that we don't try to search sub-folders. 
468          * Maybe we should, but that should be specified. */
469         if (search->folder && strlen (search->folder) && (strcmp (tny_folder_get_id (folder), search->folder) != 0))
470                 return NULL;
471         
472         GList *retval = NULL;
473         TnyIterator *iter = NULL;
474         TnyList *list = NULL;
475         
476 #ifdef MODEST_HAVE_OGS
477         if (search->flags & MODEST_SEARCH_USE_OGS) {
478         
479                 if (search->text_searcher == NULL && search->query != NULL) {
480                         OgsTextSearcher *text_searcher; 
481
482                         text_searcher = ogs_text_searcher_new (FALSE);
483                         ogs_text_searcher_parse_query (text_searcher, search->query);
484                         search->text_searcher = text_searcher;
485                 }
486         }
487 #endif
488
489         list = tny_simple_list_new ();
490         GError *error = NULL;
491         tny_folder_get_headers (folder, list, FALSE /* don't refresh */, &error);
492         if (error) {
493                 g_warning ("%s: tny_folder_get_headers() failed with error=%s.\n", 
494                 __FUNCTION__, error->message);
495                 g_error_free (error);
496                 error = NULL;   
497         }
498
499         iter = tny_list_create_iterator (list);
500
501         while (!tny_iterator_is_done (iter)) {
502                 TnyHeader *cur = (TnyHeader *) tny_iterator_get_current (iter);
503                 const time_t t = tny_header_get_date_sent (cur);
504                 gboolean found = FALSE;
505                 
506                 /* Ignore deleted (not yet expunged) emails: */
507                 if (tny_header_get_flags(cur) & TNY_HEADER_FLAG_DELETED)
508                         goto go_next;
509                         
510                 if (search->flags & MODEST_SEARCH_BEFORE)
511                         if (!(t <= search->end_date))
512                                 goto go_next;
513
514                 if (search->flags & MODEST_SEARCH_AFTER)
515                         if (!(t >= search->start_date))
516                                 goto go_next;
517
518                 if (search->flags & MODEST_SEARCH_SIZE)
519                         if (tny_header_get_message_size (cur) < search->minsize)
520                                 goto go_next;
521
522                 if (search->flags & MODEST_SEARCH_SUBJECT) {
523                         const char *str = tny_header_get_subject (cur);
524
525                         if ((found = search_string (search->subject, str, search))) {
526                             retval = add_hit (retval, cur, folder);
527                         }
528                 }
529                 
530                 if (!found && search->flags & MODEST_SEARCH_SENDER) {
531                         char *str = g_strdup (tny_header_get_from (cur));
532
533                         if ((found = search_string (search->from, (const gchar *) str, search))) {
534                                 retval = add_hit (retval, cur, folder);
535                         }
536                         g_free (str);
537                 }
538                 
539                 if (!found && search->flags & MODEST_SEARCH_RECIPIENT) {
540                         const char *str = tny_header_get_to (cur);
541
542                         if ((found = search_string (search->recipient, str, search))) {
543                                 retval = add_hit (retval, cur, folder);
544                         }
545                 }
546         
547                 if (!found && search->flags & MODEST_SEARCH_BODY) {
548                         TnyHeaderFlags flags;
549                         GError      *err = NULL;
550                         TnyMsg      *msg = NULL;
551
552                         flags = tny_header_get_flags (cur);
553
554                         if (!(flags & TNY_HEADER_FLAG_CACHED)) {
555                                 goto go_next;
556                         }
557
558                         msg = tny_folder_get_msg (folder, cur, &err);
559
560                         if (err != NULL || msg == NULL) {
561                                 g_warning ("%s: Could not get message.\n", __FUNCTION__);
562                                 g_error_free (err);
563
564                                 if (msg) {
565                                         g_object_unref (msg);
566                                 }
567                         } else {        
568                         
569                                 found = search_mime_part_and_child_parts (TNY_MIME_PART (msg), 
570                                                                           search);
571                                 if (found) {
572                                         retval = add_hit (retval, cur, folder);
573                                 }
574                         }
575                         
576                         if (msg)
577                                 g_object_unref (msg);
578                 }
579
580 go_next:
581                 g_object_unref (cur);
582                 tny_iterator_next (iter);
583         }
584
585         g_object_unref (iter);
586         g_object_unref (list);
587         return retval;
588 }
589
590 GList *
591 modest_search_account (TnyAccount *account, ModestSearch *search)
592 {
593         TnyFolderStore      *store;
594         TnyIterator         *iter;
595         TnyList             *folders;
596         GList               *hits;
597         GError              *error;
598
599         error = NULL;
600         hits = NULL;
601
602         store = TNY_FOLDER_STORE (account);
603
604         folders = tny_simple_list_new ();
605         tny_folder_store_get_folders (store, folders, NULL, &error);
606         
607         if (error != NULL) {
608                 g_object_unref (folders);
609                 return NULL;
610         }
611
612         iter = tny_list_create_iterator (folders);
613         while (!tny_iterator_is_done (iter)) {
614                 TnyFolder *folder = NULL;
615                 GList     *res = NULL;
616
617                 folder = TNY_FOLDER (tny_iterator_get_current (iter));
618                 if (folder) {
619                         /* g_debug ("DEBUG: %s: searching folder %s.", 
620                                 __FUNCTION__, tny_folder_get_name (folder)); */
621                 
622                         res = modest_search_folder (folder, search);
623
624                         if (res != NULL) {
625                                 if (hits == NULL) {
626                                         hits = res;
627                                 } else {
628                                         hits = g_list_concat (hits, res);
629                                 }
630                         }
631
632                         g_object_unref (folder);
633                 }
634
635                 tny_iterator_next (iter);
636         }
637
638         g_object_unref (iter);
639         g_object_unref (folders);
640
641         /* printf ("DEBUG: %s: hits length = %d\n", __FUNCTION__, g_list_length (hits)); */
642         return hits;
643 }
644
645 GList *
646 modest_search_all_accounts (ModestSearch *search)
647 {
648         /* printf ("DEBUG: %s: query=%s\n", __FUNCTION__, search->query); */
649         ModestTnyAccountStore *astore;
650         TnyList               *accounts;
651         TnyIterator           *iter;
652         GList                 *hits;
653
654         hits = NULL;
655         astore = modest_runtime_get_account_store ();
656
657         accounts = tny_simple_list_new ();
658         tny_account_store_get_accounts (TNY_ACCOUNT_STORE (astore),
659                                         accounts,
660                                         TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
661
662         iter = tny_list_create_iterator (accounts);
663         while (!tny_iterator_is_done (iter)) {
664                 TnyAccount *account = NULL;
665                 GList      *res = NULL;
666
667                 account = TNY_ACCOUNT (tny_iterator_get_current (iter));
668                 if (account) {
669                         /* g_debug ("DEBUG: %s: Searching account %s",
670                          __FUNCTION__, tny_account_get_name (account)); */
671                          
672                         /* Give the account time to go online if necessary, 
673                          * for instance if this is immediately after startup,
674                          * after D-Bus activation: */
675                         if (check_and_wait_for_account_is_online (account)) {
676                                 /* Search: */
677                                 res = modest_search_account (account, search);
678                                 
679                                 if (res != NULL) {      
680                                         if (hits == NULL) {
681                                                 hits = res;
682                                         } else {
683                                                 hits = g_list_concat (hits, res);
684                                         }
685                                 }
686                         }
687                         
688                         g_object_unref (account);
689                 }
690
691                 tny_iterator_next (iter);
692         }
693
694         g_object_unref (accounts);
695         g_object_unref (iter);
696
697         /* printf ("DEBUG: %s: end: hits length=%d\n", __FUNCTION__, g_list_length(hits)); */
698         return hits;
699 }
700
701