* modest-mail-operation.c:
[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
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 static TnyFolder * modest_mail_operation_find_trash_folder (ModestMailOperation *self,
89                                                             TnyStoreAccount *store_account);
90
91
92 enum _ModestMailOperationSignals 
93 {
94         PROGRESS_CHANGED_SIGNAL,
95
96         NUM_SIGNALS
97 };
98
99 typedef struct _ModestMailOperationPrivate ModestMailOperationPrivate;
100 struct _ModestMailOperationPrivate {
101         guint                      done;
102         guint                      total;
103         ModestMailOperationStatus  status;
104         GError                    *error;
105 };
106 #define MODEST_MAIL_OPERATION_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
107                                                    MODEST_TYPE_MAIL_OPERATION, \
108                                                    ModestMailOperationPrivate))
109
110 typedef struct _RefreshFolderAsyncHelper
111 {
112         ModestMailOperation *mail_op;
113         TnyIterator *iter;
114         guint failed;
115         guint canceled;
116
117 } RefreshFolderAsyncHelper;
118
119 /* some utility functions */
120 static char * get_content_type(const gchar *s);
121 static gboolean is_ascii(const gchar *s);
122
123 /* globals */
124 static GObjectClass *parent_class = NULL;
125
126 static guint signals[NUM_SIGNALS] = {0};
127
128 GType
129 modest_mail_operation_get_type (void)
130 {
131         static GType my_type = 0;
132         if (!my_type) {
133                 static const GTypeInfo my_info = {
134                         sizeof(ModestMailOperationClass),
135                         NULL,           /* base init */
136                         NULL,           /* base finalize */
137                         (GClassInitFunc) modest_mail_operation_class_init,
138                         NULL,           /* class finalize */
139                         NULL,           /* class data */
140                         sizeof(ModestMailOperation),
141                         1,              /* n_preallocs */
142                         (GInstanceInitFunc) modest_mail_operation_init,
143                         NULL
144                 };
145                 my_type = g_type_register_static (G_TYPE_OBJECT,
146                                                   "ModestMailOperation",
147                                                   &my_info, 0);
148         }
149         return my_type;
150 }
151
152 static void
153 modest_mail_operation_class_init (ModestMailOperationClass *klass)
154 {
155         GObjectClass *gobject_class;
156         gobject_class = (GObjectClass*) klass;
157
158         parent_class            = g_type_class_peek_parent (klass);
159         gobject_class->finalize = modest_mail_operation_finalize;
160
161         g_type_class_add_private (gobject_class, sizeof(ModestMailOperationPrivate));
162
163         /**
164          * ModestMailOperation::progress-changed
165          * @self: the #MailOperation that emits the signal
166          * @user_data: user data set when the signal handler was connected
167          *
168          * Emitted when the progress of a mail operation changes
169          */
170         signals[PROGRESS_CHANGED_SIGNAL] = 
171                 g_signal_new ("progress_changed",
172                               G_TYPE_FROM_CLASS (gobject_class),
173                               G_SIGNAL_RUN_FIRST,
174                               G_STRUCT_OFFSET (ModestMailOperationClass, progress_changed),
175                               NULL, NULL,
176                               g_cclosure_marshal_VOID__VOID,
177                               G_TYPE_NONE, 0);
178 }
179
180 static void
181 modest_mail_operation_init (ModestMailOperation *obj)
182 {
183         ModestMailOperationPrivate *priv;
184
185         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(obj);
186
187         priv->status   = MODEST_MAIL_OPERATION_STATUS_INVALID;
188         priv->error    = NULL;
189         priv->done     = 0;
190         priv->total    = 0;
191 }
192
193 static void
194 modest_mail_operation_finalize (GObject *obj)
195 {
196         ModestMailOperationPrivate *priv;
197
198         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(obj);
199
200         if (priv->error) {
201                 g_error_free (priv->error);
202                 priv->error = NULL;
203         }
204
205         G_OBJECT_CLASS(parent_class)->finalize (obj);
206 }
207
208 ModestMailOperation*
209 modest_mail_operation_new (void)
210 {
211         return MODEST_MAIL_OPERATION(g_object_new(MODEST_TYPE_MAIL_OPERATION, NULL));
212 }
213
214
215 void
216 modest_mail_operation_send_mail (ModestMailOperation *self,
217                                  TnyTransportAccount *transport_account,
218                                  TnyMsg* msg)
219 {
220         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
221         g_return_if_fail (TNY_IS_TRANSPORT_ACCOUNT (transport_account));
222
223         tny_transport_account_send (transport_account, msg, NULL); /* FIXME */
224 }
225
226 void
227 modest_mail_operation_send_new_mail (ModestMailOperation *self,
228                                      TnyTransportAccount *transport_account,
229                                      const gchar *from,
230                                      const gchar *to,
231                                      const gchar *cc,
232                                      const gchar *bcc,
233                                      const gchar *subject,
234                                      const gchar *body,
235                                      const GList *attachments_list)
236 {
237         TnyPlatformFactory *fact;
238         TnyMsg *new_msg;
239         TnyHeader *header;
240         gchar *content_type;
241         ModestMailOperationPrivate *priv = NULL;
242
243         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
244         g_return_if_fail (TNY_IS_TRANSPORT_ACCOUNT (transport_account));
245
246         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
247
248         /* Check parametters */
249         if (to == NULL) {
250                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
251                              MODEST_MAIL_OPERATION_ERROR_MISSING_PARAMETER,
252                              _("Error trying to send a mail. You need to set almost one a recipient"));
253                 return;
254         }
255
256         /* Create new msg */
257         fact    = modest_tny_platform_factory_get_instance ();
258         new_msg = tny_platform_factory_new_msg (fact);
259         header  = tny_platform_factory_new_header (fact);
260
261         /* WARNING: set the header before assign values to it */
262         tny_msg_set_header (new_msg, header);
263         tny_header_set_from (TNY_HEADER (header), from);
264         tny_header_set_replyto (TNY_HEADER (header), from);
265         tny_header_set_to (TNY_HEADER (header), to);
266         tny_header_set_cc (TNY_HEADER (header), cc);
267         tny_header_set_bcc (TNY_HEADER (header), bcc);
268         tny_header_set_subject (TNY_HEADER (header), subject);
269
270         content_type = get_content_type(body);
271
272         /* Add the body of the new mail */      
273         add_body_part (new_msg, body, (const gchar *) content_type,
274                        (attachments_list == NULL) ? FALSE : TRUE);
275
276         /* Add attachments */
277         add_attachments (new_msg, (GList*) attachments_list);
278
279         /* Send mail */
280         tny_transport_account_send (transport_account, new_msg, NULL); /* FIXME */
281
282         /* Clean */
283         g_object_unref (header);
284         g_object_unref (new_msg);
285         g_free(content_type);
286 }
287
288 static void
289 add_if_attachment (gpointer data, gpointer user_data)
290 {
291         TnyMimePart *part;
292         GList *attachments_list;
293
294         part = TNY_MIME_PART (data);
295         attachments_list = (GList *) user_data;
296
297         if (tny_mime_part_is_attachment (part))
298                 attachments_list = g_list_prepend (attachments_list, part);
299 }
300
301
302 static TnyMsg *
303 create_reply_forward_mail (TnyMsg *msg, const gchar *from, gboolean is_reply, guint type)
304 {
305         TnyPlatformFactory *fact;
306         TnyMsg *new_msg;
307         TnyHeader *new_header, *header;
308         gchar *new_subject;
309         TnyMimePart *body;
310         ModestFormatter *formatter;
311
312         /* Get body from original msg */
313         header = tny_msg_get_header (msg);
314         body   = modest_tny_msg_actions_find_body_part (msg, TRUE);
315
316         /* TODO: select the formatter from account prefs */
317         formatter = modest_formatter_new ("text/plain");
318
319         /* Format message body */
320         if (is_reply) {
321                 switch (type) {
322                 case MODEST_MAIL_OPERATION_REPLY_TYPE_CITE:
323                 default:
324                         new_msg = modest_formatter_cite  (formatter, body, header);
325                         break;
326                 case MODEST_MAIL_OPERATION_REPLY_TYPE_QUOTE:
327                         new_msg = modest_formatter_quote (formatter, body, header);
328                         break;
329                 }
330         } else {
331                 switch (type) {
332                 case MODEST_MAIL_OPERATION_FORWARD_TYPE_INLINE:
333                 default:
334                         new_msg = modest_formatter_inline  (formatter, body, header);
335                         break;
336                 case MODEST_MAIL_OPERATION_FORWARD_TYPE_ATTACHMENT:
337                         new_msg = modest_formatter_attach (formatter, body, header);
338                         break;
339                 }
340         }
341         g_object_unref (G_OBJECT (formatter));
342
343         /* Fill the header */
344         fact = modest_tny_platform_factory_get_instance ();
345         new_header = TNY_HEADER (tny_platform_factory_new_header (fact));
346         tny_msg_set_header (new_msg, new_header);
347         tny_header_set_from (new_header, from);
348         tny_header_set_replyto (new_header, from);
349
350         /* Change the subject */
351         new_subject = 
352                 (gchar *) modest_text_utils_derived_subject (tny_header_get_subject(header), 
353                                                              (is_reply) ? _("Re:") : _("Fwd:"));
354         tny_header_set_subject (new_header, (const gchar *) new_subject);
355         g_free (new_subject);
356
357         /* Clean */
358         g_object_unref (G_OBJECT (new_header));
359         g_object_unref (G_OBJECT (header));
360
361         return new_msg;
362 }
363
364 TnyMsg* 
365 modest_mail_operation_create_forward_mail (TnyMsg *msg, 
366                                            const gchar *from,
367                                            ModestMailOperationForwardType forward_type)
368 {
369         TnyMsg *new_msg;
370         TnyList *parts = NULL;
371         GList *attachments_list = NULL;
372
373         new_msg = create_reply_forward_mail (msg, from, FALSE, forward_type);
374
375         /* Add attachments */
376         parts = TNY_LIST (tny_simple_list_new());
377         tny_mime_part_get_parts (TNY_MIME_PART (msg), parts);
378         tny_list_foreach (parts, add_if_attachment, attachments_list);
379         add_attachments (new_msg, attachments_list);
380
381         /* Clean */
382         if (attachments_list) g_list_free (attachments_list);
383         g_object_unref (G_OBJECT (parts));
384
385         return new_msg;
386 }
387
388 TnyMsg* 
389 modest_mail_operation_create_reply_mail (TnyMsg *msg, 
390                                          const gchar *from,
391                                          ModestMailOperationReplyType reply_type,
392                                          ModestMailOperationReplyMode reply_mode)
393 {
394         TnyMsg *new_msg;
395         TnyHeader *new_header, *header;
396         const gchar* reply_to;
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         if (reply_to)
405                 tny_header_set_to (new_header, reply_to);
406         else
407                 tny_header_set_to (new_header, tny_header_get_from (header));
408
409         switch (reply_mode) {
410                 gchar *new_cc = NULL;
411                 const gchar *cc = NULL, *bcc = NULL;
412                 GString *tmp = NULL;
413
414         case MODEST_MAIL_OPERATION_REPLY_MODE_SENDER:
415                 /* Do not fill neither cc nor bcc */
416                 break;
417         case MODEST_MAIL_OPERATION_REPLY_MODE_LIST:
418                 /* TODO */
419                 break;
420         case MODEST_MAIL_OPERATION_REPLY_MODE_ALL:
421                 /* Concatenate to, cc and bcc */
422                 cc = tny_header_get_cc (header);
423                 bcc = tny_header_get_bcc (header);
424
425                 tmp = g_string_new (tny_header_get_to (header));
426                 if (cc)  g_string_append_printf (tmp, ",%s",cc);
427                 if (bcc) g_string_append_printf (tmp, ",%s",bcc);
428
429                /* Remove my own address from the cc list. TODO:
430                   remove also the To: of the new message, needed due
431                   to the new reply_to feature */
432                 new_cc = (gchar *) 
433                         modest_text_utils_remove_address ((const gchar *) tmp->str, 
434                                                           from);
435                 /* FIXME: remove also the mails from the new To: */
436                 tny_header_set_cc (new_header, new_cc);
437
438                 /* Clean */
439                 g_string_free (tmp, TRUE);
440                 g_free (new_cc);
441                 break;
442         }
443
444         /* Clean */
445         g_object_unref (G_OBJECT (new_header));
446         g_object_unref (G_OBJECT (header));
447
448         return new_msg;
449 }
450
451 static void
452 status_update_cb (TnyFolder *folder, const gchar *what, gint status, gint oftotal, gpointer user_data) 
453 {
454         g_print ("%s status: %d, of total %d\n", what, status, oftotal);
455 }
456
457 static void
458 folder_refresh_cb (TnyFolder *folder, gboolean canceled, GError **err, gpointer user_data)
459 {
460         ModestMailOperation *self = NULL;
461         ModestMailOperationPrivate *priv = NULL;
462         RefreshFolderAsyncHelper *helper;
463
464         helper = (RefreshFolderAsyncHelper *) user_data;
465         self = MODEST_MAIL_OPERATION (helper->mail_op);
466         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
467
468         if ((canceled && *err) || *err) {
469                 priv->error = g_error_copy (*err);
470                 helper->failed++;
471         } else if (canceled) {
472                 helper->canceled++;
473                 g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
474                              MODEST_MAIL_OPERATION_ERROR_OPERATION_CANCELED,
475                              _("Error trying to refresh folder %s. Operation canceled"),
476                              tny_folder_get_name (folder));
477         } else {
478                 priv->done++;
479         }
480
481         if (priv->done == priv->total)
482                 priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
483         else if ((priv->done + helper->canceled + helper->failed) == priv->total) {
484                 if (helper->failed == priv->total)
485                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
486                 else if (helper->failed == priv->total)
487                         priv->status = MODEST_MAIL_OPERATION_STATUS_CANCELED;
488                 else
489                         priv->status = MODEST_MAIL_OPERATION_STATUS_FINISHED_WITH_ERRORS;
490         }
491         tny_iterator_next (helper->iter);
492         if (tny_iterator_is_done (helper->iter)) {
493                 TnyList *list;
494                 list = tny_iterator_get_list (helper->iter);
495                 g_object_unref (G_OBJECT (helper->iter));
496                 g_object_unref (G_OBJECT (list));
497                 g_slice_free (RefreshFolderAsyncHelper, helper);
498         } else {
499                 tny_folder_refresh_async (TNY_FOLDER (tny_iterator_get_current (helper->iter)),
500                                           folder_refresh_cb,
501                                           status_update_cb, 
502                                           helper);
503         }
504         g_signal_emit (G_OBJECT (self), signals[PROGRESS_CHANGED_SIGNAL], 0, NULL);
505 }
506
507
508 static void
509 update_folders_cb (TnyFolderStore *folder_store, TnyList *list, GError **err, gpointer user_data)
510 {
511         ModestMailOperation *self;
512         ModestMailOperationPrivate *priv;
513         RefreshFolderAsyncHelper *helper;
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         tny_folder_refresh_async (TNY_FOLDER (tny_iterator_get_current (helper->iter)),
536                                   folder_refresh_cb,
537                                   status_update_cb, 
538                                   helper);
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
691                 trash_folder = modest_mail_operation_find_trash_folder (self,
692                                                                         TNY_STORE_ACCOUNT (folder_store));
693
694                 /* TODO: error_handling */
695                 modest_mail_operation_move_folder (self, 
696                                                    folder, 
697                                                    TNY_FOLDER_STORE (trash_folder));
698         } else {
699                 tny_folder_store_remove_folder (folder_store, folder, NULL); /* FIXME */
700                 g_object_unref (G_OBJECT (folder));
701         }
702
703         /* Free instances */
704         g_object_unref (G_OBJECT (folder_store));
705 }
706
707 void
708 modest_mail_operation_rename_folder (ModestMailOperation *self,
709                                      TnyFolder *folder,
710                                      const gchar *name)
711 {
712         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
713         g_return_if_fail (TNY_IS_FOLDER_STORE (folder));
714         g_return_if_fail (name);
715
716         /* FIXME: better error handling */
717         if (strrchr (name, '/') != NULL)
718                 return;
719
720         /* Rename. Camel handles folder subscription/unsubscription */
721         tny_folder_set_name (folder, name, NULL); /* FIXME */
722  }
723
724 void
725 modest_mail_operation_move_folder (ModestMailOperation *self,
726                                    TnyFolder *folder,
727                                    TnyFolderStore *parent)
728 {
729         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
730         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
731         g_return_if_fail (TNY_IS_FOLDER (folder));
732         
733         modest_mail_operation_xfer_folder (self, folder, parent, TRUE);
734 }
735
736 void
737 modest_mail_operation_copy_folder (ModestMailOperation *self,
738                                    TnyFolder *folder,
739                                    TnyFolderStore *parent)
740 {
741         g_return_if_fail (MODEST_IS_MAIL_OPERATION (self));
742         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
743         g_return_if_fail (TNY_IS_FOLDER (folder));
744
745         modest_mail_operation_xfer_folder (self, folder, parent, FALSE);
746 }
747
748 static void
749 modest_mail_operation_xfer_folder (ModestMailOperation *self,
750                                    TnyFolder *folder,
751                                    TnyFolderStore *parent,
752                                    gboolean delete_original)
753 {
754         const gchar *folder_name;
755         TnyFolder *dest_folder, *child;
756         TnyIterator *iter;
757         TnyList *folders, *headers;
758
759         g_return_if_fail (TNY_IS_FOLDER (folder));
760         g_return_if_fail (TNY_IS_FOLDER_STORE (parent));
761
762         /* Create the destination folder */
763         folder_name = tny_folder_get_name (folder);
764         dest_folder = modest_mail_operation_create_folder (self, 
765                                                            parent, folder_name);
766
767         /* Transfer messages */
768         headers = TNY_LIST (tny_simple_list_new ());
769         tny_folder_get_headers (folder, headers, FALSE, NULL); /* FIXME */
770         tny_folder_transfer_msgs (folder, headers, dest_folder, delete_original, NULL); /* FIXME */
771
772         /* Recurse children */
773         folders = TNY_LIST (tny_simple_list_new ());
774         tny_folder_store_get_folders (TNY_FOLDER_STORE (folder), folders, NULL, NULL ); /* FIXME */
775         iter = tny_list_create_iterator (folders);
776
777         while (!tny_iterator_is_done (iter)) {
778
779                 child = TNY_FOLDER (tny_iterator_get_current (iter));
780                 modest_mail_operation_xfer_folder (self, child,
781                                                    TNY_FOLDER_STORE (dest_folder),
782                                                    delete_original);
783                 tny_iterator_next (iter);
784         }
785
786         /* Delete source folder (if needed) */
787         if (delete_original)
788                 modest_mail_operation_remove_folder (self, folder, FALSE);
789
790         /* Clean up */
791         g_object_unref (G_OBJECT (dest_folder));
792         g_object_unref (G_OBJECT (headers));
793         g_object_unref (G_OBJECT (folders));
794         g_object_unref (G_OBJECT (iter));
795 }
796
797
798 /* FIXME: this method should be rewritten when the policy for the
799    Trash folder becomes clearer */
800 static TnyFolder *
801 modest_mail_operation_find_trash_folder (ModestMailOperation *self,
802                                          TnyStoreAccount *store_account)
803 {
804         TnyList *folders;
805         TnyIterator *iter;
806         gboolean found;
807         /*TnyFolderStoreQuery *query;*/
808         TnyFolder *trash_folder;
809
810         /* Look for Trash folder */
811         folders = TNY_LIST (tny_simple_list_new ());
812         tny_folder_store_get_folders (TNY_FOLDER_STORE (store_account),
813                                       folders, NULL, NULL); /* FIXME */
814         iter = tny_list_create_iterator (folders);
815
816         found = FALSE;
817         while (!tny_iterator_is_done (iter) && !found) {
818
819                 trash_folder = TNY_FOLDER (tny_iterator_get_current (iter));
820                 if (tny_folder_get_folder_type (trash_folder) == TNY_FOLDER_TYPE_TRASH)
821                         found = TRUE;
822                 else
823                         tny_iterator_next (iter);
824         }
825
826         /* Clean up */
827         g_object_unref (G_OBJECT (folders));
828         g_object_unref (G_OBJECT (iter));
829
830         /* TODO: better error handling management */
831         if (!found) 
832                 return NULL;
833         else
834                 return trash_folder;
835 }
836
837 /* ******************************************************************* */
838 /* **************************  MSG  ACTIONS  ************************* */
839 /* ******************************************************************* */
840
841 gboolean 
842 modest_mail_operation_copy_msg (ModestMailOperation *self,
843                                 TnyHeader *header, 
844                                 TnyFolder *folder)
845 {
846         g_return_val_if_fail (TNY_IS_HEADER (header), FALSE);
847         g_return_val_if_fail (TNY_IS_FOLDER (folder), FALSE);
848
849         return modest_mail_operation_xfer_msg (self, header, folder, FALSE);
850 }
851
852 gboolean 
853 modest_mail_operation_move_msg (ModestMailOperation *self,
854                                 TnyHeader *header, 
855                                 TnyFolder *folder)
856 {
857         g_return_val_if_fail (TNY_IS_HEADER (header), FALSE);
858         g_return_val_if_fail (TNY_IS_FOLDER (folder), FALSE);
859
860         return modest_mail_operation_xfer_msg (self, header, folder, TRUE);
861 }
862
863 void 
864 modest_mail_operation_remove_msg (ModestMailOperation *self,
865                                   TnyHeader *header,
866                                   gboolean remove_to_trash)
867 {
868         TnyFolder *folder;
869
870         g_return_if_fail (TNY_IS_HEADER (header));
871
872         folder = tny_header_get_folder (header);
873
874         /* Delete or move to trash */
875         if (remove_to_trash) {
876                 TnyFolder *trash_folder;
877                 TnyStoreAccount *store_account;
878
879                 store_account = TNY_STORE_ACCOUNT (tny_folder_get_account (folder));
880                 trash_folder = modest_mail_operation_find_trash_folder (self, store_account);
881
882                 if (trash_folder) {
883                         modest_mail_operation_move_msg (self, header, trash_folder);
884 /*                      g_object_unref (trash_folder); */
885                 } else {
886                         ModestMailOperationPrivate *priv;
887
888                         /* Set status failed and set an error */
889                         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
890                         priv->status = MODEST_MAIL_OPERATION_STATUS_FAILED;
891                         g_set_error (&(priv->error), MODEST_MAIL_OPERATION_ERROR,
892                                      MODEST_MAIL_OPERATION_ERROR_ITEM_NOT_FOUND,
893                                      _("Error trying to delete a message. Trash folder not found"));
894                 }
895
896                 g_object_unref (G_OBJECT (store_account));
897         } else {
898                 tny_folder_remove_msg (folder, header, NULL); /* FIXME */
899                 tny_folder_expunge (folder, NULL); /* FIXME */
900         }
901
902         /* Free */
903         g_object_unref (folder);
904 }
905
906 static void
907 transfer_msgs_cb (TnyFolder *folder, GError **err, gpointer user_data)
908 {
909         ModestMailOperationPrivate *priv;
910
911         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(user_data);
912         priv->done = 1;
913         priv->status = MODEST_MAIL_OPERATION_STATUS_SUCCESS;
914
915         g_signal_emit (G_OBJECT (user_data), signals[PROGRESS_CHANGED_SIGNAL], 0, NULL);
916 }
917
918 static gboolean
919 modest_mail_operation_xfer_msg (ModestMailOperation *self,
920                                 TnyHeader *header, 
921                                 TnyFolder *folder, 
922                                 gboolean delete_original)
923 {
924         ModestMailOperationPrivate *priv;
925         TnyFolder *src_folder;
926         TnyList *headers;
927
928         src_folder = tny_header_get_folder (header);
929         headers = tny_simple_list_new ();
930
931         priv = MODEST_MAIL_OPERATION_GET_PRIVATE(self);
932         priv->total = 1;
933         priv->done = 0;
934         priv->status = MODEST_MAIL_OPERATION_STATUS_IN_PROGRESS;
935
936         tny_list_prepend (headers, G_OBJECT (header));
937         tny_folder_transfer_msgs_async (src_folder, headers, folder, 
938                                         delete_original, transfer_msgs_cb, self);
939
940         /* Free */
941         g_object_unref (headers);
942         g_object_unref (folder);
943
944         return TRUE;
945 }
946
947
948 /* ******************************************************************* */
949 /* ************************* UTILIY FUNCTIONS ************************ */
950 /* ******************************************************************* */
951 static gboolean
952 is_ascii(const gchar *s)
953 {
954         while (s[0]) {
955                 if (s[0] & 128 || s[0] < 32)
956                         return FALSE;
957                 s++;
958         }
959         return TRUE;
960 }
961
962 static char *
963 get_content_type(const gchar *s)
964 {
965         GString *type;
966         
967         type = g_string_new("text/plain");
968         if (!is_ascii(s)) {
969                 if (g_utf8_validate(s, -1, NULL)) {
970                         g_string_append(type, "; charset=\"utf-8\"");
971                 } else {
972                         /* it should be impossible to reach this, but better safe than sorry */
973                         g_warning("invalid utf8 in message");
974                         g_string_append(type, "; charset=\"latin1\"");
975                 }
976         }
977         return g_string_free(type, FALSE);
978 }
979
980 static void
981 add_attachments (TnyMsg *msg, GList *attachments_list)
982 {
983         GList *pos;
984         TnyMimePart *attachment_part, *old_attachment;
985         const gchar *attachment_content_type;
986         const gchar *attachment_filename;
987         TnyStream *attachment_stream;
988         TnyPlatformFactory *fact;
989
990         fact = modest_tny_platform_factory_get_instance ();
991         for (pos = (GList *)attachments_list; pos; pos = pos->next) {
992
993                 old_attachment = pos->data;
994                 attachment_filename = tny_mime_part_get_filename (old_attachment);
995                 attachment_stream = tny_mime_part_get_stream (old_attachment);
996                 attachment_part = tny_platform_factory_new_mime_part (fact);
997                 
998                 attachment_content_type = tny_mime_part_get_content_type (old_attachment);
999                                  
1000                 tny_mime_part_construct_from_stream (attachment_part,
1001                                                      attachment_stream,
1002                                                      attachment_content_type);
1003                 tny_stream_reset (attachment_stream);
1004                 
1005                 tny_mime_part_set_filename (attachment_part, attachment_filename);
1006                 
1007                 tny_mime_part_add_part (TNY_MIME_PART (msg), attachment_part);
1008 /*              g_object_unref (attachment_part); */
1009         }
1010 }
1011
1012
1013 static TnyMimePart *
1014 add_body_part (TnyMsg *msg, 
1015                const gchar *body,
1016                const gchar *content_type,
1017                gboolean has_attachments)
1018 {
1019         TnyMimePart *text_body_part = NULL;
1020         TnyStream *text_body_stream;
1021         TnyPlatformFactory *fact;
1022
1023         fact = modest_tny_platform_factory_get_instance ();
1024
1025         /* Create the stream */
1026         text_body_stream = TNY_STREAM (tny_camel_stream_new
1027                                        (camel_stream_mem_new_with_buffer
1028                                         (body, strlen(body))));
1029
1030         /* Create body part if needed */
1031         if (has_attachments)
1032                 text_body_part = tny_platform_factory_new_mime_part (fact);
1033         else
1034                 text_body_part = TNY_MIME_PART(msg);
1035
1036         /* Construct MIME part */
1037         tny_stream_reset (text_body_stream);
1038         tny_mime_part_construct_from_stream (text_body_part,
1039                                              text_body_stream,
1040                                              content_type);
1041         tny_stream_reset (text_body_stream);
1042
1043         /* Add part if needed */
1044         if (has_attachments) {
1045                 tny_mime_part_add_part (TNY_MIME_PART (msg), text_body_part);
1046                 g_object_unref (G_OBJECT(text_body_part));
1047         }
1048
1049         /* Clean */
1050         g_object_unref (text_body_stream);
1051
1052         return text_body_part;
1053 }