59d35091c3d24c961a7eb2f6df4b49594e016fb6
[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.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_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         g_object_unref (G_OBJECT(body));
340         
341         /* Fill the header */
342         fact = modest_tny_platform_factory_get_instance ();
343         new_header = TNY_HEADER (tny_platform_factory_new_header (fact));
344         tny_msg_set_header (new_msg, new_header);
345         tny_header_set_from (new_header, from);
346         tny_header_set_replyto (new_header, from);
347
348         /* Change the subject */
349         new_subject =
350                 (gchar *) modest_text_utils_derived_subject (tny_header_get_subject(header),
351                                                              (is_reply) ? _("Re:") : _("Fwd:"));
352         tny_header_set_subject (new_header, (const gchar *) new_subject);
353         g_free (new_subject);
354
355         /* Clean */
356         g_object_unref (G_OBJECT (new_header));
357         g_object_unref (G_OBJECT (header));
358
359         return new_msg;
360 }
361
362 TnyMsg* 
363 modest_mail_operation_create_forward_mail (TnyMsg *msg, 
364                                            const gchar *from,
365                                            ModestMailOperationForwardType forward_type)
366 {
367         TnyMsg *new_msg;
368         TnyList *parts = NULL;
369         GList *attachments_list = NULL;
370
371         new_msg = create_reply_forward_mail (msg, from, FALSE, forward_type);
372
373         /* Add attachments */
374         parts = TNY_LIST (tny_simple_list_new());
375         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
376         tny_list_foreach (parts, add_if_attachment, attachments_list);
377         add_attachments (new_msg, attachments_list);
378
379         /* Clean */
380         if (attachments_list) g_list_free (attachments_list);
381         g_object_unref (G_OBJECT (parts));
382
383         return new_msg;
384 }
385
386 TnyMsg* 
387 modest_mail_operation_create_reply_mail (TnyMsg *msg, 
388                                          const gchar *from,
389                                          ModestMailOperationReplyType reply_type,
390                                          ModestMailOperationReplyMode reply_mode)
391 {
392         TnyMsg *new_msg = NULL;
393         TnyHeader *new_header, *header;
394         const gchar* reply_to;
395         gchar *new_cc = NULL;
396         const gchar *cc = NULL, *bcc = NULL;
397         GString *tmp = NULL;
398
399         new_msg = create_reply_forward_mail (msg, from, TRUE, reply_type);
400
401         /* Fill the header */
402         header = tny_msg_get_header (msg);
403         new_header = tny_msg_get_header (new_msg);
404         reply_to = tny_header_get_replyto (header);
405
406         if (reply_to)
407                 tny_header_set_to (new_header, reply_to);
408         else
409                 tny_header_set_to (new_header, tny_header_get_from (header));
410
411         switch (reply_mode) {
412         case MODEST_MAIL_OPERATION_REPLY_MODE_SENDER:
413                 /* Do not fill neither cc nor bcc */
414                 break;
415         case MODEST_MAIL_OPERATION_REPLY_MODE_LIST:
416                 /* TODO */
417                 break;
418         case MODEST_MAIL_OPERATION_REPLY_MODE_ALL:
419                 /* Concatenate to, cc and bcc */
420                 cc = tny_header_get_cc (header);
421                 bcc = tny_header_get_bcc (header);
422
423                 tmp = g_string_new (tny_header_get_to (header));
424                 if (cc)  g_string_append_printf (tmp, ",%s",cc);
425                 if (bcc) g_string_append_printf (tmp, ",%s",bcc);
426
427                /* Remove my own address from the cc list. TODO:
428                   remove also the To: of the new message, needed due
429                   to the new reply_to feature */
430                 new_cc = (gchar *)
431                         modest_text_utils_remove_address ((const gchar *) tmp->str,
432                                                           from);
433                 /* FIXME: remove also the mails from the new To: */
434                 tny_header_set_cc (new_header, new_cc);
435
436                 /* Clean */
437                 g_string_free (tmp, TRUE);
438                 g_free (new_cc);
439                 break;
440         }
441
442         /* Clean */
443         g_object_unref (G_OBJECT (new_header));
444         g_object_unref (G_OBJECT (header));
445
446         return new_msg;
447 }
448
449 static void
450 status_update_cb (TnyFolder *folder, const gchar *what, gint status, gint oftotal, gpointer user_data) 
451 {
452         g_print ("%s status: %d, of total %d\n", what, status, oftotal);
453 }
454
455 static void
456 folder_refresh_cb (TnyFolder *folder, gboolean canceled, GError **err, gpointer user_data)
457 {
458         ModestMailOperation *self = NULL;
459         ModestMailOperationPrivate *priv = NULL;
460         RefreshFolderAsyncHelper *helper;
461
462         helper = (RefreshFolderAsyncHelper *) user_data;
463         self = MODEST_MAIL_OPERATION (helper->mail_op);
464         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
465
466         if ((canceled && *err) || *err) {
467                 priv->error = g_error_copy (*err);
468                 helper->failed++;
469         } else if (canceled) {
470                 helper->canceled++;
471                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
472                              MODEST_MAIL_OPERATION_ERROR_OPERATION_CANCELED,
473                              _("Error trying to refresh folder %s. Operation canceled"),
474                              tny_folder_get_name (folder));
475         } else {
476                 priv->done++;
477         }
478
479         if (priv->done == priv->total)
480                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
481         else if ((priv->done + helper->canceled + helper->failed) == priv->total) {
482                 if (helper->failed == priv->total)
483                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
484                 else if (helper->failed == priv->total)
485                         priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
486                 else
487                         priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
488         }
489         tny_iterator_next (helper->iter);
490         if (tny_iterator_is_done (helper->iter)) {
491                 TnyList *list;
492                 list = tny_iterator_get_list (helper->iter);
493                 g_object_unref (G_OBJECT (helper->iter));
494                 g_object_unref (G_OBJECT (list));
495                 g_slice_free (RefreshFolderAsyncHelper, helper);
496         } else {
497                 TnyFolder *folder = TNY_FOLDER (tny_iterator_get_current (helper->iter));
498                 tny_folder_refresh_async (folder, folder_refresh_cb,
499                                           status_update_cb, 
500                                           helper);
501                 g_object_unref (G_OBJECT(folder));
502         }
503         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 0, NULL);
504 }
505
506
507 static void
508 update_folders_cb (TnyFolderStore *folder_store, TnyList *list, GError **err, gpointer user_data)
509 {
510         ModestMailOperation *self;
511         ModestMailOperationPrivate *priv;
512         RefreshFolderAsyncHelper *helper;
513         TnyFolder *folder;
514         
515         self  = MODEST_MAIL_OPERATION (user_data);
516         priv  = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
517
518         if (*err) {
519                 priv->error = g_error_copy (*err);
520                 priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
521                 return;
522         }
523
524         priv->total = tny_list_get_length (list);
525         priv->done = 0;
526         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
527
528         helper = g_slice_new0 (RefreshFolderAsyncHelper);
529         helper->mail_op = self;
530         helper->iter = tny_list_create_iterator (list);
531         helper->failed = 0;
532         helper->canceled = 0;
533
534         /* Async refresh folders */
535         folder = TNY_FOLDER (tny_iterator_get_current (helper->iter));
536         tny_folder_refresh_async (folder, folder_refresh_cb,
537                                   status_update_cb, helper);
538         g_object_unref (G_OBJECT(folder));
539 }
540
541 gboolean
542 modest_mail_operation_update_account (ModestMailOperation *self,
543                                       TnyStoreAccount *store_account)
544 {
545         ModestMailOperationPrivate *priv;
546         TnyList *folders;
547         TnyFolderStoreQuery *query;
548
549         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), FALSE);
550         g_return_val_if_fail (TNY_IS_STORE_ACCOUNT(store_account), FALSE);
551
552         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
553
554         /* Get subscribed folders & refresh them */
555         folders = TNY_LIST (tny_simple_list_new ());
556         query = tny_folder_store_query_new ();
557         tny_folder_store_query_add_item (query, NULL, TNY_FOLDER_STORE_QUERY_OPTION_SUBSCRIBED);
558         tny_folder_store_get_folders_async (TNY_FOLDER_STORE (store_account),
559                                             folders, update_folders_cb, query, self);
560         g_object_unref (query);
561
562         return TRUE;
563 }
564
565 ModestMailOperationStatus
566 modest_mail_operation_get_status (ModestMailOperation *self)
567 {
568         ModestMailOperationPrivate *priv;
569
570         g_return_val_if_fail (self, MODEST_MAIL_OPERATION_STATUS_INVALID);
571         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self),
572                               MODEST_MAIL_OPERATION_STATUS_INVALID);
573
574         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
575         return priv->status;
576 }
577
578 const GError *
579 modest_mail_operation_get_error (ModestMailOperation *self)
580 {
581         ModestMailOperationPrivate *priv;
582
583         g_return_val_if_fail (self, NULL);
584         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), NULL);
585
586         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
587         return priv->error;
588 }
589
590 gboolean 
591 modest_mail_operation_cancel (ModestMailOperation *self)
592 {
593         /* TODO */
594         return TRUE;
595 }
596
597 guint 
598 modest_mail_operation_get_task_done (ModestMailOperation *self)
599 {
600         ModestMailOperationPrivate *priv;
601
602         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), 0);
603
604         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
605         return priv->done;
606 }
607
608 guint 
609 modest_mail_operation_get_task_total (ModestMailOperation *self)
610 {
611         ModestMailOperationPrivate *priv;
612
613         g_return_val_if_fail (MODEST_IS_MAIL_OPERATION (self), 0);
614
615         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
616         return priv->total;
617 }
618
619 gboolean
620 modest_mail_operation_is_finished (ModestMailOperation *self)
621 {
622         ModestMailOperationPrivate *priv;
623         gboolean retval = FALSE;
624
625         if (!MODEST_IS_MAIL_OPERATION (self)) {
626                 g_warning ("%s: invalid parametter", G_GNUC_FUNCTION);
627                 return retval;
628         }
629
630         priv = MODEST_MAIL_OPERATION_GET_PRIVATE (self);
631
632         if (priv->status == MODEST_MAIL_OPERATION_STATUS_SUCCESS   ||
633             priv->status == MODEST_MAIL_OPERATION_STATUS_FAILED    ||
634             priv->status == MODEST_MAIL_OPERATION_STATUS_CANCELED  ||
635             priv->status == MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS) {
636                 retval = TRUE;
637         } else {
638                 retval = FALSE;
639         }
640
641         return retval;
642 }
643
644 /* ******************************************************************* */
645 /* ************************** STORE  ACTIONS ************************* */
646 /* ******************************************************************* */
647
648
649 TnyFolder *
650 modest_mail_operation_create_folder (ModestMailOperation *self,
651                                      TnyFolderStore *parent,
652                                      const gchar *name)
653 {
654         g_return_val_if_fail (TNY_IS_FOLDER_STORE (parent), NULL);
655         g_return_val_if_fail (name, NULL);
656
657         TnyFolder *new_folder = NULL;
658         TnyStoreAccount *store_account;
659
660         /* Create the folder */
661         new_folder = tny_folder_store_create_folder (parent, name, NULL); /* FIXME */
662         if (!new_folder) 
663                 return NULL;
664
665         /* Subscribe to folder */
666         if (!tny_folder_is_subscribed (new_folder)) {
667                 store_account = TNY_STORE_ACCOUNT (tny_folder_get_account (TNY_FOLDER (parent)));
668                 tny_store_account_subscribe (store_account, new_folder);
669                 g_object_unref (G_OBJECT (store_account));
670         }
671
672         return new_folder;
673 }
674
675 void
676 modest_mail_operation_remove_folder (ModestMailOperation *self,
677                                      TnyFolder *folder,
678                                      gboolean remove_to_trash)
679 {
680         TnyFolderStore *folder_store;
681
682         g_return_if_fail (TNY_IS_FOLDER (folder));
683
684         /* Get folder store */
685         folder_store = TNY_FOLDER_STORE (tny_folder_get_account (folder));
686
687         /* Delete folder or move to trash */
688         if (remove_to_trash) {
689                 TnyFolder *trash_folder;
690                 trash_folder = modest_tny_account_get_special_folder (TNY_ACCOUNT(folder_store),
691                                                                       TNY_FOLDER_TYPE_TRASH);
692                 /* TODO: error_handling */
693                 modest_mail_operation_move_folder (self, folder, 
694                                                    TNY_FOLDER_STORE (trash_folder));
695         } else {
696                 tny_folder_store_remove_folder (folder_store, folder, NULL); /* FIXME */
697                 g_object_unref (G_OBJECT (folder));
698         }
699
700         /* Free instances */
701         g_object_unref (G_OBJECT (folder_store));
702 }
703
704 void
705 modest_mail_operation_rename_folder (ModestMailOperation *self,
706                                      TnyFolder *folder,
707                                      const gchar *name)
708 {
709         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
710         g_return_if_fail (TNY_IS_FOLDER_STORE (folder));
711         g_return_if_fail (name);
712
713         /* FIXME: better error handling */
714         if (strrchr (name, '/') != NULL)
715                 return;
716
717         /* Rename. Camel handles folder subscription/unsubscription */
718         tny_folder_set_name (folder, name, NULL); /* FIXME */
719  }
720
721 void
722 modest_mail_operation_move_folder (ModestMailOperation *self,
723                                    TnyFolder *folder,
724                                    TnyFolderStore *parent)
725 {
726         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
727         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
728         g_return_if_fail (TNY_IS_FOLDER (folder));
729         
730         modest_mail_operation_xfer_folder (self, folder, parent, TRUE);
731 }
732
733 void
734 modest_mail_operation_copy_folder (ModestMailOperation *self,
735                                    TnyFolder *folder,
736                                    TnyFolderStore *parent)
737 {
738         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
739         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
740         g_return_if_fail (TNY_IS_FOLDER (folder));
741
742         modest_mail_operation_xfer_folder (self, folder, parent, FALSE);
743 }
744
745 static void
746 modest_mail_operation_xfer_folder (ModestMailOperation *self,
747                                    TnyFolder *folder,
748                                    TnyFolderStore *parent,
749                                    gboolean delete_original)
750 {
751         const gchar *folder_name;
752         TnyFolder *dest_folder, *child;
753         TnyIterator *iter;
754         TnyList *folders, *headers;
755
756         g_return_if_fail (TNY_IS_FOLDER (folder));
757         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
758
759         /* Create the destination folder */
760         folder_name = tny_folder_get_name (folder);
761         dest_folder = modest_mail_operation_create_folder (self, 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                 child = TNY_FOLDER (tny_iterator_get_current (iter));
775                 modest_mail_operation_xfer_folder (self, child, TNY_FOLDER_STORE (dest_folder),
776                                                    delete_original);
777                 tny_iterator_next (iter);
778                 g_object_unref (G_OBJECT(child));
779         }
780
781         /* Delete source folder (if needed) */
782         if (delete_original)
783                 modest_mail_operation_remove_folder (self, folder, FALSE);
784
785         /* Clean up */
786         g_object_unref (G_OBJECT (dest_folder));
787         g_object_unref (G_OBJECT (headers));
788         g_object_unref (G_OBJECT (folders));
789         g_object_unref (G_OBJECT (iter));
790 }
791
792
793 /* ******************************************************************* */
794 /* **************************  MSG  ACTIONS  ************************* */
795 /* ******************************************************************* */
796
797 gboolean 
798 modest_mail_operation_copy_msg (ModestMailOperation *self,
799                                 TnyHeader *header, 
800                                 TnyFolder *folder)
801 {
802         g_return_val_if_fail (TNY_IS_HEADER (header), FALSE);
803         g_return_val_if_fail (TNY_IS_FOLDER (folder), FALSE);
804
805         return modest_mail_operation_xfer_msg (self, header, folder, FALSE);
806 }
807
808 gboolean 
809 modest_mail_operation_move_msg (ModestMailOperation *self,
810                                 TnyHeader *header, 
811                                 TnyFolder *folder)
812 {
813         g_return_val_if_fail (TNY_IS_HEADER (header), FALSE);
814         g_return_val_if_fail (TNY_IS_FOLDER (folder), FALSE);
815
816         return modest_mail_operation_xfer_msg (self, header, folder, TRUE);
817 }
818
819 void 
820 modest_mail_operation_remove_msg (ModestMailOperation *self,
821                                   TnyHeader *header,
822                                   gboolean remove_to_trash)
823 {
824         TnyFolder *folder;
825
826         g_return_if_fail (TNY_IS_HEADER (header));
827
828         folder = tny_header_get_folder (header);
829
830         /* Delete or move to trash */
831         if (remove_to_trash) {
832                 TnyFolder *trash_folder;
833                 TnyStoreAccount *store_account;
834
835                 store_account = TNY_STORE_ACCOUNT (tny_folder_get_account (folder));
836                 trash_folder = modest_tny_account_get_special_folder (TNY_ACCOUNT(store_account),
837                                                                       TNY_FOLDER_TYPE_TRASH);
838                 if (trash_folder) {
839                         modest_mail_operation_move_msg (self, header, trash_folder);
840 /*                      g_object_unref (trash_folder); */
841                 } else {
842                         ModestMailOperationPrivate *priv;
843
844                         /* Set status failed and set an error */
845                         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
846                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
847                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
848                                      MODEST_MAIL_OPERATION_ERROR_ITEM_NOT_FOUND,
849                                      _("Error trying to delete a message. Trash folder not found"));
850                 }
851
852                 g_object_unref (G_OBJECT (store_account));
853         } else {
854                 tny_folder_remove_msg (folder, header, NULL); /* FIXME */
855                 tny_folder_sync(folder, TRUE, NULL); /* FIXME */
856         }
857
858         /* Free */
859         g_object_unref (folder);
860 }
861
862 static void
863 transfer_msgs_cb (TnyFolder *folder, GError **err, gpointer user_data)
864 {
865         ModestMailOperationPrivate *priv;
866
867         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(user_data);
868         priv->done = 1;
869         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
870
871         g_signal_emit (G_OBJECT (user_data), signals[PROGRESS_CHANGED_SIGNAL], 0, NULL);
872 }
873
874 static gboolean
875 modest_mail_operation_xfer_msg (ModestMailOperation *self,
876                                 TnyHeader *header, 
877                                 TnyFolder *folder, 
878                                 gboolean delete_original)
879 {
880         ModestMailOperationPrivate *priv;
881         TnyFolder *src_folder;
882         TnyList *headers;
883
884         src_folder = tny_header_get_folder (header);
885         headers = tny_simple_list_new ();
886
887         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
888         priv->total = 1;
889         priv->done = 0;
890         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
891
892         tny_list_prepend (headers, G_OBJECT (header));
893         tny_folder_transfer_msgs_async (src_folder, headers, folder, 
894                                         delete_original, transfer_msgs_cb, self);
895
896         /* Free */
897         g_object_unref (headers);
898         g_object_unref (folder);
899
900         return TRUE;
901 }
902
903
904 /* ******************************************************************* */
905 /* ************************* UTILIY FUNCTIONS ************************ */
906 /* ******************************************************************* */
907 static gboolean
908 is_ascii(const gchar *s)
909 {
910         while (s[0]) {
911                 if (s[0] & 128 || s[0] < 32)
912                         return FALSE;
913                 s++;
914         }
915         return TRUE;
916 }
917
918 static char *
919 get_content_type(const gchar *s)
920 {
921         GString *type;
922         
923         type = g_string_new("text/plain");
924         if (!is_ascii(s)) {
925                 if (g_utf8_validate(s, -1, NULL)) {
926                         g_string_append(type, "; charset=\"utf-8\"");
927                 } else {
928                         /* it should be impossible to reach this, but better safe than sorry */
929                         g_warning("invalid utf8 in message");
930                         g_string_append(type, "; charset=\"latin1\"");
931                 }
932         }
933         return g_string_free(type, FALSE);
934 }
935
936 static void
937 add_attachments (TnyMsg *msg, GList *attachments_list)
938 {
939         GList *pos;
940         TnyMimePart *attachment_part, *old_attachment;
941         const gchar *attachment_content_type;
942         const gchar *attachment_filename;
943         TnyStream *attachment_stream;
944         TnyPlatformFactory *fact;
945
946         fact = modest_tny_platform_factory_get_instance ();
947         for (pos = (GList *)attachments_list; pos; pos = pos->next) {
948
949                 old_attachment = pos->data;
950                 attachment_filename = tny_mime_part_get_filename (old_attachment);
951                 attachment_stream = tny_mime_part_get_stream (old_attachment);
952                 attachment_part = tny_platform_factory_new_mime_part (fact);
953                 
954                 attachment_content_type = tny_mime_part_get_content_type (old_attachment);
955                                  
956                 tny_mime_part_construct_from_stream (attachment_part,
957                                                      attachment_stream,
958                                                      attachment_content_type);
959                 tny_stream_reset (attachment_stream);
960                 
961                 tny_mime_part_set_filename (attachment_part, attachment_filename);
962                 
963                 tny_mime_part_add_part (TNY_MIME_PART (msg), attachment_part);
964 /*              g_object_unref (attachment_part); */
965         }
966 }
967
968
969 static TnyMimePart *
970 add_body_part (TnyMsg *msg, 
971                const gchar *body,
972                const gchar *content_type,
973                gboolean has_attachments)
974 {
975         TnyMimePart *text_body_part = NULL;
976         TnyStream *text_body_stream;
977         TnyPlatformFactory *fact;
978
979         fact = modest_tny_platform_factory_get_instance ();
980
981         /* Create the stream */
982         text_body_stream = TNY_STREAM (tny_camel_stream_new
983                                        (camel_stream_mem_new_with_buffer
984                                         (body, strlen(body))));
985
986         /* Create body part if needed */
987         if (has_attachments)
988                 text_body_part = tny_platform_factory_new_mime_part (fact);
989         else
990                 text_body_part = TNY_MIME_PART(msg);
991
992         /* Construct MIME part */
993         tny_stream_reset (text_body_stream);
994         tny_mime_part_construct_from_stream (text_body_part,
995                                              text_body_stream,
996                                              content_type);
997         tny_stream_reset (text_body_stream);
998
999         /* Add part if needed */
1000         if (has_attachments) {
1001                 tny_mime_part_add_part (TNY_MIME_PART (msg), text_body_part);
1002                 g_object_unref (G_OBJECT(text_body_part));
1003         }
1004
1005         /* Clean */
1006         g_object_unref (text_body_stream);
1007
1008         return text_body_part;
1009 }