2007-06-19 Murray Cumming,,, <murrayc@murrayc-desktop>
[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.\n", __FUNCTION__);
571                 goto out;
572         }
573         g_debug ("%s: Found folder. (%s)\n",  __FUNCTION__, uri);
574         
575
576         msg = tny_folder_find_msg (folder, uri, &err);
577         
578         if (!msg) {
579                 g_debug ("%s: tny_folder_find_msg() failed for folder %s\n  with error=%s.\n",
580                          __FUNCTION__, tny_folder_get_id (folder), err->message);
581         }
582
583 out:
584         if (err)
585                 g_error_free (err);
586
587         if (account && !msg) {
588                 g_object_unref (account);
589                 *ac_out = NULL;
590         }
591
592         if (folder) {
593                 g_object_unref (folder);
594         }
595
596         return msg;
597 }
598
599 static gboolean
600 on_idle_open_message (gpointer user_data)
601 {
602         ModestWindow *msg_view;
603         TnyMsg       *msg;
604         TnyAccount   *account;
605         TnyHeader    *header; 
606         const char   *msg_uid;
607         const char   *account_name;
608         char         *uri;
609        
610         uri = (char *) user_data;
611
612         g_debug ("%s: Trying to find msg by url: %s", __FUNCTION__, uri);       
613         msg = find_message_by_url (uri, &account);
614         g_free (uri);
615
616         if (msg == NULL) {
617                 g_debug ("  %s: message not found.", __FUNCTION__);
618                 return FALSE;
619         }
620         g_debug ("  %s: Found message.", __FUNCTION__);
621
622         header = tny_msg_get_header (msg);
623         account_name = tny_account_get_name (account);
624         msg_uid = tny_header_get_uid (header);
625         
626         msg_view = modest_msg_view_window_new (msg,
627                                                account_name,
628                                                msg_uid);
629         /* TODO: does that leak the msg_view ?! */
630
631         gtk_widget_show_all (GTK_WIDGET (msg_view));
632
633         g_object_unref (header);
634         g_object_unref (account);
635         
636         return FALSE; /* Do not call this callback again. */
637 }
638
639 static gint on_open_message(GArray * arguments, gpointer data, osso_rpc_t * retval)
640 {
641         if (arguments->len != MODEST_DEBUS_OPEN_MESSAGE_ARGS_COUNT)
642         return OSSO_ERROR;
643         
644     /* Use g_idle to context-switch into the application's thread: */
645
646     /* Get the arguments: */
647         osso_rpc_t val = g_array_index(arguments, osso_rpc_t, MODEST_DEBUS_OPEN_MESSAGE_ARG_URI);
648         gchar *uri = g_strdup (val.value.s);
649         
650         /* printf("  debug: to=%s\n", idle_data->to); */
651         g_idle_add(on_idle_open_message, (gpointer)uri);
652         
653         /* Note that we cannot report failures during sending, 
654          * because that would be asynchronous. */
655         return OSSO_OK;
656 }
657
658
659 static gint
660 on_delete_message (GArray *arguments, gpointer data, osso_rpc_t *retval)
661 {
662         TnyList      *headers;
663         TnyFolder    *folder;
664         TnyIterator  *iter; 
665         TnyHeader    *header;
666         TnyHeader    *msg_header;
667         TnyMsg       *msg;
668         TnyAccount   *account;
669         GError       *error;
670         osso_rpc_t    val;
671         const char   *uri;
672         const char   *uid;
673         gint          res;
674
675         if (arguments->len != MODEST_DEBUS_DELETE_MESSAGE_ARGS_COUNT) {
676                 return OSSO_ERROR;
677         }
678
679         val = g_array_index (arguments,
680                              osso_rpc_t,
681                              MODEST_DEBUS_DELETE_MESSAGE_ARG_URI);
682
683         uri = (const char *) val.value.s;
684
685         g_debug ("Searching message (delete message)");
686         
687         msg = find_message_by_url (uri, &account);
688
689         if (msg == NULL) {
690                 return OSSO_ERROR;
691         }
692
693         g_debug ("Found message");
694         
695         msg_header = tny_msg_get_header (msg);
696         uid = tny_header_get_uid (msg_header);
697         folder = tny_msg_get_folder (msg);
698
699
700         /* tny_msg_get_header () flaw:
701          * From tinythingy doc: You can't use the returned instance with the
702          * TnyFolder operations
703          *
704          * To get a header instance that will work with these folder methods,
705          * you can use tny_folder_get_headers.
706          *
707          * Ok, we will do so then. Sigh.
708          * */
709         headers = tny_simple_list_new ();
710
711         tny_folder_get_headers (folder, headers, TRUE, NULL);
712         iter = tny_list_create_iterator (headers);
713         header = NULL;
714
715         g_debug ("Searching header for msg in folder");
716         while (!tny_iterator_is_done (iter)) {
717                 const char *cur_id;
718
719                 header = TNY_HEADER (tny_iterator_get_current (iter));
720                 cur_id = tny_header_get_uid (header);
721                 
722                 if (cur_id && uid && g_str_equal (cur_id, uid)) {
723                         g_debug ("Found correspoding header from folder");
724                         break;
725                 }
726
727                 header = NULL;
728                 g_object_unref (header);
729                 tny_iterator_next (iter);
730         }
731
732         g_object_unref (iter);
733         g_object_unref (headers);
734         
735         g_object_unref (msg_header);
736         g_object_unref (msg);
737
738         if (header == NULL) {
739                 g_object_unref (folder);
740                 return OSSO_ERROR;
741         }
742
743
744         error = NULL;
745         res = OSSO_OK;
746         tny_folder_remove_msg (folder, header, &error);
747
748         if (error != NULL) {
749                 res = OSSO_ERROR;
750                 g_error_free (error);
751         }
752
753         g_object_unref (folder);
754         return res;
755 }
756
757 static gboolean
758 on_idle_send_receive(gpointer user_data)
759 {
760         ModestWindow *win;
761
762         /* Pick the main window if it exists */
763         win = modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
764
765         /* Send & receive all if "Update automatically" is set */
766         /* TODO: check the auto-update parameter in the configuration */
767         modest_ui_actions_do_send_receive_all (win);
768         
769         return FALSE; /* Do not call this callback again. */
770 }
771
772 static gint on_send_receive(GArray * arguments, gpointer data, osso_rpc_t * retval)
773 {       
774     /* Use g_idle to context-switch into the application's thread: */
775
776     /* This method has no arguments. */
777         
778         /* printf("  debug: to=%s\n", idle_data->to); */
779         g_idle_add(on_idle_send_receive, NULL);
780         
781         /* Note that we cannot report failures during send/receive, 
782          * because that would be asynchronous. */
783         return OSSO_OK;
784 }
785
786 static gboolean
787 on_idle_open_default_inbox(gpointer user_data)
788 {
789         ModestWindow *win = 
790                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
791
792         /* Get the folder view */
793         GtkWidget *folder_view = modest_main_window_get_child_widget (MODEST_MAIN_WINDOW (win),
794                                                            MODEST_WIDGET_TYPE_FOLDER_VIEW);
795         modest_folder_view_select_first_inbox_or_local (
796                 MODEST_FOLDER_VIEW (folder_view));
797         
798         return FALSE; /* Do not call this callback again. */
799 }
800
801 static gint on_open_default_inbox(GArray * arguments, gpointer data, osso_rpc_t * retval)
802 {
803     /* Use g_idle to context-switch into the application's thread: */
804
805     /* This method has no arguments. */
806         
807         g_idle_add(on_idle_open_default_inbox, NULL);
808         
809         /* Note that we cannot report failures during send/receive, 
810          * because that would be asynchronous. */
811         return OSSO_OK;
812 }
813                       
814 /* Callback for normal D-BUS messages */
815 gint modest_dbus_req_handler(const gchar * interface, const gchar * method,
816                       GArray * arguments, gpointer data,
817                       osso_rpc_t * retval)
818 {
819         
820         g_debug ("debug: %s\n", __FUNCTION__);
821         g_debug ("debug: %s: method received: %s\n", __FUNCTION__, method);
822         
823         if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_SEND_MAIL) == 0) {
824                 return on_send_mail (arguments, data, retval);
825         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_MAIL_TO) == 0) {
826                 return on_mail_to (arguments, data, retval);
827         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_OPEN_MESSAGE) == 0) {
828                 return on_open_message (arguments, data, retval);
829         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_SEND_RECEIVE) == 0) {
830                 return on_send_receive (arguments, data, retval);
831         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_COMPOSE_MAIL) == 0) {
832                 return on_compose_mail (arguments, data, retval);
833         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_DELETE_MESSAGE) == 0) {
834                 return on_delete_message (arguments,data, retval);
835         } else if (g_ascii_strcasecmp(method, MODEST_DBUS_METHOD_OPEN_DEFAULT_INBOX) == 0) {
836                 return on_open_default_inbox (arguments, data, retval);
837         }
838         else { 
839                 /* We need to return INVALID here so
840                  * osso is returning DBUS_HANDLER_RESULT_NOT_YET_HANDLED 
841                  * so our modest_dbus_req_filter can kick in!
842                  * */
843                 return OSSO_INVALID;
844         }
845 }
846
847 #define SEARCH_HIT_DBUS_TYPE \
848         DBUS_STRUCT_BEGIN_CHAR_AS_STRING \
849         DBUS_TYPE_STRING_AS_STRING \
850         DBUS_TYPE_STRING_AS_STRING \
851         DBUS_TYPE_STRING_AS_STRING \
852         DBUS_TYPE_STRING_AS_STRING \
853         DBUS_TYPE_UINT64_AS_STRING \
854         DBUS_TYPE_BOOLEAN_AS_STRING \
855         DBUS_TYPE_BOOLEAN_AS_STRING \
856         DBUS_TYPE_INT64_AS_STRING \
857         DBUS_STRUCT_END_CHAR_AS_STRING
858
859 static DBusMessage *
860 search_result_to_message (DBusMessage *reply,
861                            GList       *hits)
862 {
863         DBusMessageIter iter;
864         DBusMessageIter array_iter;
865         GList          *hit_iter;
866
867         dbus_message_iter_init_append (reply, &iter); 
868         dbus_message_iter_open_container (&iter,
869                                           DBUS_TYPE_ARRAY,
870                                           SEARCH_HIT_DBUS_TYPE,
871                                           &array_iter); 
872
873         for (hit_iter = hits; hit_iter; hit_iter = hit_iter->next) {
874                 DBusMessageIter  struct_iter;
875                 ModestSearchHit *hit;
876                 char            *msg_url;
877                 const char      *subject;
878                 const char      *folder;
879                 const char      *sender;
880                 guint64          size;
881                 gboolean         has_attachment;
882                 gboolean         is_unread;
883                 gint64           ts;
884
885                 hit = (ModestSearchHit *) hit_iter->data;
886
887                 msg_url = hit->msgid;
888                 subject = hit->subject;
889                 folder  = hit->folder;
890                 sender  = hit->sender;
891                 size           = hit->msize;
892                 has_attachment = hit->has_attachment;
893                 is_unread      = hit->is_unread;
894                 ts             = hit->timestamp;
895
896                 g_debug ("DEBUG: %s: Adding hit: %s", __FUNCTION__, msg_url);   
897                 
898                 dbus_message_iter_open_container (&array_iter,
899                                                   DBUS_TYPE_STRUCT,
900                                                   NULL,
901                                                   &struct_iter);
902
903                 dbus_message_iter_append_basic (&struct_iter,
904                                                 DBUS_TYPE_STRING,
905                                                 &msg_url);
906
907                 dbus_message_iter_append_basic (&struct_iter,
908                                                 DBUS_TYPE_STRING,
909                                                 &subject); 
910
911                 dbus_message_iter_append_basic (&struct_iter,
912                                                 DBUS_TYPE_STRING,
913                                                 &folder);
914
915                 dbus_message_iter_append_basic (&struct_iter,
916                                                 DBUS_TYPE_STRING,
917                                                 &sender);
918
919                 dbus_message_iter_append_basic (&struct_iter,
920                                                 DBUS_TYPE_UINT64,
921                                                 &size);
922
923                 dbus_message_iter_append_basic (&struct_iter,
924                                                 DBUS_TYPE_BOOLEAN,
925                                                 &has_attachment);
926
927                 dbus_message_iter_append_basic (&struct_iter,
928                                                 DBUS_TYPE_BOOLEAN,
929                                                 &is_unread);
930                 
931                 dbus_message_iter_append_basic (&struct_iter,
932                                                 DBUS_TYPE_INT64,
933                                                 &ts);
934
935                 dbus_message_iter_close_container (&array_iter,
936                                                    &struct_iter); 
937
938                 g_free (hit->msgid);
939                 g_free (hit->subject);
940                 g_free (hit->folder);
941                 g_free (hit->sender);
942
943                 g_slice_free (ModestSearchHit, hit);
944         }
945
946         dbus_message_iter_close_container (&iter, &array_iter);
947
948         return reply;
949 }
950
951 DBusHandlerResult
952 modest_dbus_req_filter (DBusConnection *con,
953                         DBusMessage    *message,
954                         void           *user_data)
955 {
956         gboolean  handled = FALSE;
957         DBusError error;
958
959         if (dbus_message_is_method_call (message,
960                                          MODEST_DBUS_IFACE,
961                                          MODEST_DBUS_METHOD_SEARCH)) {
962                 ModestDBusSearchFlags dbus_flags;
963                 ModestSearch  search;
964                 DBusMessage  *reply = NULL;
965                 dbus_bool_t  res;
966                 dbus_int64_t sd_v;
967                 dbus_int64_t ed_v;
968                 dbus_int32_t flags_v;
969                 dbus_uint32_t serial;
970                 dbus_uint32_t size_v;
971                 char *folder;
972                 char *query;
973                 time_t start_date;
974                 time_t end_date;
975                 GList *hits;
976
977                 handled = TRUE;
978
979                 dbus_error_init (&error);
980
981                 sd_v = ed_v = 0;
982                 flags_v = 0;
983
984                 res = dbus_message_get_args (message,
985                                              &error,
986                                              DBUS_TYPE_STRING, &query,
987                                              DBUS_TYPE_STRING, &folder,
988                                              DBUS_TYPE_INT64, &sd_v,
989                                              DBUS_TYPE_INT64, &ed_v,
990                                              DBUS_TYPE_INT32, &flags_v,
991                                              DBUS_TYPE_UINT32, &size_v,
992                                              DBUS_TYPE_INVALID);
993                 
994                 dbus_flags = (ModestDBusSearchFlags) flags_v;
995                 start_date = (time_t) sd_v;
996                 end_date = (time_t) ed_v;
997
998                 memset (&search, 0, sizeof (search));
999 #ifdef MODEST_HAVE_OGS
1000                 search.query  = query;
1001 #endif
1002                 search.before = start_date;
1003                 search.after  = end_date;
1004                 search.flags  = 0;
1005
1006                 if (dbus_flags & MODEST_DBUS_SEARCH_SUBJECT) {
1007                         search.flags |= MODEST_SEARCH_SUBJECT;
1008                         search.subject = query;
1009                 }
1010
1011                 if (dbus_flags & MODEST_DBUS_SEARCH_SENDER) {
1012                         search.flags |=  MODEST_SEARCH_SENDER;
1013                         search.from = query;
1014                 }
1015
1016                 if (dbus_flags & MODEST_DBUS_SEARCH_RECIPIENT) {
1017                         search.flags |= MODEST_SEARCH_RECIPIENT; 
1018                         search.recipient = query;
1019                 }
1020
1021                 if (dbus_flags & MODEST_DBUS_SEARCH_BODY) {
1022                         search.flags |=  MODEST_SEARCH_BODY; 
1023                         search.subject = query;
1024                 }
1025
1026                 if (sd_v > 0) {
1027                         search.flags |= MODEST_SEARCH_BEFORE;
1028                         search.before = start_date;
1029                 }
1030
1031                 if (ed_v > 0) {
1032                         search.flags |= MODEST_SEARCH_AFTER;
1033                         search.after = end_date;
1034                 }
1035
1036                 if (size_v > 0) {
1037                         search.flags |= MODEST_SEARCH_SIZE;
1038                         search.minsize = size_v;
1039                 }
1040
1041 #ifdef MODEST_HAVE_OGS
1042                 search.flags |= MODEST_SEARCH_USE_OGS;
1043                 g_debug ("Starting search for %s", search.query);
1044 #endif
1045                 hits = modest_search_all_accounts (&search);
1046
1047                 reply = dbus_message_new_method_return (message);
1048
1049                 search_result_to_message (reply, hits);
1050
1051                 if (reply == NULL) {
1052                         g_warning ("Could not create reply");
1053                 }
1054
1055                 if (reply) {
1056                         dbus_connection_send (con, reply, &serial);
1057                         dbus_connection_flush (con);
1058                         dbus_message_unref (reply);
1059                 }
1060
1061                 g_list_free (hits);
1062
1063         }
1064         
1065
1066         return (handled ? 
1067                 DBUS_HANDLER_RESULT_HANDLED :
1068                 DBUS_HANDLER_RESULT_NOT_YET_HANDLED);
1069 }
1070
1071
1072 void
1073 modest_osso_cb_hw_state_handler(osso_hw_state_t *state, gpointer data)
1074 {
1075         /* TODO? */
1076     /* printf("%s()\n", __PRETTY_FUNCTION__); */
1077
1078     if(state->system_inactivity_ind)
1079     {
1080     }
1081     else if(state->save_unsaved_data_ind)
1082     {
1083     }
1084     else
1085     {
1086     
1087     }
1088
1089     /* printf("debug: %s(): return\n", __PRETTY_FUNCTION__); */
1090 }