Added support to handle accounts-reloaded signal
[modest] / src / modest-mail-operation.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "modest-mail-operation.h"
31 /* include other impl specific header files */
32 #include <string.h>
33 #include <stdarg.h>
34 #include <tny-mime-part.h>
35 #include <tny-store-account.h>
36 #include <tny-folder-store.h>
37 #include <tny-folder-store-query.h>
38 #include <tny-camel-stream.h>
39 #include <tny-simple-list.h>
40 #include <camel/camel-stream-mem.h>
41 #include <glib/gi18n.h>
42 #include <modest-tny-account.h>
43 #include "modest-text-utils.h"
44 #include "modest-tny-msg-actions.h"
45 #include "modest-tny-platform-factory.h"
46 #include "modest-marshal.h"
47 #include "modest-formatter.h"
48 #include "modest-error.h"
49
50 /* 'private'/'protected' functions */
51 static void modest_mail_operation_class_init (ModestMailOperationClass *klass);
52 static void modest_mail_operation_init       (ModestMailOperation *obj);
53 static void modest_mail_operation_finalize   (GObject *obj);
54
55 static void     status_update_cb     (TnyFolder *folder, 
56                                       const gchar *what, 
57                                       gint status, 
58                                       gint oftotal,
59                                       gpointer user_data);
60 static void     folder_refresh_cb    (TnyFolder *folder, 
61                                       gboolean canceled,
62                                       GError **err,
63                                       gpointer user_data);
64 static void     update_folders_cb    (TnyFolderStore *self, 
65                                       TnyList *list, 
66                                       GError **err, 
67                                       gpointer user_data);
68 static void     add_attachments      (TnyMsg *msg, 
69                                       GList *attachments_list);
70
71
72 static TnyMimePart *         add_body_part    (TnyMsg *msg, 
73                                                const gchar *body,
74                                                const gchar *content_type, 
75                                                gboolean has_attachments);
76
77
78 static void        modest_mail_operation_xfer_folder       (ModestMailOperation *self,
79                                                             TnyFolder *folder,
80                                                             TnyFolderStore *parent,
81                                                             gboolean delete_original);
82
83 static gboolean    modest_mail_operation_xfer_msg          (ModestMailOperation *self,
84                                                             TnyHeader *header, 
85                                                             TnyFolder *folder, 
86                                                             gboolean delete_original);
87
88 enum _ModestMailOperationSignals 
89 {
90         PROGRESS_CHANGED_SIGNAL,
91
92         NUM_SIGNALS
93 };
94
95 typedef struct _ModestMailOperationPrivate ModestMailOperationPrivate;
96 struct _ModestMailOperationPrivate {
97         guint                      done;
98         guint                      total;
99         ModestMailOperationStatus  status;
100         GError                    *error;
101 };
102 #define MODEST_MAIL_OPERATION_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
103                                                    MODEST_TYPE_MAIL_OPERATION, \
104                                                    ModestMailOperationPrivate))
105
106 typedef struct _RefreshFolderAsyncHelper
107 {
108         ModestMailOperation *mail_op;
109         TnyIterator *iter;
110         guint failed;
111         guint canceled;
112
113 } RefreshFolderAsyncHelper;
114
115 /* some utility functions */
116 static char * get_content_type(const gchar *s);
117 static gboolean is_ascii(const gchar *s);
118
119 /* globals */
120 static GObjectClass *parent_class = NULL;
121
122 static guint signals[NUM_SIGNALS] = {0};
123
124 GType
125 modest_mail_operation_get_type (void)
126 {
127         static GType my_type = 0;
128         if (!my_type) {
129                 static const GTypeInfo my_info = {
130                         sizeof(ModestMailOperationClass),
131                         NULL,           /* base init */
132                         NULL,           /* base finalize */
133                         (GClassInitFunc) modest_mail_operation_class_init,
134                         NULL,           /* class finalize */
135                         NULL,           /* class data */
136                         sizeof(ModestMailOperation),
137                         1,              /* n_preallocs */
138                         (GInstanceInitFunc) modest_mail_operation_init,
139                         NULL
140                 };
141                 my_type = g_type_register_static (G_TYPE_OBJECT,
142                                                   "ModestMailOperation",
143                                                   &my_info, 0);
144         }
145         return my_type;
146 }
147
148 static void
149 modest_mail_operation_class_init (ModestMailOperationClass *klass)
150 {
151         GObjectClass *gobject_class;
152         gobject_class = (GObjectClass*) klass;
153
154         parent_class            = g_type_class_peek_parent (klass);
155         gobject_class->finalize = modest_mail_operation_finalize;
156
157         g_type_class_add_private (gobject_class, sizeof(ModestMailOperationPrivate));
158
159         /**
160          * ModestMailOperation::progress-changed
161          * @self: the #MailOperation that emits the signal
162          * @user_data: user data set when the signal handler was connected
163          *
164          * Emitted when the progress of a mail operation changes
165          */
166         signals[PROGRESS_CHANGED_SIGNAL] = 
167                 g_signal_new ("progress_changed",
168                               G_TYPE_FROM_CLASS (gobject_class),
169                               G_SIGNAL_RUN_FIRST,
170                               G_STRUCT_OFFSET (ModestMailOperationClass, progress_changed),
171                               NULL, NULL,
172                               g_cclosure_marshal_VOID__VOID,
173                               G_TYPE_NONE, 0);
174 }
175
176 static void
177 modest_mail_operation_init (ModestMailOperation *obj)
178 {
179         ModestMailOperationPrivate *priv;
180
181         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(obj);
182
183         priv->status   = MODEST_MAIL_OPERATION_STATUS_INVALID;
184         priv->error    = NULL;
185         priv->done     = 0;
186         priv->total    = 0;
187 }
188
189 static void
190 modest_mail_operation_finalize (GObject *obj)
191 {
192         ModestMailOperationPrivate *priv;
193
194         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(obj);
195
196         if (priv->error) {
197                 g_error_free (priv->error);
198                 priv->error = NULL;
199         }
200
201         G_OBJECT_CLASS(parent_class)->finalize (obj);
202 }
203
204 ModestMailOperation*
205 modest_mail_operation_new (void)
206 {
207         return MODEST_MAIL_OPERATION(g_object_new(MODEST_TYPE_MAIL_OPERATION, NULL));
208 }
209
210
211 void
212 modest_mail_operation_send_mail (ModestMailOperation *self,
213                                  TnyTransportAccount *transport_account,
214                                  TnyMsg* msg)
215 {
216         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
217         g_return_if_fail (TNY_IS_TRANSPORT_ACCOUNT (transport_account));
218
219         tny_transport_account_send (transport_account, msg, NULL); /* FIXME */
220 }
221
222 void
223 modest_mail_operation_send_new_mail (ModestMailOperation *self,
224                                      TnyTransportAccount *transport_account,
225                                      const gchar *from,
226                                      const gchar *to,
227                                      const gchar *cc,
228                                      const gchar *bcc,
229                                      const gchar *subject,
230                                      const gchar *body,
231                                      const GList *attachments_list)
232 {
233         TnyPlatformFactory *fact;
234         TnyMsg *new_msg;
235         TnyHeader *header;
236         gchar *content_type;
237         ModestMailOperationPrivate *priv = NULL;
238
239         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
240         g_return_if_fail (TNY_IS_TRANSPORT_ACCOUNT (transport_account));
241
242         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
243
244         /* Check parametters */
245         if (to == NULL) {
246                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
247                              MODEST_MAIL_OPERATION_ERROR_MISSING_PARAMETER,
248                              _("Error trying to send a mail. You need to set almost one a recipient"));
249                 return;
250         }
251
252         /* Create new msg */
253         fact    = modest_tny_platform_factory_get_instance ();
254         new_msg = tny_platform_factory_new_msg (fact);
255         header  = tny_platform_factory_new_header (fact);
256
257         /* WARNING: set the header before assign values to it */
258         tny_msg_set_header (new_msg, header);
259         tny_header_set_from (TNY_HEADER (header), from);
260         tny_header_set_replyto (TNY_HEADER (header), from);
261         tny_header_set_to (TNY_HEADER (header), to);
262         tny_header_set_cc (TNY_HEADER (header), cc);
263         tny_header_set_bcc (TNY_HEADER (header), bcc);
264         tny_header_set_subject (TNY_HEADER (header), subject);
265
266         content_type = get_content_type(body);
267
268         /* Add the body of the new mail */      
269         add_body_part (new_msg, body, (const gchar *) content_type,
270                        (attachments_list == NULL) ? FALSE : TRUE);
271
272         /* Add attachments */
273         add_attachments (new_msg, (GList*) attachments_list);
274
275         /* Send mail */
276         tny_transport_account_send (transport_account, new_msg, NULL); /* FIXME */
277
278         /* Clean */
279         g_object_unref (header);
280         g_object_unref (new_msg);
281         g_free(content_type);
282 }
283
284 static void
285 add_if_attachment (gpointer data, gpointer user_data)
286 {
287         TnyMimePart *part;
288         GList *attachments_list;
289
290         part = TNY_MIME_PART (data);
291         attachments_list = (GList *) user_data;
292
293         if (tny_mime_part_is_attachment (part))
294                 attachments_list = g_list_prepend (attachments_list, part);
295 }
296
297
298 static TnyMsg *
299 create_reply_forward_mail (TnyMsg *msg, const gchar *from, gboolean is_reply, guint type)
300 {
301         TnyPlatformFactory *fact;
302         TnyMsg *new_msg;
303         TnyHeader *new_header, *header;
304         gchar *new_subject;
305         TnyMimePart *body;
306         ModestFormatter *formatter;
307
308         /* Get body from original msg. Always look for the text/plain
309            part of the message to create the reply/forwarded mail */
310         header = tny_msg_get_header (msg);
311         body   = modest_tny_msg_actions_find_body_part (msg, FALSE);
312
313         /* TODO: select the formatter from account prefs */
314         formatter = modest_formatter_new ("text/plain");
315
316         /* Format message body */
317         if (is_reply) {
318                 switch (type) {
319                 case MODEST_MAIL_OPERATION_REPLY_TYPE_CITE:
320                 default:
321                         new_msg = modest_formatter_cite  (formatter, body, header);
322                         break;
323                 case MODEST_MAIL_OPERATION_REPLY_TYPE_QUOTE:
324                         new_msg = modest_formatter_quote (formatter, body, header);
325                         break;
326                 }
327         } else {
328                 switch (type) {
329                 case MODEST_MAIL_OPERATION_FORWARD_TYPE_INLINE:
330                 default:
331                         new_msg = modest_formatter_inline  (formatter, body, header);
332                         break;
333                 case MODEST_MAIL_OPERATION_FORWARD_TYPE_ATTACHMENT:
334                         new_msg = modest_formatter_attach (formatter, body, header);
335                         break;
336                 }
337         }
338         g_object_unref (G_OBJECT (formatter));
339
340         /* Fill the header */
341         fact = modest_tny_platform_factory_get_instance ();
342         new_header = TNY_HEADER (tny_platform_factory_new_header (fact));
343         tny_msg_set_header (new_msg, new_header);
344         tny_header_set_from (new_header, from);
345         tny_header_set_replyto (new_header, from);
346
347         /* Change the subject */
348         new_subject =
349                 (gchar *) modest_text_utils_derived_subject (tny_header_get_subject(header),
350                                                              (is_reply) ? _("Re:") : _("Fwd:"));
351         tny_header_set_subject (new_header, (const gchar *) new_subject);
352         g_free (new_subject);
353
354         /* Clean */
355         g_object_unref (G_OBJECT (new_header));
356         g_object_unref (G_OBJECT (header));
357
358         return new_msg;
359 }
360
361 TnyMsg* 
362 modest_mail_operation_create_forward_mail (TnyMsg *msg, 
363                                            const gchar *from,
364                                            ModestMailOperationForwardType forward_type)
365 {
366         TnyMsg *new_msg;
367         TnyList *parts = NULL;
368         GList *attachments_list = NULL;
369
370         new_msg = create_reply_forward_mail (msg, from, FALSE, forward_type);
371
372         /* Add attachments */
373         parts = TNY_LIST (tny_simple_list_new());
374         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
375         tny_list_foreach (parts, add_if_attachment, attachments_list);
376         add_attachments (new_msg, attachments_list);
377
378         /* Clean */
379         if (attachments_list) g_list_free (attachments_list);
380         g_object_unref (G_OBJECT (parts));
381
382         return new_msg;
383 }
384
385 TnyMsg* 
386 modest_mail_operation_create_reply_mail (TnyMsg *msg, 
387                                          const gchar *from,
388                                          ModestMailOperationReplyType reply_type,
389                                          ModestMailOperationReplyMode reply_mode)
390 {
391         TnyMsg *new_msg = NULL;
392         TnyHeader *new_header, *header;
393         const gchar* reply_to;
394         gchar *new_cc = NULL;
395         const gchar *cc = NULL, *bcc = NULL;
396         GString *tmp = NULL;
397
398         new_msg = create_reply_forward_mail (msg, from, TRUE, reply_type);
399
400         /* Fill the header */
401         header = tny_msg_get_header (msg);
402         new_header = tny_msg_get_header (new_msg);
403         reply_to = tny_header_get_replyto (header);
404
405         if (reply_to)
406                 tny_header_set_to (new_header, reply_to);
407         else
408                 tny_header_set_to (new_header, tny_header_get_from (header));
409
410         switch (reply_mode) {
411         case MODEST_MAIL_OPERATION_REPLY_MODE_SENDER:
412                 /* Do not fill neither cc nor bcc */
413                 break;
414         case MODEST_MAIL_OPERATION_REPLY_MODE_LIST:
415                 /* TODO */
416                 break;
417         case MODEST_MAIL_OPERATION_REPLY_MODE_ALL:
418                 /* Concatenate to, cc and bcc */
419                 cc = tny_header_get_cc (header);
420                 bcc = tny_header_get_bcc (header);
421
422                 tmp = g_string_new (tny_header_get_to (header));
423                 if (cc)  g_string_append_printf (tmp, ",%s",cc);
424                 if (bcc) g_string_append_printf (tmp, ",%s",bcc);
425
426                /* Remove my own address from the cc list. TODO:
427                   remove also the To: of the new message, needed due
428                   to the new reply_to feature */
429                 new_cc = (gchar *)
430                         modest_text_utils_remove_address ((const gchar *) tmp->str,
431                                                           from);
432                 /* FIXME: remove also the mails from the new To: */
433                 tny_header_set_cc (new_header, new_cc);
434
435                 /* Clean */
436                 g_string_free (tmp, TRUE);
437                 g_free (new_cc);
438                 break;
439         }
440
441         /* Clean */
442         g_object_unref (G_OBJECT (new_header));
443         g_object_unref (G_OBJECT (header));
444
445         return new_msg;
446 }
447
448 static void
449 status_update_cb (TnyFolder *folder, const gchar *what, gint status, gint oftotal, gpointer user_data) 
450 {
451         g_print ("%s status: %d, of total %d\n", what, status, oftotal);
452 }
453
454 static void
455 folder_refresh_cb (TnyFolder *folder, gboolean canceled, GError **err, gpointer user_data)
456 {
457         ModestMailOperation *self = NULL;
458         ModestMailOperationPrivate *priv = NULL;
459         RefreshFolderAsyncHelper *helper;
460
461         helper = (RefreshFolderAsyncHelper *) user_data;
462         self = MODEST_MAIL_OPERATION (helper->mail_op);
463         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
464
465         if ((canceled && *err) || *err) {
466                 priv->error = g_error_copy (*err);
467                 helper->failed++;
468         } else if (canceled) {
469                 helper->canceled++;
470                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
471                              MODEST_MAIL_OPERATION_ERROR_OPERATION_CANCELED,
472                              _("Error trying to refresh folder %s. Operation canceled"),
473                              tny_folder_get_name (folder));
474         } else {
475                 priv->done++;
476         }
477
478         if (priv->done == priv->total)
479                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
480         else if ((priv->done + helper->canceled + helper->failed) == priv->total) {
481                 if (helper->failed == priv->total)
482                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
483                 else if (helper->failed == priv->total)
484                         priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
485                 else
486                         priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
487         }
488         tny_iterator_next (helper->iter);
489         if (tny_iterator_is_done (helper->iter)) {
490                 TnyList *list;
491                 list = tny_iterator_get_list (helper->iter);
492                 g_object_unref (G_OBJECT (helper->iter));
493                 g_object_unref (G_OBJECT (list));
494                 g_slice_free (RefreshFolderAsyncHelper, helper);
495         } else {
496                 tny_folder_refresh_async (TNY_FOLDER (tny_iterator_get_current (helper->iter)),
497                                           folder_refresh_cb,
498                                           status_update_cb, 
499                                           helper);
500         }
501         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 0, NULL);
502 }
503
504
505 static void
506 update_folders_cb (TnyFolderStore *folder_store, TnyList *list, GError **err, gpointer user_data)
507 {
508         ModestMailOperation *self;
509         ModestMailOperationPrivate *priv;
510         RefreshFolderAsyncHelper *helper;
511
512         self  = MODEST_MAIL_OPERATION (user_data);
513         priv  = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
514
515         if (*err) {
516                 priv->error = g_error_copy (*err);
517                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
518                 return;
519         }
520
521         priv->total = tny_list_get_length (list);
522         priv->done = 0;
523         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
524
525         helper = g_slice_new0 (RefreshFolderAsyncHelper);
526         helper->mail_op = self;
527         helper->iter = tny_list_create_iterator (list);
528         helper->failed = 0;
529         helper->canceled = 0;
530
531         /* Async refresh folders */
532         tny_folder_refresh_async (TNY_FOLDER (tny_iterator_get_current (helper->iter)),
533                                   folder_refresh_cb,
534                                   status_update_cb, 
535                                   helper);
536 }
537
538 gboolean
539 modest_mail_operation_update_account (ModestMailOperation *self,
540                                       TnyStoreAccount *store_account)
541 {
542         ModestMailOperationPrivate *priv;
543         TnyList *folders;
544         TnyFolderStoreQuery *query;
545
546         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), FALSE);
547         g_return_val_if_fail (TNY_IS_STORE_ACCOUNT(store_account), FALSE);
548
549         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
550
551         /* Get subscribed folders & refresh them */
552         folders = TNY_LIST (tny_simple_list_new ());
553         query = tny_folder_store_query_new ();
554         tny_folder_store_query_add_item (query, NULL, TNY_FOLDER_STORE_QUERY_OPTION_SUBSCRIBED);
555         tny_folder_store_get_folders_async (TNY_FOLDER_STORE (store_account),
556                                             folders, update_folders_cb, query, self);
557         g_object_unref (query);
558
559         return TRUE;
560 }
561
562 ModestMailOperationStatus
563 modest_mail_operation_get_status (ModestMailOperation *self)
564 {
565         ModestMailOperationPrivate *priv;
566
567         g_return_val_if_fail (self, MODEST_MAIL_OPERATION_STATUS_INVALID);
568         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self),
569                               MODEST_MAIL_OPERATION_STATUS_INVALID);
570
571         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
572         return priv->status;
573 }
574
575 const GError *
576 modest_mail_operation_get_error (ModestMailOperation *self)
577 {
578         ModestMailOperationPrivate *priv;
579
580         g_return_val_if_fail (self, NULL);
581         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), NULL);
582
583         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
584         return priv->error;
585 }
586
587 gboolean 
588 modest_mail_operation_cancel (ModestMailOperation *self)
589 {
590         /* TODO */
591         return TRUE;
592 }
593
594 guint 
595 modest_mail_operation_get_task_done (ModestMailOperation *self)
596 {
597         ModestMailOperationPrivate *priv;
598
599         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), 0);
600
601         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
602         return priv->done;
603 }
604
605 guint 
606 modest_mail_operation_get_task_total (ModestMailOperation *self)
607 {
608         ModestMailOperationPrivate *priv;
609
610         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), 0);
611
612         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
613         return priv->total;
614 }
615
616 gboolean
617 modest_mail_operation_is_finished (ModestMailOperation *self)
618 {
619         ModestMailOperationPrivate *priv;
620         gboolean retval = FALSE;
621
622         if (!MODEST_IS_MAIL_OPERATION (self)) {
623                 g_warning ("%s: invalid parametter", G_GNUC_FUNCTION);
624                 return retval;
625         }
626
627         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
628
629         if (priv->status == MODEST_MAIL_OPERATION_STATUS_SUCCESS   ||
630             priv->status == MODEST_MAIL_OPERATION_STATUS_FAILED    ||
631             priv->status == MODEST_MAIL_OPERATION_STATUS_CANCELED  ||
632             priv->status == MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS) {
633                 retval = TRUE;
634         } else {
635                 retval = FALSE;
636         }
637
638         return retval;
639 }
640
641 /* ******************************************************************* */
642 /* ************************** STORE  ACTIONS ************************* */
643 /* ******************************************************************* */
644
645
646 TnyFolder *
647 modest_mail_operation_create_folder (ModestMailOperation *self,
648                                      TnyFolderStore *parent,
649                                      const gchar *name)
650 {
651         g_return_val_if_fail (TNY_IS_FOLDER_STORE (parent), NULL);
652         g_return_val_if_fail (name, NULL);
653
654         TnyFolder *new_folder = NULL;
655         TnyStoreAccount *store_account;
656
657         /* Create the folder */
658         new_folder = tny_folder_store_create_folder (parent, name, NULL); /* FIXME */
659         if (!new_folder) 
660                 return NULL;
661
662         /* Subscribe to folder */
663         if (!tny_folder_is_subscribed (new_folder)) {
664                 store_account = TNY_STORE_ACCOUNT (tny_folder_get_account (TNY_FOLDER (parent)));
665                 tny_store_account_subscribe (store_account, new_folder);
666                 g_object_unref (G_OBJECT (store_account));
667         }
668
669         return new_folder;
670 }
671
672 void
673 modest_mail_operation_remove_folder (ModestMailOperation *self,
674                                      TnyFolder *folder,
675                                      gboolean remove_to_trash)
676 {
677         TnyFolderStore *folder_store;
678
679         g_return_if_fail (TNY_IS_FOLDER (folder));
680
681         /* Get folder store */
682         folder_store = TNY_FOLDER_STORE (tny_folder_get_account (folder));
683
684         /* Delete folder or move to trash */
685         if (remove_to_trash) {
686                 TnyFolder *trash_folder;
687                 trash_folder = modest_tny_account_get_special_folder (TNY_ACCOUNT(folder_store),
688                                                                       TNY_FOLDER_TYPE_TRASH);
689                 
690                 /* TODO: error_handling */
691                 modest_mail_operation_move_folder (self, 
692                                                    folder, 
693                                                    TNY_FOLDER_STORE (trash_folder));
694         } else {
695                 tny_folder_store_remove_folder (folder_store, folder, NULL); /* FIXME */
696                 g_object_unref (G_OBJECT (folder));
697         }
698
699         /* Free instances */
700         g_object_unref (G_OBJECT (folder_store));
701 }
702
703 void
704 modest_mail_operation_rename_folder (ModestMailOperation *self,
705                                      TnyFolder *folder,
706                                      const gchar *name)
707 {
708         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
709         g_return_if_fail (TNY_IS_FOLDER_STORE (folder));
710         g_return_if_fail (name);
711
712         /* FIXME: better error handling */
713         if (strrchr (name, '/') != NULL)
714                 return;
715
716         /* Rename. Camel handles folder subscription/unsubscription */
717         tny_folder_set_name (folder, name, NULL); /* FIXME */
718  }
719
720 void
721 modest_mail_operation_move_folder (ModestMailOperation *self,
722                                    TnyFolder *folder,
723                                    TnyFolderStore *parent)
724 {
725         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
726         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
727         g_return_if_fail (TNY_IS_FOLDER (folder));
728         
729         modest_mail_operation_xfer_folder (self, folder, parent, TRUE);
730 }
731
732 void
733 modest_mail_operation_copy_folder (ModestMailOperation *self,
734                                    TnyFolder *folder,
735                                    TnyFolderStore *parent)
736 {
737         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
738         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
739         g_return_if_fail (TNY_IS_FOLDER (folder));
740
741         modest_mail_operation_xfer_folder (self, folder, parent, FALSE);
742 }
743
744 static void
745 modest_mail_operation_xfer_folder (ModestMailOperation *self,
746                                    TnyFolder *folder,
747                                    TnyFolderStore *parent,
748                                    gboolean delete_original)
749 {
750         const gchar *folder_name;
751         TnyFolder *dest_folder, *child;
752         TnyIterator *iter;
753         TnyList *folders, *headers;
754
755         g_return_if_fail (TNY_IS_FOLDER (folder));
756         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
757
758         /* Create the destination folder */
759         folder_name = tny_folder_get_name (folder);
760         dest_folder = modest_mail_operation_create_folder (self, 
761                                                            parent, folder_name);
762
763         /* Transfer messages */
764         headers = TNY_LIST (tny_simple_list_new ());
765         tny_folder_get_headers (folder, headers, FALSE, NULL); /* FIXME */
766         tny_folder_transfer_msgs (folder, headers, dest_folder, delete_original, NULL); /* FIXME */
767
768         /* Recurse children */
769         folders = TNY_LIST (tny_simple_list_new ());
770         tny_folder_store_get_folders (TNY_FOLDER_STORE (folder), folders, NULL, NULL ); /* FIXME */
771         iter = tny_list_create_iterator (folders);
772
773         while (!tny_iterator_is_done (iter)) {
774
775                 child = TNY_FOLDER (tny_iterator_get_current (iter));
776                 modest_mail_operation_xfer_folder (self, child,
777                                                    TNY_FOLDER_STORE (dest_folder),
778                                                    delete_original);
779                 tny_iterator_next (iter);
780         }
781
782         /* Delete source folder (if needed) */
783         if (delete_original)
784                 modest_mail_operation_remove_folder (self, folder, FALSE);
785
786         /* Clean up */
787         g_object_unref (G_OBJECT (dest_folder));
788         g_object_unref (G_OBJECT (headers));
789         g_object_unref (G_OBJECT (folders));
790         g_object_unref (G_OBJECT (iter));
791 }
792
793
794 /* ******************************************************************* */
795 /* **************************  MSG  ACTIONS  ************************* */
796 /* ******************************************************************* */
797
798 gboolean 
799 modest_mail_operation_copy_msg (ModestMailOperation *self,
800                                 TnyHeader *header, 
801                                 TnyFolder *folder)
802 {
803         g_return_val_if_fail (TNY_IS_HEADER (header), FALSE);
804         g_return_val_if_fail (TNY_IS_FOLDER (folder), FALSE);
805
806         return modest_mail_operation_xfer_msg (self, header, folder, FALSE);
807 }
808
809 gboolean 
810 modest_mail_operation_move_msg (ModestMailOperation *self,
811                                 TnyHeader *header, 
812                                 TnyFolder *folder)
813 {
814         g_return_val_if_fail (TNY_IS_HEADER (header), FALSE);
815         g_return_val_if_fail (TNY_IS_FOLDER (folder), FALSE);
816
817         return modest_mail_operation_xfer_msg (self, header, folder, TRUE);
818 }
819
820 void 
821 modest_mail_operation_remove_msg (ModestMailOperation *self,
822                                   TnyHeader *header,
823                                   gboolean remove_to_trash)
824 {
825         TnyFolder *folder;
826
827         g_return_if_fail (TNY_IS_HEADER (header));
828
829         folder = tny_header_get_folder (header);
830
831         /* Delete or move to trash */
832         if (remove_to_trash) {
833                 TnyFolder *trash_folder;
834                 TnyStoreAccount *store_account;
835
836                 store_account = TNY_STORE_ACCOUNT (tny_folder_get_account (folder));
837                 trash_folder = modest_tny_account_get_special_folder (TNY_ACCOUNT(store_account),
838                                                                       TNY_FOLDER_TYPE_TRASH);
839                 if (trash_folder) {
840                         modest_mail_operation_move_msg (self, header, trash_folder);
841 /*                      g_object_unref (trash_folder); */
842                 } else {
843                         ModestMailOperationPrivate *priv;
844
845                         /* Set status failed and set an error */
846                         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
847                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
848                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
849                                      MODEST_MAIL_OPERATION_ERROR_ITEM_NOT_FOUND,
850                                      _("Error trying to delete a message. Trash folder not found"));
851                 }
852
853                 g_object_unref (G_OBJECT (store_account));
854         } else {
855                 tny_folder_remove_msg (folder, header, NULL); /* FIXME */
856                 tny_folder_sync(folder, TRUE, NULL); /* FIXME */
857         }
858
859         /* Free */
860         g_object_unref (folder);
861 }
862
863 static void
864 transfer_msgs_cb (TnyFolder *folder, GError **err, gpointer user_data)
865 {
866         ModestMailOperationPrivate *priv;
867
868         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(user_data);
869         priv->done = 1;
870         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
871
872         g_signal_emit (G_OBJECT (user_data), signals[PROGRESS_CHANGED_SIGNAL], 0, NULL);
873 }
874
875 static gboolean
876 modest_mail_operation_xfer_msg (ModestMailOperation *self,
877                                 TnyHeader *header, 
878                                 TnyFolder *folder, 
879                                 gboolean delete_original)
880 {
881         ModestMailOperationPrivate *priv;
882         TnyFolder *src_folder;
883         TnyList *headers;
884
885         src_folder = tny_header_get_folder (header);
886         headers = tny_simple_list_new ();
887
888         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
889         priv->total = 1;
890         priv->done = 0;
891         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
892
893         tny_list_prepend (headers, G_OBJECT (header));
894         tny_folder_transfer_msgs_async (src_folder, headers, folder, 
895                                         delete_original, transfer_msgs_cb, self);
896
897         /* Free */
898         g_object_unref (headers);
899         g_object_unref (folder);
900
901         return TRUE;
902 }
903
904
905 /* ******************************************************************* */
906 /* ************************* UTILIY FUNCTIONS ************************ */
907 /* ******************************************************************* */
908 static gboolean
909 is_ascii(const gchar *s)
910 {
911         while (s[0]) {
912                 if (s[0] & 128 || s[0] < 32)
913                         return FALSE;
914                 s++;
915         }
916         return TRUE;
917 }
918
919 static char *
920 get_content_type(const gchar *s)
921 {
922         GString *type;
923         
924         type = g_string_new("text/plain");
925         if (!is_ascii(s)) {
926                 if (g_utf8_validate(s, -1, NULL)) {
927                         g_string_append(type, "; charset=\"utf-8\"");
928                 } else {
929                         /* it should be impossible to reach this, but better safe than sorry */
930                         g_warning("invalid utf8 in message");
931                         g_string_append(type, "; charset=\"latin1\"");
932                 }
933         }
934         return g_string_free(type, FALSE);
935 }
936
937 static void
938 add_attachments (TnyMsg *msg, GList *attachments_list)
939 {
940         GList *pos;
941         TnyMimePart *attachment_part, *old_attachment;
942         const gchar *attachment_content_type;
943         const gchar *attachment_filename;
944         TnyStream *attachment_stream;
945         TnyPlatformFactory *fact;
946
947         fact = modest_tny_platform_factory_get_instance ();
948         for (pos = (GList *)attachments_list; pos; pos = pos->next) {
949
950                 old_attachment = pos->data;
951                 attachment_filename = tny_mime_part_get_filename (old_attachment);
952                 attachment_stream = tny_mime_part_get_stream (old_attachment);
953                 attachment_part = tny_platform_factory_new_mime_part (fact);
954                 
955                 attachment_content_type = tny_mime_part_get_content_type (old_attachment);
956                                  
957                 tny_mime_part_construct_from_stream (attachment_part,
958                                                      attachment_stream,
959                                                      attachment_content_type);
960                 tny_stream_reset (attachment_stream);
961                 
962                 tny_mime_part_set_filename (attachment_part, attachment_filename);
963                 
964                 tny_mime_part_add_part (TNY_MIME_PART (msg), attachment_part);
965 /*              g_object_unref (attachment_part); */
966         }
967 }
968
969
970 static TnyMimePart *
971 add_body_part (TnyMsg *msg, 
972                const gchar *body,
973                const gchar *content_type,
974                gboolean has_attachments)
975 {
976         TnyMimePart *text_body_part = NULL;
977         TnyStream *text_body_stream;
978         TnyPlatformFactory *fact;
979
980         fact = modest_tny_platform_factory_get_instance ();
981
982         /* Create the stream */
983         text_body_stream = TNY_STREAM (tny_camel_stream_new
984                                        (camel_stream_mem_new_with_buffer
985                                         (body, strlen(body))));
986
987         /* Create body part if needed */
988         if (has_attachments)
989                 text_body_part = tny_platform_factory_new_mime_part (fact);
990         else
991                 text_body_part = TNY_MIME_PART(msg);
992
993         /* Construct MIME part */
994         tny_stream_reset (text_body_stream);
995         tny_mime_part_construct_from_stream (text_body_part,
996                                              text_body_stream,
997                                              content_type);
998         tny_stream_reset (text_body_stream);
999
1000         /* Add part if needed */
1001         if (has_attachments) {
1002                 tny_mime_part_add_part (TNY_MIME_PART (msg), text_body_part);
1003                 g_object_unref (G_OBJECT(text_body_part));
1004         }
1005
1006         /* Clean */
1007         g_object_unref (text_body_stream);
1008
1009         return text_body_part;
1010 }