2007-06-20 Murray Cumming <murrayc@murrayc.com>
[modest] / src / dbus_api / modest-dbus-callbacks.c
1 /* Copyright (c) 2007, 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 #include "modest-dbus-callbacks.h"
31 #include "modest-runtime.h"
32 #include "modest-account-mgr.h"
33 #include "modest-account-mgr-helpers.h"
34 #include "modest-tny-account.h"
35 #include "modest-ui-actions.h"
36
37 #include "modest-search.h"
38 #include "widgets/modest-msg-edit-window.h"
39 #include "modest-tny-msg.h"
40 #include <libmodest-dbus-client/libmodest-dbus-client.h>
41 #include <libgnomevfs/gnome-vfs-utils.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <glib/gstdio.h>
45 #include <libgnomevfs/gnome-vfs-mime.h>
46 #include <tny-fs-stream.h>
47
48 #include <tny-list.h>
49 #include <tny-iterator.h>
50 #include <tny-simple-list.h>
51
52 typedef struct 
53 {
54         gchar *to;
55         gchar *cc;
56         gchar *bcc;
57         gchar *subject;
58         gchar *body;
59         gchar *attachments;
60 } SendMailIdleData;
61
62 typedef struct 
63 {
64         gchar *to;
65         gchar *cc;
66         gchar *bcc;
67         gchar *subject;
68         gchar *body;
69         gchar *attachments;
70 } ComposeMailIdleData;
71
72 static gboolean
73 on_idle_send_mail(gpointer user_data)
74 {
75         SendMailIdleData *idle_data = (SendMailIdleData*)user_data;
76         
77         /* Get the TnyTransportAccount so we can instantiate a mail operation: */
78         ModestAccountMgr *account_mgr = modest_runtime_get_account_mgr();
79         gchar *account_name = modest_account_mgr_get_default_account (account_mgr);
80         if (!account_name) {
81                 g_printerr ("modest: no account found\n");
82         }
83         
84         TnyTransportAccount *transport_account = NULL;
85         if (account_mgr) {
86                 transport_account = TNY_TRANSPORT_ACCOUNT(modest_tny_account_store_get_transport_account_for_open_connection
87                                       (modest_runtime_get_account_store(),
88                                        account_name));
89         }
90         
91         if (!transport_account) {
92                 g_printerr ("modest: no transport account found for '%s'\n", account_name);
93         }
94         
95         /* Create the mail operation: */
96         if (transport_account) {        
97                 /* Use the mail operation: */
98                 gchar * from = modest_account_mgr_get_from_string (account_mgr,
99                                                                   account_name);
100                 if (!from) {
101                         g_printerr ("modest: no from address for account '%s'\n", account_name);
102                 } else {
103                         ModestMailOperation *mail_operation = modest_mail_operation_new (MODEST_MAIL_OPERATION_TYPE_SEND, NULL);
104                         modest_mail_operation_queue_add (modest_runtime_get_mail_operation_queue (), mail_operation);
105                         
106                         modest_mail_operation_send_new_mail (mail_operation,
107                                              transport_account,
108                                              NULL,
109                                              from, /* from */
110                                              idle_data->to, idle_data->cc, idle_data->bcc, idle_data->subject, 
111                                              idle_data->body, /* plain_body */
112                                              NULL, /* html_body */
113                                              NULL, /* attachments_list, GSList of TnyMimePart. */
114                                              (TnyHeaderFlags)0);
115                                              
116                         g_free (from);
117                         g_object_unref (G_OBJECT (mail_operation));
118                 }
119                                      
120                 g_object_unref (G_OBJECT (transport_account));
121         }
122         
123         g_free (account_name);
124         
125         /* Free the idle data: */
126         g_free (idle_data->to);
127         g_free (idle_data->cc);
128         g_free (idle_data->bcc);
129         g_free (idle_data->subject);
130         g_free (idle_data->body);
131         g_free (idle_data->attachments);
132         g_free (idle_data);
133         
134         return FALSE; /* Do not call this callback again. */
135 }
136
137 /* TODO: Is this actually used by anything?
138  * I guess that everything uses *_compose_mail() instead. murrayc.
139  */
140 static gint on_send_mail(GArray * arguments, gpointer data, osso_rpc_t * retval)
141 {
142         if (arguments->len != MODEST_DEBUS_SEND_MAIL_ARGS_COUNT)
143         return OSSO_ERROR;
144         
145     /* Use g_idle to context-switch into the application's thread: */
146         SendMailIdleData *idle_data = g_new0(SendMailIdleData, 1); /* Freed in the idle callback. */
147         
148     /* Get the arguments: */
149         osso_rpc_t val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_SEND_MAIL_ARG_TO);
150         idle_data->to = g_strdup (val.value.s);
151         
152         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_SEND_MAIL_ARG_CC);
153         idle_data->cc = g_strdup (val.value.s);
154         
155         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_SEND_MAIL_ARG_BCC);
156         idle_data->bcc = g_strdup (val.value.s);
157         
158         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_SEND_MAIL_ARG_SUBJECT);
159         idle_data->subject = g_strdup (val.value.s);
160         
161         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_SEND_MAIL_ARG_BODY);
162         idle_data->body = g_strdup (val.value.s);
163         
164         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_SEND_MAIL_ARG_ATTACHMENTS);
165         idle_data->attachments = g_strdup (val.value.s);
166         
167         /* printf("  debug: to=%s\n", idle_data->to); */
168         g_idle_add(on_idle_send_mail, (gpointer)idle_data);
169         
170         /* Note that we cannot report failures during sending, 
171          * because that would be asynchronous. */
172         return OSSO_OK;
173 }
174
175 /** uri_unescape:
176  * @uri An escaped URI. URIs should always be escaped.
177  * @len The length of the @uri string, or -1 if the string is null terminated.
178  * 
179  * Decode a URI, or URI fragment, as per RFC 1738.
180  * http://www.ietf.org/rfc/rfc1738.txt
181  * 
182  * Return value: An unescaped string. This should be freed with g_free().
183  */
184 static gchar* uri_unescape(const gchar* uri, size_t len)
185 {
186         if (!uri)
187                 return NULL;
188                 
189         if (len == -1)
190                 len = strlen (uri);
191         
192         /* Allocate an extra string so we can be sure that it is null-terminated,
193          * so we can use gnome_vfs_unescape_string().
194          * This is not efficient. */
195         gchar * escaped_nullterminated = g_strndup (uri, len);
196         gchar *result = gnome_vfs_unescape_string (escaped_nullterminated, NULL);
197         g_free (escaped_nullterminated);
198         
199         return result;
200 }
201
202 /** uri_parse_mailto:
203  * @mailto A mailto URI, with the mailto: prefix.
204  * @list_items_and_values: A pointer to a list that should be filled with item namesand value strings, 
205  * with each name item being followed by a value item. This list should be freed with g_slist_free) after 
206  * all the string items have been freed. This parameter may be NULL.
207  * Parse a mailto URI as per RFC2368.
208  * http://www.ietf.org/rfc/rfc2368.txt
209  * 
210  * Return value: The to address, unescaped. This should be freed with g_free().
211  */
212 static gchar* uri_parse_mailto (const gchar* mailto, GSList** list_items_and_values)
213 {
214         const gchar* start_to = NULL;
215         /* Remove the mailto: prefix: 
216          * 7 is the length of "mailto:": */
217         if (strncmp (mailto, "mailto:", 7) == 0) {
218                 start_to = mailto + 7;
219         }
220         
221         if (!start_to)
222                 return NULL;
223         
224         /* Look for ?, or the end of the string, marking the end of the to address: */
225         const size_t len_to = strcspn (start_to, "?");
226         gchar* result_to = uri_unescape (start_to, len_to);
227         printf("debug: result_to=%s\n", result_to);
228         
229         /* Get any other items: */
230         const size_t len_mailto = strlen (start_to);
231         const gchar* p = start_to + len_to + 1; /* parsed so far. */
232         const gchar* end = start_to + len_mailto;
233         /* GSList *items = NULL; */
234         const gchar* start_item_name = p;
235         size_t len_item_name = 0;
236         const gchar* start_item_value = NULL;
237         while (p < end) {
238                 
239                 /* Looking for the end of a name; */
240                 if (start_item_name) {
241                         const size_t len = strcspn (p, "="); /* Returns whole string if none found. */
242                         if (len) {
243                                 /* This marks the end of a name and the start of the value: */
244                                 len_item_name = len;
245                                 
246                                 /* Skip over the name and mark the start of the value: */
247                                 p += (len + 1); /* Skip over the = */
248                                 start_item_value = p;
249                         }
250                 }
251                 
252                 /* Looking for the end of a value: */
253                 if (start_item_value) {
254                         const size_t len = strcspn (p, "?"); /* Returns whole string if none found. */
255                         /* ? marks the start of a new item: */
256                         if (len) {
257                                 if (start_item_name && len_item_name) {
258                                         /* Finish the previously-started item: */
259                                         gchar *item_value = uri_unescape (start_item_value, len);
260                                         gchar *item_name = g_strndup (start_item_name, len_item_name);
261                                         /* printf ("debug: item name=%s, value=%s\n", item_name, item_value); */
262                                         
263                                         /* Append the items to the list */
264                                         if(list_items_and_values) {
265                                                 *list_items_and_values = g_slist_append (*list_items_and_values, item_name);
266                                                 *list_items_and_values = g_slist_append (*list_items_and_values, item_value);
267                                         }
268                                 }
269                                 
270                                 /* Skip over the value and mark the start of a possible new name/value pair: */
271                                 p += (len + 1); /* Skip over the ? */
272                                 start_item_name = p;
273                                 len_item_name = 0;
274                                 start_item_value = NULL;
275                         }
276                 }
277                 
278         }
279         
280         return result_to;
281 }
282
283
284 static gboolean
285 on_idle_mail_to(gpointer user_data)
286 {
287         /* This is based on the implemenation of main.c:start_uil(): */
288         
289         gchar *uri = (gchar*)user_data;
290         GSList *list_names_and_values = NULL;
291         gchar *to = uri_parse_mailto (uri, &list_names_and_values);
292         
293         /* Get the TnyTransportAccount so we can instantiate a mail operation: */
294         ModestAccountMgr *account_mgr = modest_runtime_get_account_mgr();
295         gchar *account_name = modest_account_mgr_get_default_account (account_mgr);
296         if (!account_name) {
297                 g_printerr ("modest: no account found\n");
298         }
299         
300         TnyAccount *account = NULL;
301         if (account_mgr) {
302                 account = modest_tny_account_store_get_transport_account_for_open_connection (
303                         modest_runtime_get_account_store(), account_name);
304         }
305         
306         if (!account) {
307                 g_printerr ("modest: failed to get tny account folder'\n", account_name);
308         } else {
309                 gchar * from = modest_account_mgr_get_from_string (account_mgr,
310                                                                   account_name);
311                 if (!from) {
312                         g_printerr ("modest: no from address for account '%s'\n", account_name);
313                 } else {
314                         const gchar *cc = NULL;
315                         const gchar *bcc = NULL;
316                         const gchar *subject = NULL;
317                         const gchar *body = NULL;
318                         
319                         /* Get the relevant items from the list: */
320                         GSList *list = list_names_and_values;
321                         while (list) {
322                                 const gchar * name = (const gchar*)list->data;
323                                 GSList *list_value = g_slist_next (list);
324                                 const gchar * value = (const gchar*)list_value->data;
325                                 
326                                 if (strcmp (name, "cc") == 0) {
327                                         cc = value;
328                                 } else if (strcmp (name, "bcc") == 0) {
329                                         bcc = value;
330                                 } else if (strcmp (name, "subject") == 0) {
331                                         subject = value;
332                                 } else if (strcmp (name, "body") == 0) {
333                                         body = value;
334                                 }
335                                 
336                                 /* Go to the next pair: */
337                                 if (list_value) {
338                                         list = g_slist_next (list_value);
339                                 } else 
340                                         list = NULL;
341                         }
342                         
343                         /* Create the message: */
344                         TnyMsg *msg  = modest_tny_msg_new (to, from, 
345                                 cc, bcc, subject, body, 
346                                 NULL /* attachments */);
347                                 
348                         if (!msg) {
349                                 g_printerr ("modest: failed to create message\n");
350                         } else
351                         {
352                                 /* Add the message to a folder and show its UI for editing: */
353                                 TnyFolder *folder = modest_tny_account_get_special_folder (account,
354                                                                         TNY_FOLDER_TYPE_DRAFTS);
355                                 if (!folder) {
356                                         g_printerr ("modest: failed to find Drafts folder\n");
357                                 } else {
358                         
359                                         tny_folder_add_msg (folder, msg, NULL); /* TODO: check err */
360                 
361                                         ModestWindow *win = modest_msg_edit_window_new (msg, account_name);
362                                         gtk_widget_show_all (GTK_WIDGET (win));
363                                 
364                                         g_object_unref (G_OBJECT(folder));
365                                 }
366                         
367                                 g_object_unref (G_OBJECT(msg));
368                         }
369                         
370                         g_object_unref (G_OBJECT(account));
371                 }
372         }
373         
374         g_free (account_name);
375         
376         /* Free the list, as required by the uri_parse_mailto() documentation: */
377         if (list_names_and_values)
378                 g_slist_foreach (list_names_and_values, (GFunc)g_free, NULL);
379         g_slist_free (list_names_and_values);
380         
381         g_free(to);
382                 
383         g_free(uri);
384
385         return FALSE; /* Do not call this callback again. */
386 }
387
388 static gint on_mail_to(GArray * arguments, gpointer data, osso_rpc_t * retval)
389 {
390         if (arguments->len != MODEST_DEBUS_MAIL_TO_ARGS_COUNT)
391         return OSSO_ERROR;
392         
393     /* Use g_idle to context-switch into the application's thread: */
394  
395     /* Get the arguments: */
396         osso_rpc_t val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_MAIL_TO_ARG_URI);
397         gchar *uri = g_strdup (val.value.s);
398         
399         /* printf("  debug: to=%s\n", idle_data->to); */
400         g_idle_add(on_idle_mail_to, (gpointer)uri);
401         
402         /* Note that we cannot report failures during sending, 
403          * because that would be asynchronous. */
404         return OSSO_OK;
405 }
406
407
408
409
410
411 static gboolean
412 on_idle_compose_mail(gpointer user_data)
413 {
414         ComposeMailIdleData *idle_data = (ComposeMailIdleData*)user_data;
415         gchar **list = NULL;
416         gint i = 0;
417
418         /* Get the TnyTransportAccount so we can instantiate a mail operation: */
419         ModestAccountMgr *account_mgr = modest_runtime_get_account_mgr();
420         gchar *account_name = modest_account_mgr_get_default_account (account_mgr);
421         if (!account_name) {
422                 g_printerr ("modest: no account found\n");
423         }
424         
425         TnyAccount *account = NULL;
426         if (account_mgr) {
427                 account = modest_tny_account_store_get_transport_account_for_open_connection (
428                         modest_runtime_get_account_store(), account_name);
429         }
430         
431         if (!account) {
432                 g_printerr ("modest: failed to get tny account folder'%s'\n", account_name);
433         } else {
434                 gchar * from = modest_account_mgr_get_from_string (account_mgr,
435                                                                   account_name);
436                 if (!from) {
437                         g_printerr ("modest: no from address for account '%s'\n", account_name);
438                 } else {
439         
440                         /* Create the message: */
441                         TnyMsg *msg  = modest_tny_msg_new (idle_data->to, from, 
442                                 idle_data->cc, idle_data->bcc, idle_data->subject, idle_data->body, 
443                                 NULL); /* NULL because m_t_m_n doesn't use it */
444                                 
445                         if (!msg) {
446                                 g_printerr ("modest: failed to create message\n");
447                         } else
448                         {
449                                 /* Add the message to a folder and show its UI for editing: */
450                                 TnyFolder *folder = modest_tny_account_get_special_folder (account,
451                                                                         TNY_FOLDER_TYPE_DRAFTS);
452                                 if (!folder) {
453                                         g_printerr ("modest: failed to find Drafts folder\n");
454                                 } else {
455                         
456                                         tny_folder_add_msg (folder, msg, NULL); /* TODO: check err */
457                 
458                                         ModestWindow *win = modest_msg_edit_window_new (msg, account_name);
459
460                                         list = g_strsplit(idle_data->attachments, ",", 0);
461                                         for (i=0; list[i] != NULL; i++) {
462                                                 modest_msg_edit_window_attach_file_noninteractive(
463                                                                 (ModestMsgEditWindow *)win, list[i]);
464                                         }
465                                         g_strfreev(list);
466                                         
467                                         gtk_widget_show_all (GTK_WIDGET (win));
468                                 
469                                         g_object_unref (G_OBJECT(folder));
470                                 }
471                         
472                                 g_object_unref (G_OBJECT(msg));
473                         }
474                         
475                         g_object_unref (G_OBJECT(account));
476                 }
477         }
478
479         /* Free the idle data: */
480         g_free (idle_data->to);
481         g_free (idle_data->cc);
482         g_free (idle_data->bcc);
483         g_free (idle_data->subject);
484         g_free (idle_data->body);
485         g_free (idle_data->attachments);
486         g_free (idle_data);
487         
488         g_free (account_name);
489         return FALSE; /* Do not call this callback again. */
490 }
491
492 static gint on_compose_mail(GArray * arguments, gpointer data, osso_rpc_t * retval)
493 {
494
495         
496         if (arguments->len != MODEST_DEBUS_COMPOSE_MAIL_ARGS_COUNT)
497         return OSSO_ERROR;
498         
499         /* Use g_idle to context-switch into the application's thread: */
500         ComposeMailIdleData *idle_data = g_new0(ComposeMailIdleData, 1); /* Freed in the idle callback. */
501         
502         /* Get the arguments: */
503         osso_rpc_t val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_TO);
504         idle_data->to = g_strdup (val.value.s);
505         
506         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_CC);
507         idle_data->cc = g_strdup (val.value.s);
508         
509         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_BCC);
510         idle_data->bcc = g_strdup (val.value.s);
511         
512         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_SUBJECT);
513         idle_data->subject = g_strdup (val.value.s);
514         
515         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_BODY);
516         idle_data->body = g_strdup (val.value.s);
517         
518         val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_COMPOSE_MAIL_ARG_ATTACHMENTS);
519         idle_data->attachments = g_strdup (val.value.s);
520
521         g_idle_add(on_idle_compose_mail, (gpointer)idle_data);
522         
523         /* Note that we cannot report failures during sending, 
524          * because that would be asynchronous. */
525         return OSSO_OK;
526 }
527
528
529 static TnyMsg *
530 find_message_by_url (const char *uri, TnyAccount **ac_out)
531 {
532         ModestTnyAccountStore *astore;
533         TnyAccount            *account;
534         TnyFolder             *folder;
535         TnyMsg                *msg;
536         GError *err = NULL;
537         account = NULL;
538         msg = NULL;
539         folder = NULL;
540
541         astore = modest_runtime_get_account_store ();
542         
543         if (astore == NULL) {
544                 return NULL;
545         }
546
547         account = tny_account_store_find_account (TNY_ACCOUNT_STORE (astore),
548                                                   uri);
549         
550         if (account == NULL) {
551                 g_debug ("%s: tny_account_store_find_account() failed.\n", __FUNCTION__);
552                 return NULL;
553         }
554
555         g_debug ("%s: Found account.\n", __FUNCTION__);
556
557         if ( ! TNY_IS_STORE_ACCOUNT (account)) {
558                 goto out;
559         }
560
561         g_debug ("%s: Account is store account.\n", __FUNCTION__);
562
563         *ac_out = account;
564
565         folder = tny_store_account_find_folder (TNY_STORE_ACCOUNT (account),
566                                                 uri,
567                                                 &err);
568
569         if (folder == NULL) {
570                 g_debug ("%s: tny_store_account_find_folder() failed\naccount=%s, uri=%s.\n", __FUNCTION__, 
571                         tny_account_get_id (TNY_ACCOUNT(account)), uri);
572                 goto out;
573         }
574         g_debug ("%s: Found folder. (%s)\n",  __FUNCTION__, uri);
575         
576
577         msg = tny_folder_find_msg (folder, uri, &err);
578         
579         if (!msg) {
580                 g_debug ("%s: tny_folder_find_msg() failed for folder %s\n  with error=%s.\n",
581                          __FUNCTION__, tny_folder_get_id (folder), err->message);
582         }
583
584 out:
585         if (err)
586                 g_error_free (err);
587
588         if (account && !msg) {
589                 g_object_unref (account);
590                 *ac_out = NULL;
591         }
592
593         if (folder) {
594                 g_object_unref (folder);
595         }
596
597         return msg;
598 }
599
600 static gboolean
601 on_idle_open_message (gpointer user_data)
602 {
603         ModestWindow *msg_view;
604         TnyMsg       *msg;
605         TnyAccount   *account;
606         TnyHeader    *header; 
607         const char   *msg_uid;
608         const char   *account_name;
609         char         *uri;
610        
611         uri = (char *) user_data;
612
613         g_debug ("%s: Trying to find msg by url: %s", __FUNCTION__, uri);       
614         msg = find_message_by_url (uri, &account);
615         g_free (uri);
616
617         if (msg == NULL) {
618                 g_debug ("  %s: message not found.", __FUNCTION__);
619                 return FALSE;
620         }
621         g_debug ("  %s: Found message.", __FUNCTION__);
622
623         header = tny_msg_get_header (msg);
624         account_name = tny_account_get_name (account);
625         msg_uid = tny_header_get_uid (header);
626         
627         msg_view = modest_msg_view_window_new (msg,
628                                                account_name,
629                                                msg_uid);
630         /* TODO: does that leak the msg_view ?! */
631
632         gtk_widget_show_all (GTK_WIDGET (msg_view));
633
634         g_object_unref (header);
635         g_object_unref (account);
636         
637         return FALSE; /* Do not call this callback again. */
638 }
639
640 static gint on_open_message(GArray * arguments, gpointer data, osso_rpc_t * retval)
641 {
642         if (arguments->len != MODEST_DEBUS_OPEN_MESSAGE_ARGS_COUNT)
643         return OSSO_ERROR;
644         
645     /* Use g_idle to context-switch into the application's thread: */
646
647     /* Get the arguments: */
648         osso_rpc_t val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_OPEN_MESSAGE_ARG_URI);
649         gchar *uri = g_strdup (val.value.s);
650         
651         /* printf("  debug: to=%s\n", idle_data->to); */
652         g_idle_add(on_idle_open_message, (gpointer)uri);
653         
654         /* Note that we cannot report failures during sending, 
655          * because that would be asynchronous. */
656         return OSSO_OK;
657 }
658
659
660 static gint
661 on_delete_message (GArray *arguments, gpointer data, osso_rpc_t *retval)
662 {
663         TnyList      *headers;
664         TnyFolder    *folder;
665         TnyIterator  *iter; 
666         TnyHeader    *header;
667         TnyHeader    *msg_header;
668         TnyMsg       *msg;
669         TnyAccount   *account;
670         GError       *error;
671         osso_rpc_t    val;
672         const char   *uri;
673         const char   *uid;
674         gint          res;
675
676         if (arguments->len != MODEST_DEBUS_DELETE_MESSAGE_ARGS_COUNT) {
677                 return OSSO_ERROR;
678         }
679
680         val = g_array_index (arguments,
681                              osso_rpc_t,
682                              MODEST_DEBUS_DELETE_MESSAGE_ARG_URI);
683
684         uri = (const char *) val.value.s;
685
686         g_debug ("Searching message (delete message)");
687         
688         msg = find_message_by_url (uri, &account);
689
690         if (msg == NULL) {
691                 return OSSO_ERROR;
692         }
693
694         g_debug ("Found message");
695         
696         msg_header = tny_msg_get_header (msg);
697         uid = tny_header_get_uid (msg_header);
698         folder = tny_msg_get_folder (msg);
699
700
701         /* tny_msg_get_header () flaw:
702          * From tinythingy doc: You can't use the returned instance with the
703          * TnyFolder operations
704          *
705          * To get a header instance that will work with these folder methods,
706          * you can use tny_folder_get_headers.
707          *
708          * Ok, we will do so then. Sigh.
709          * */
710         headers = tny_simple_list_new ();
711
712         tny_folder_get_headers (folder, headers, TRUE, NULL);
713         iter = tny_list_create_iterator (headers);
714         header = NULL;
715
716         g_debug ("Searching header for msg in folder");
717         while (!tny_iterator_is_done (iter)) {
718                 const char *cur_id;
719
720                 header = TNY_HEADER (tny_iterator_get_current (iter));
721                 cur_id = tny_header_get_uid (header);
722                 
723                 if (cur_id && uid && g_str_equal (cur_id, uid)) {
724                         g_debug ("Found correspoding header from folder");
725                         break;
726                 }
727
728                 header = NULL;
729                 g_object_unref (header);
730                 tny_iterator_next (iter);
731         }
732
733         g_object_unref (iter);
734         g_object_unref (headers);
735         
736         g_object_unref (msg_header);
737         g_object_unref (msg);
738
739         if (header == NULL) {
740                 g_object_unref (folder);
741                 return OSSO_ERROR;
742         }
743
744
745         error = NULL;
746         res = OSSO_OK;
747         tny_folder_remove_msg (folder, header, &error);
748
749         if (error != NULL) {
750                 res = OSSO_ERROR;
751                 g_error_free (error);
752         }
753
754         g_object_unref (folder);
755         return res;
756 }
757
758 static gboolean
759 on_idle_send_receive(gpointer user_data)
760 {
761         ModestWindow *win;
762
763         /* Pick the main window if it exists */
764         win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
765
766         /* Send & receive all if "Update automatically" is set */
767         /* TODO: check the auto-update parameter in the configuration */
768         modest_ui_actions_do_send_receive_all (win);
769         
770         return FALSE; /* Do not call this callback again. */
771 }
772
773 static gint on_send_receive(GArray * arguments, gpointer data, osso_rpc_t * retval)
774 {       
775     /* Use g_idle to context-switch into the application's thread: */
776
777     /* This method has no arguments. */
778         
779         /* printf("  debug: to=%s\n", idle_data->to); */
780         g_idle_add(on_idle_send_receive, NULL);
781         
782         /* Note that we cannot report failures during send/receive, 
783          * because that would be asynchronous. */
784         return OSSO_OK;
785 }
786
787 static gboolean
788 on_idle_open_default_inbox(gpointer user_data)
789 {
790         ModestWindow *win = 
791                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
792
793         /* Get the folder view */
794         GtkWidget *folder_view = modest_main_window_get_child_widget (MODEST_MAIN_WINDOW (win),
795                                                            MODEST_WIDGET_TYPE_FOLDER_VIEW);
796         modest_folder_view_select_first_inbox_or_local (
797                 MODEST_FOLDER_VIEW (folder_view));
798         
799         return FALSE; /* Do not call this callback again. */
800 }
801
802 static gint on_open_default_inbox(GArray * arguments, gpointer data, osso_rpc_t * retval)
803 {
804     /* Use g_idle to context-switch into the application's thread: */
805
806     /* This method has no arguments. */
807         
808         g_idle_add(on_idle_open_default_inbox, NULL);
809         
810         /* Note that we cannot report failures during send/receive, 
811          * because that would be asynchronous. */
812         return OSSO_OK;
813 }
814                       
815 /* Callback for normal D-BUS messages */
816 gint modest_dbus_req_handler(const gchar * interface, const gchar * method,
817                       GArray * arguments, gpointer data,
818                       osso_rpc_t * retval)
819 {
820         
821         g_debug ("debug: %s\n", __FUNCTION__);
822         g_debug ("debug: %s: method received: %s\n", __FUNCTION__, method);
823         
824         if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_SEND_MAIL) == 0) {
825                 return on_send_mail (arguments, data, retval);
826         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_MAIL_TO) == 0) {
827                 return on_mail_to (arguments, data, retval);
828         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_OPEN_MESSAGE) == 0) {
829                 return on_open_message (arguments, data, retval);
830         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_SEND_RECEIVE) == 0) {
831                 return on_send_receive (arguments, data, retval);
832         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_COMPOSE_MAIL) == 0) {
833                 return on_compose_mail (arguments, data, retval);
834         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_DELETE_MESSAGE) == 0) {
835                 return on_delete_message (arguments,data, retval);
836         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_OPEN_DEFAULT_INBOX) == 0) {
837                 return on_open_default_inbox (arguments, data, retval);
838         }
839         else { 
840                 /* We need to return INVALID here so
841                  * osso is returning DBUS_HANDLER_RESULT_NOT_YET_HANDLED 
842                  * so our modest_dbus_req_filter can kick in!
843                  * */
844                 return OSSO_INVALID;
845         }
846 }
847
848 #define SEARCH_HIT_DBUS_TYPE \
849         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
850         DBUS_TYPE_STRING_AS_STRING \
851         DBUS_TYPE_STRING_AS_STRING \
852         DBUS_TYPE_STRING_AS_STRING \
853         DBUS_TYPE_STRING_AS_STRING \
854         DBUS_TYPE_UINT64_AS_STRING \
855         DBUS_TYPE_BOOLEAN_AS_STRING \
856         DBUS_TYPE_BOOLEAN_AS_STRING \
857         DBUS_TYPE_INT64_AS_STRING \
858         DBUS_STRUCT_END_CHAR_AS_STRING
859
860 static DBusMessage *
861 search_result_to_message (DBusMessage *reply,
862                            GList       *hits)
863 {
864         DBusMessageIter iter;
865         DBusMessageIter array_iter;
866         GList          *hit_iter;
867
868         dbus_message_iter_init_append (reply, &iter); 
869         dbus_message_iter_open_container (&iter,
870                                           DBUS_TYPE_ARRAY,
871                                           SEARCH_HIT_DBUS_TYPE,
872                                           &array_iter); 
873
874         for (hit_iter = hits; hit_iter; hit_iter = hit_iter->next) {
875                 DBusMessageIter  struct_iter;
876                 ModestSearchHit *hit;
877                 char            *msg_url;
878                 const char      *subject;
879                 const char      *folder;
880                 const char      *sender;
881                 guint64          size;
882                 gboolean         has_attachment;
883                 gboolean         is_unread;
884                 gint64           ts;
885
886                 hit = (ModestSearchHit *) hit_iter->data;
887
888                 msg_url = hit->msgid;
889                 subject = hit->subject;
890                 folder  = hit->folder;
891                 sender  = hit->sender;
892                 size           = hit->msize;
893                 has_attachment = hit->has_attachment;
894                 is_unread      = hit->is_unread;
895                 ts             = hit->timestamp;
896
897                 g_debug ("DEBUG: %s: Adding hit: %s", __FUNCTION__, msg_url);   
898                 
899                 dbus_message_iter_open_container (&array_iter,
900                                                   DBUS_TYPE_STRUCT,
901                                                   NULL,
902                                                   &struct_iter);
903
904                 dbus_message_iter_append_basic (&struct_iter,
905                                                 DBUS_TYPE_STRING,
906                                                 &msg_url);
907
908                 dbus_message_iter_append_basic (&struct_iter,
909                                                 DBUS_TYPE_STRING,
910                                                 &subject); 
911
912                 dbus_message_iter_append_basic (&struct_iter,
913                                                 DBUS_TYPE_STRING,
914                                                 &folder);
915
916                 dbus_message_iter_append_basic (&struct_iter,
917                                                 DBUS_TYPE_STRING,
918                                                 &sender);
919
920                 dbus_message_iter_append_basic (&struct_iter,
921                                                 DBUS_TYPE_UINT64,
922                                                 &size);
923
924                 dbus_message_iter_append_basic (&struct_iter,
925                                                 DBUS_TYPE_BOOLEAN,
926                                                 &has_attachment);
927
928                 dbus_message_iter_append_basic (&struct_iter,
929                                                 DBUS_TYPE_BOOLEAN,
930                                                 &is_unread);
931                 
932                 dbus_message_iter_append_basic (&struct_iter,
933                                                 DBUS_TYPE_INT64,
934                                                 &ts);
935
936                 dbus_message_iter_close_container (&array_iter,
937                                                    &struct_iter); 
938
939                 g_free (hit->msgid);
940                 g_free (hit->subject);
941                 g_free (hit->folder);
942                 g_free (hit->sender);
943
944                 g_slice_free (ModestSearchHit, hit);
945         }
946
947         dbus_message_iter_close_container (&iter, &array_iter);
948
949         return reply;
950 }
951
952 DBusHandlerResult
953 modest_dbus_req_filter (DBusConnection *con,
954                         DBusMessage    *message,
955                         void           *user_data)
956 {
957         gboolean  handled = FALSE;
958         DBusError error;
959
960         if (dbus_message_is_method_call (message,
961                                          MODEST_DBUS_IFACE,
962                                          MODEST_DBUS_METHOD_SEARCH)) {
963                 ModestDBusSearchFlags dbus_flags;
964                 ModestSearch  search;
965                 DBusMessage  *reply = NULL;
966                 dbus_bool_t  res;
967                 dbus_int64_t sd_v;
968                 dbus_int64_t ed_v;
969                 dbus_int32_t flags_v;
970                 dbus_uint32_t serial;
971                 dbus_uint32_t size_v;
972                 char *folder;
973                 char *query;
974                 time_t start_date;
975                 time_t end_date;
976                 GList *hits;
977
978                 handled = TRUE;
979
980                 dbus_error_init (&error);
981
982                 sd_v = ed_v = 0;
983                 flags_v = 0;
984
985                 res = dbus_message_get_args (message,
986                                              &error,
987                                              DBUS_TYPE_STRING, &query,
988                                              DBUS_TYPE_STRING, &folder,
989                                              DBUS_TYPE_INT64, &sd_v,
990                                              DBUS_TYPE_INT64, &ed_v,
991                                              DBUS_TYPE_INT32, &flags_v,
992                                              DBUS_TYPE_UINT32, &size_v,
993                                              DBUS_TYPE_INVALID);
994                 
995                 dbus_flags = (ModestDBusSearchFlags) flags_v;
996                 start_date = (time_t) sd_v;
997                 end_date = (time_t) ed_v;
998
999                 memset (&search, 0, sizeof (search));
1000 #ifdef MODEST_HAVE_OGS
1001                 search.query  = query;
1002 #endif
1003                 search.before = start_date;
1004                 search.after  = end_date;
1005                 search.flags  = 0;
1006
1007                 if (dbus_flags & MODEST_DBUS_SEARCH_SUBJECT) {
1008                         search.flags |= MODEST_SEARCH_SUBJECT;
1009                         search.subject = query;
1010                 }
1011
1012                 if (dbus_flags & MODEST_DBUS_SEARCH_SENDER) {
1013                         search.flags |=  MODEST_SEARCH_SENDER;
1014                         search.from = query;
1015                 }
1016
1017                 if (dbus_flags & MODEST_DBUS_SEARCH_RECIPIENT) {
1018                         search.flags |= MODEST_SEARCH_RECIPIENT; 
1019                         search.recipient = query;
1020                 }
1021
1022                 if (dbus_flags & MODEST_DBUS_SEARCH_BODY) {
1023                         search.flags |=  MODEST_SEARCH_BODY; 
1024                         search.subject = query;
1025                 }
1026
1027                 if (sd_v > 0) {
1028                         search.flags |= MODEST_SEARCH_BEFORE;
1029                         search.before = start_date;
1030                 }
1031
1032                 if (ed_v > 0) {
1033                         search.flags |= MODEST_SEARCH_AFTER;
1034                         search.after = end_date;
1035                 }
1036
1037                 if (size_v > 0) {
1038                         search.flags |= MODEST_SEARCH_SIZE;
1039                         search.minsize = size_v;
1040                 }
1041
1042 #ifdef MODEST_HAVE_OGS
1043                 search.flags |= MODEST_SEARCH_USE_OGS;
1044                 g_debug ("Starting search for %s", search.query);
1045 #endif
1046                 hits = modest_search_all_accounts (&search);
1047
1048                 reply = dbus_message_new_method_return (message);
1049
1050                 search_result_to_message (reply, hits);
1051
1052                 if (reply == NULL) {
1053                         g_warning ("Could not create reply");
1054                 }
1055
1056                 if (reply) {
1057                         dbus_connection_send (con, reply, &serial);
1058                         dbus_connection_flush (con);
1059                         dbus_message_unref (reply);
1060                 }
1061
1062                 g_list_free (hits);
1063
1064         }
1065         
1066
1067         return (handled ? 
1068                 DBUS_HANDLER_RESULT_HANDLED :
1069                 DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
1070 }
1071
1072
1073 void
1074 modest_osso_cb_hw_state_handler(osso_hw_state_t *state, gpointer data)
1075 {
1076         /* TODO? */
1077     /* printf("%s()\n", __PRETTY_FUNCTION__); */
1078
1079     if(state->system_inactivity_ind)
1080     {
1081     }
1082     else if(state->save_unsaved_data_ind)
1083     {
1084     }
1085     else
1086     {
1087     
1088     }
1089
1090     /* printf("debug: %s(): return\n", __PRETTY_FUNCTION__); */
1091 }