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