* leak fixes; free both list and its elements when we call modest_account_mgr_account...
[modest] / src / modest-tny-account-store.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 <string.h>
31 #include <glib/gi18n.h>
32
33 #include <tny-account.h>
34 #include <tny-account-store.h>
35 #include <tny-store-account.h>
36 #include <tny-error.h>
37 #include <tny-transport-account.h>
38 #include <tny-simple-list.h>
39 #include <tny-account-store.h>
40 #include <tny-camel-transport-account.h>
41 #include <tny-camel-imap-store-account.h>
42 #include <tny-camel-pop-store-account.h>
43
44 #include <modest-runtime.h>
45 #include <modest-marshal.h>
46 #include <modest-protocol-info.h>
47 #include <modest-local-folder-info.h>
48 #include <modest-tny-account.h>
49 #include <modest-tny-local-folders-account.h>
50 #include <modest-account-mgr.h>
51 #include <modest-account-mgr-helpers.h>
52 #include <widgets/modest-window-mgr.h>
53 #include <modest-account-settings-dialog.h>
54
55
56 #include "modest-tny-account-store.h"
57 #include "modest-tny-platform-factory.h"
58 #include <tny-gtk-lockable.h>
59 #include <camel/camel.h>
60
61 #ifdef MODEST_PLATFORM_MAEMO
62 #include <tny-maemo-conic-device.h>
63 #ifdef MODEST_HILDON_VERSION_0
64 #include <hildon-widgets/hildon-note.h>
65 #include <hildon-widgets/hildon-banner.h>
66 #else
67 #include <hildon/hildon-note.h>
68 #include <hildon/hildon-banner.h>
69 #endif
70 #endif
71
72 #include <libgnomevfs/gnome-vfs-volume-monitor.h>
73
74 /* 'private'/'protected' functions */
75 static void modest_tny_account_store_class_init   (ModestTnyAccountStoreClass *klass);
76 //static void modest_tny_account_store_init         (ModestTnyAccountStore *obj);
77 static void modest_tny_account_store_finalize     (GObject *obj);
78
79 /* implementations for tny-account-store-iface */
80 static void    modest_tny_account_store_instance_init (ModestTnyAccountStore *obj);
81 static void    modest_tny_account_store_init          (gpointer g, gpointer iface_data);
82
83
84 static void    get_server_accounts                    (TnyAccountStore *self, 
85                                                        TnyList *list, 
86                                                        TnyAccountType type);
87
88 /* list my signals */
89 enum {
90         ACCOUNT_UPDATE_SIGNAL,
91         PASSWORD_REQUESTED_SIGNAL,
92         LAST_SIGNAL
93 };
94
95 typedef struct _ModestTnyAccountStorePrivate ModestTnyAccountStorePrivate;
96 struct _ModestTnyAccountStorePrivate {
97         gchar              *cache_dir;  
98         GHashTable         *password_hash;
99         ModestAccountMgr   *account_mgr;
100         TnySessionCamel    *session;
101         TnyDevice          *device;
102         
103         /* We cache the lists of accounts here.
104          * They are created in our get_accounts_func() implementation. */
105         GSList             *store_accounts;
106         GSList             *transport_accounts;
107         
108         /* This is also contained in store_accounts,
109          * but we cached it temporarily separately, 
110          * because we create this while creating the transport accounts, 
111          * but return it when requesting the store accounts: 
112          */
113         GSList             *store_accounts_outboxes;
114 };
115
116 #define MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
117                                                       MODEST_TYPE_TNY_ACCOUNT_STORE, \
118                                                       ModestTnyAccountStorePrivate))
119
120 /* globals */
121 static GObjectClass *parent_class = NULL;
122
123 static guint signals[LAST_SIGNAL] = {0};
124
125 GType
126 modest_tny_account_store_get_type (void)
127 {
128         static GType my_type = 0;
129
130         if (!my_type) {
131                 static const GTypeInfo my_info = {
132                         sizeof(ModestTnyAccountStoreClass),
133                         NULL,           /* base init */
134                         NULL,           /* base finalize */
135                         (GClassInitFunc) modest_tny_account_store_class_init,
136                         NULL,           /* class finalize */
137                         NULL,           /* class data */
138                         sizeof(ModestTnyAccountStore),
139                         0,              /* n_preallocs */
140                         (GInstanceInitFunc) modest_tny_account_store_instance_init,
141                         NULL
142                 };
143
144                 static const GInterfaceInfo iface_info = {
145                         (GInterfaceInitFunc) modest_tny_account_store_init,
146                         NULL,         /* interface_finalize */
147                         NULL          /* interface_data */
148                 };
149                 /* hack hack */
150                 my_type = g_type_register_static (G_TYPE_OBJECT,
151                                                   "ModestTnyAccountStore",
152                                                   &my_info, 0);
153                 g_type_add_interface_static (my_type, TNY_TYPE_ACCOUNT_STORE,
154                                              &iface_info);
155         }
156         return my_type;
157 }
158
159 static void
160 modest_tny_account_store_class_init (ModestTnyAccountStoreClass *klass)
161 {
162         GObjectClass *gobject_class;
163         gobject_class = (GObjectClass*) klass;
164
165         parent_class            = g_type_class_peek_parent (klass);
166         gobject_class->finalize = modest_tny_account_store_finalize;
167
168         g_type_class_add_private (gobject_class,
169                                   sizeof(ModestTnyAccountStorePrivate));
170
171          signals[ACCOUNT_UPDATE_SIGNAL] =
172                 g_signal_new ("account_update",
173                               G_TYPE_FROM_CLASS (gobject_class),
174                               G_SIGNAL_RUN_FIRST,
175                               G_STRUCT_OFFSET(ModestTnyAccountStoreClass, account_update),
176                               NULL, NULL,
177                               g_cclosure_marshal_VOID__STRING,
178                               G_TYPE_NONE, 1, G_TYPE_STRING);
179          
180          signals[PASSWORD_REQUESTED_SIGNAL] =
181                  g_signal_new ("password_requested",
182                                G_TYPE_FROM_CLASS (gobject_class),
183                                G_SIGNAL_RUN_FIRST,
184                                G_STRUCT_OFFSET(ModestTnyAccountStoreClass, password_requested),
185                                NULL, NULL,
186                                modest_marshal_VOID__STRING_POINTER_POINTER_POINTER_POINTER,
187                                G_TYPE_NONE, 5, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_POINTER, G_TYPE_POINTER,
188                                G_TYPE_POINTER);
189 }
190
191
192      
193 static void
194 on_vfs_volume_mounted(GnomeVFSVolumeMonitor *volume_monitor, 
195         GnomeVFSVolume *volume, gpointer user_data);
196
197 static void
198 on_vfs_volume_unmounted(GnomeVFSVolumeMonitor *volume_monitor, 
199         GnomeVFSVolume *volume, gpointer user_data);
200
201 static void
202 modest_tny_account_store_instance_init (ModestTnyAccountStore *obj)
203 {
204         ModestTnyAccountStorePrivate *priv =
205                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
206
207         priv->cache_dir              = NULL;
208         priv->account_mgr            = NULL;
209         priv->session                = NULL;
210         priv->device                 = NULL;
211         
212         /* An in-memory store of passwords, 
213          * for passwords that are not remembered in the configuration,
214          * so they need to be asked for from the user once in each session:
215          */
216         priv->password_hash          = g_hash_table_new_full (g_str_hash, g_str_equal,
217                                                               g_free, g_free);
218                                                               
219         /* Respond to volume mounts and unmounts, such 
220          * as the insertion/removal of the memory card: */
221         GnomeVFSVolumeMonitor* monitor = 
222                 gnome_vfs_get_volume_monitor();
223         g_signal_connect (G_OBJECT(monitor), "volume-mounted",
224                           G_CALLBACK(on_vfs_volume_mounted),
225                           obj);
226         g_signal_connect (G_OBJECT(monitor), "volume-unmounted",
227                           G_CALLBACK(on_vfs_volume_unmounted),
228                           obj);
229 }
230
231 static void
232 account_list_free (GSList *accounts)
233 {
234         GSList *cursor = accounts;
235
236         while (cursor) {
237                 if (G_IS_OBJECT(cursor->data)) { /* check twice... */
238                         const gchar *id = tny_account_get_id(TNY_ACCOUNT(cursor->data));
239                         modest_runtime_verify_object_last_ref(cursor->data,id);
240                 }                       
241                 g_object_unref (G_OBJECT(cursor->data));
242                 cursor = cursor->next;
243         }
244         g_slist_free (accounts);
245 }
246
247 static void
248 recreate_all_accounts (ModestTnyAccountStore *self)
249 {
250         ModestTnyAccountStorePrivate *priv = 
251                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
252         
253         if (priv->store_accounts_outboxes) {
254                 account_list_free (priv->store_accounts_outboxes);
255                 priv->store_accounts_outboxes = NULL;
256         }
257                         
258         if (priv->store_accounts) {
259                 account_list_free (priv->store_accounts);
260                 priv->store_accounts = NULL;
261                 get_server_accounts (TNY_ACCOUNT_STORE(self),
262                                              NULL, TNY_ACCOUNT_TYPE_STORE);
263         }
264         
265         if (priv->transport_accounts) {
266                 account_list_free (priv->transport_accounts);
267                 priv->transport_accounts = NULL;
268                 get_server_accounts (TNY_ACCOUNT_STORE(self), NULL,
269                                              TNY_ACCOUNT_TYPE_TRANSPORT);
270         }
271 }
272
273 static void
274 on_vfs_volume_mounted(GnomeVFSVolumeMonitor *volume_monitor, 
275         GnomeVFSVolume *volume, gpointer user_data)
276 {
277         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
278         
279         /* Check whether this was the external MMC1 card: */
280         gchar *uri = gnome_vfs_volume_get_activation_uri (volume);      
281         if (uri && (strcmp (uri, MODEST_MCC1_VOLUMEPATH_URI) == 0)) {
282                 printf ("DEBUG: %s: MMC1 card mounted.\n", __FUNCTION__);
283                 
284                 /* TODO: Just add an account and emit (and respond to) 
285                  * TnyAccountStore::accountinserted signal?
286                  */
287                 recreate_all_accounts (self);
288                 
289                 g_signal_emit (G_OBJECT(self), signals[ACCOUNT_UPDATE_SIGNAL], 0,
290                                NULL);
291         }
292         
293         g_free (uri);
294 }
295
296 static void
297 on_vfs_volume_unmounted(GnomeVFSVolumeMonitor *volume_monitor, 
298         GnomeVFSVolume *volume, gpointer user_data)
299 {
300         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
301         
302         /* Check whether this was the external MMC1 card: */
303         gchar *uri = gnome_vfs_volume_get_activation_uri (volume);
304         if (uri && (strcmp (uri, MODEST_MCC1_VOLUMEPATH_URI) == 0)) {
305                 printf ("DEBUG: %s: MMC1 card unmounted.\n", __FUNCTION__);
306                 
307                 /* TODO: Just add an account and emit (and respond to) 
308                  * TnyAccountStore::accountinserted signal?
309                  */
310                 recreate_all_accounts (self);
311                 
312                 g_signal_emit (G_OBJECT(self), signals[ACCOUNT_UPDATE_SIGNAL], 0,
313                                NULL);
314         }
315         
316         g_free (uri);
317 }
318
319 static void
320 on_account_removed (ModestAccountMgr *acc_mgr, 
321                     const gchar *account,
322                     gboolean server_account,
323                     gpointer user_data)
324 {
325         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
326         TnyAccount *store_account;
327         
328         /* Clear the account cache */
329         store_account = modest_tny_account_store_get_tny_account_by  (self, 
330                                                                       MODEST_TNY_ACCOUNT_STORE_QUERY_NAME, 
331                                                                       account);
332         if (store_account) {
333                 tny_store_account_delete_cache (TNY_STORE_ACCOUNT (store_account));
334                 
335                 g_signal_emit (G_OBJECT (self), 
336                                          tny_account_store_signals [TNY_ACCOUNT_STORE_ACCOUNT_REMOVED], 
337                                          0, store_account);
338
339                 g_object_unref (store_account);
340         } else
341                 g_printerr ("modest: cannot find server account for %s", account);
342         
343         /* FIXME: make this more finegrained; changes do not
344          * really affect _all_ accounts, and some do not
345          * affect tny accounts at all (such as 'last_update')
346          */
347         recreate_all_accounts (self);
348
349         g_signal_emit (G_OBJECT(self), signals[ACCOUNT_UPDATE_SIGNAL], 0,
350                        account);
351 }
352
353 static void
354 on_account_changed (ModestAccountMgr *acc_mgr, const gchar *account,
355                     const GSList *keys, gboolean server_account, gpointer user_data)
356
357 {
358         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
359         
360         /* Ignore the change if it's a change in the last_updated value */
361         if (g_slist_length ((GSList *)keys) == 1 &&
362             g_str_has_suffix ((const gchar *) keys->data, MODEST_ACCOUNT_LAST_UPDATED))
363                 return;
364
365         /* FIXME: make this more finegrained; changes do not really affect _all_
366          * accounts
367          */
368         recreate_all_accounts (self);
369
370         g_signal_emit (G_OBJECT(self), signals[ACCOUNT_UPDATE_SIGNAL], 0,
371                        account);
372 }
373
374
375 static ModestTnyAccountStore*
376 get_account_store_for_account (TnyAccount *account)
377 {
378         return MODEST_TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
379                                                            "account_store"));
380 }
381
382 /* This callback will be called by Tinymail when it needs the password
383  * from the user, for instance if the password was not remembered.
384  * Note that TnyAccount here will be the server account. */
385 static gchar*
386 get_password (TnyAccount *account, const gchar *prompt, gboolean *cancel)
387 {
388         /* Initialize the output parameter: */
389         if (cancel)
390           *cancel = FALSE;
391           
392         const gchar *key;
393         const TnyAccountStore *account_store;
394         ModestTnyAccountStore *self;
395         ModestTnyAccountStorePrivate *priv;
396         gchar *username = NULL;
397         gchar *pwd = NULL;
398         gpointer pwd_ptr;
399         gboolean already_asked;
400         
401         key           = tny_account_get_id (account);
402         account_store = TNY_ACCOUNT_STORE(get_account_store_for_account (account));
403         
404         self = MODEST_TNY_ACCOUNT_STORE (account_store);
405         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
406         
407         /* This hash map stores passwords, including passwords that are not stored in gconf. */
408         /* is it in the hash? if it's already there, it must be wrong... */
409         pwd_ptr = (gpointer)&pwd; /* pwd_ptr so the compiler does not complained about
410                                    * type-punned ptrs...*/
411         already_asked = g_hash_table_lookup_extended (priv->password_hash,
412                                                       key,
413                                                       NULL,
414                                                       (gpointer*)&pwd_ptr);
415
416         /* if the password is not already there, try ModestConf */
417         if (!already_asked) {
418                 pwd  = modest_account_mgr_get_string (priv->account_mgr,
419                                                       key, MODEST_ACCOUNT_PASSWORD, TRUE);
420                 g_hash_table_insert (priv->password_hash, g_strdup (key), g_strdup (pwd));
421         }
422
423         /* if it was already asked, it must have been wrong, so ask again */
424         /* TODO: However, when we supply a wrong password to tinymail, 
425          * it seems to (at least sometimes) call our alert_func() instead of 
426          * asking for the password again.
427          */
428         if (already_asked || !pwd || strlen(pwd) == 0) {
429                 /* we don't have it yet. Get the password from the user */
430                 const gchar* account_id = tny_account_get_id (account);
431                 gboolean remember = FALSE;
432                 pwd = NULL;
433                 
434                 /* Note that we ignore the returned username here,
435                  * because it is enough that it will be stored in gconf 
436                  * by the signal handler. */
437                 g_signal_emit (G_OBJECT(self), signals[PASSWORD_REQUESTED_SIGNAL], 0,
438                                account_id, /* server_account_name */
439                                &username, &pwd, cancel, &remember);
440                 
441                 if (!*cancel) {
442                         if (remember)
443                                 modest_account_mgr_set_string (priv->account_mgr,key,
444                                                                MODEST_ACCOUNT_PASSWORD,
445                                                                pwd, TRUE);
446                         /* We need to dup the string even knowing that
447                            it's already a dup of the contents of an
448                            entry, because it if it's wrong, then camel
449                            will free it */
450                         g_hash_table_insert (priv->password_hash, g_strdup (key), g_strdup(pwd));
451                 } else {
452                         g_hash_table_remove (priv->password_hash, key);
453                         
454                         g_free (pwd);
455                         pwd = NULL;
456                 }
457
458                 g_free (username);
459                 username = NULL;
460         } else
461                 *cancel = FALSE;
462  
463     /* printf("  DEBUG: %s: returning %s\n", __FUNCTION__, pwd); */
464         
465         return pwd;
466 }
467
468 /* tinymail calls this if the connection failed due to an incorrect password.
469  * And it seems to call this for any general connection failure. */
470 static void
471 forget_password (TnyAccount *account)
472 {
473         printf ("DEBUG: %s\n", __FUNCTION__);
474         ModestTnyAccountStore *self;
475         ModestTnyAccountStorePrivate *priv;
476         const TnyAccountStore *account_store;
477         gchar *pwd;
478         const gchar *key;
479         
480         account_store = TNY_ACCOUNT_STORE(get_account_store_for_account (account));
481         self = MODEST_TNY_ACCOUNT_STORE (account_store);
482         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
483         key  = tny_account_get_id (account);
484
485         /* Do not remove the key, this will allow us to detect that we
486            have already asked for it at least once */
487         pwd = g_hash_table_lookup (priv->password_hash, key);
488         if (pwd) {
489                 memset (pwd, 0, strlen (pwd));
490                 g_hash_table_insert (priv->password_hash, g_strdup (key), NULL);
491         }
492
493         /* Remove from configuration system */
494         modest_account_mgr_unset (priv->account_mgr,
495                                   key, MODEST_ACCOUNT_PASSWORD, TRUE);
496 }
497
498
499 static void
500 modest_tny_account_store_finalize (GObject *obj)
501 {
502         ModestTnyAccountStore *self        = MODEST_TNY_ACCOUNT_STORE(obj);
503         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
504         
505         //gboolean debug = modest_runtime_get_debug_flags() & MODEST_RUNTIME_DEBUG_DEBUG_OBJECTS;
506
507         g_free (priv->cache_dir);
508         priv->cache_dir = NULL;
509         
510         if (priv->password_hash) {
511                 g_hash_table_destroy (priv->password_hash);
512                 priv->password_hash = NULL;
513         }
514
515         if (priv->account_mgr) {
516                 g_object_unref (G_OBJECT(priv->account_mgr));
517                 priv->account_mgr = NULL;
518         }
519
520         if (priv->device) {
521                 g_object_unref (G_OBJECT(priv->device));
522                 priv->device = NULL;
523         }
524
525         /* this includes the local folder */
526         account_list_free (priv->store_accounts);
527         priv->store_accounts = NULL;
528         
529         account_list_free (priv->transport_accounts);
530         priv->transport_accounts = NULL;
531
532         if (priv->session) {
533                 camel_object_unref (CAMEL_OBJECT(priv->session));
534                 priv->session = NULL;
535         }
536         
537         G_OBJECT_CLASS(parent_class)->finalize (obj);
538 }
539
540
541 ModestTnyAccountStore*
542 modest_tny_account_store_new (ModestAccountMgr *account_mgr, TnyDevice *device) {
543
544         GObject *obj;
545         ModestTnyAccountStorePrivate *priv;
546         TnyList *list; 
547         
548         g_return_val_if_fail (account_mgr, NULL);
549         g_return_val_if_fail (device, NULL);
550
551         obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_ACCOUNT_STORE, NULL));
552         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
553
554         priv->account_mgr = g_object_ref (G_OBJECT(account_mgr));
555         priv->device = g_object_ref (device);
556         
557         priv->session = tny_session_camel_new (TNY_ACCOUNT_STORE(obj));
558         
559         tny_session_camel_set_ui_locker (priv->session,  tny_gtk_lockable_new ());
560         /* FIXME: unref this in the end? */
561         tny_session_camel_set_async_connecting (priv->session, TRUE);
562         
563         /* force a cache fill... ugly */
564         list = TNY_LIST(tny_simple_list_new());
565         tny_account_store_get_accounts (TNY_ACCOUNT_STORE(obj), list,
566                                         TNY_ACCOUNT_STORE_BOTH);
567         g_object_unref(list);
568         
569         /* Connect signals */
570         g_signal_connect (G_OBJECT(account_mgr), "account_changed",
571                                        G_CALLBACK (on_account_changed), obj);
572         g_signal_connect (G_OBJECT(account_mgr), "account_removed",
573                                        G_CALLBACK (on_account_removed), obj);
574
575         return MODEST_TNY_ACCOUNT_STORE(obj);
576 }
577
578 /** Fill the TnyList from the appropriate cached GSList of accounts. */
579 static void
580 get_cached_accounts (TnyAccountStore *self, TnyList *list, TnyAccountType type)
581 {
582         ModestTnyAccountStorePrivate *priv;
583         GSList                       *accounts, *cursor;
584         
585         priv     = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
586         accounts = (type == TNY_ACCOUNT_TYPE_STORE ? priv->store_accounts : priv->transport_accounts);
587
588         cursor = accounts;
589         while (cursor) {
590                 if (cursor->data) {
591                         GObject *object = G_OBJECT(cursor->data);
592                         tny_list_prepend (list, object);
593                 }
594                         
595                 cursor = cursor->next;
596         }
597 }
598
599 static void
600 create_per_account_local_outbox_folders (TnyAccountStore *self)
601 {
602         g_return_if_fail (self);
603         
604         ModestTnyAccountStorePrivate *priv = 
605                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
606         
607         /* printf("DEBUG: %s: priv->store_accounts_outboxes = %p\n", __FUNCTION__, priv->store_accounts_outboxes); */
608         
609         GSList *accounts = NULL;
610         
611         GSList *account_names  = modest_account_mgr_account_names (priv->account_mgr, 
612                 TRUE /* including disabled accounts */);
613         
614         GSList *iter = NULL;
615         for (iter = account_names; iter; iter = g_slist_next (iter)) {
616                 
617                 const gchar* account_name = (const gchar*)iter->data;
618                 
619                 /* Create a per-account local outbox folder (a _store_ account) 
620                  * for each _transport_ account: */
621                 TnyAccount *tny_account_outbox =
622                         modest_tny_account_new_for_per_account_local_outbox_folder (
623                                 priv->account_mgr, account_name, priv->session);
624                                 
625                 accounts = g_slist_append (accounts, tny_account_outbox); /* cache it */
626         };
627
628         modest_account_mgr_free_account_names (account_names);
629         account_names = NULL;
630         
631         priv->store_accounts_outboxes = accounts;
632 }
633
634 /* This function fills the TnyList, and also stores a GSList of the accounts,
635  * for caching purposes. It creates the TnyAccount objects if necessary.
636  * The @list parameter may be NULL, if you just want to fill the cache.
637  */
638 static void
639 get_server_accounts  (TnyAccountStore *self, TnyList *list, TnyAccountType type)
640 {
641         g_return_if_fail (self);
642                 
643         ModestTnyAccountStorePrivate *priv = 
644                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
645                 
646         /* Do nothing if the accounts are already cached: */
647         if (type == TNY_ACCOUNT_TYPE_STORE) {
648                 if (priv->store_accounts)
649                         return;
650         } else if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
651                 if (priv->transport_accounts)
652                         return;
653         }
654         
655         GSList *account_names = NULL, *cursor = NULL;
656         GSList *accounts = NULL;
657
658         /* These are account names, not server_account names */
659         account_names = modest_account_mgr_account_names (priv->account_mgr,FALSE);
660                 
661         for (cursor = account_names; cursor; cursor = cursor->next) {
662                 
663                 gchar *account_name = (gchar*)cursor->data;
664                 
665                 /* we get the server_accounts for enabled accounts */
666                 if (modest_account_mgr_get_enabled(priv->account_mgr, account_name)) {
667                                 
668                         /* Add the account: */
669                         TnyAccount *tny_account = 
670                                 modest_tny_account_new_from_account (priv->account_mgr,
671                                                                      account_name,
672                                                                      type, priv->session,
673                                                                      get_password,
674                                                                      forget_password);
675                         if (tny_account) {
676                                 g_object_set_data (G_OBJECT(tny_account), "account_store",
677                                                    (gpointer)self);
678                                 if (list)
679                                         tny_list_prepend (list, G_OBJECT(tny_account));
680                                 
681                                 accounts = g_slist_append (accounts, tny_account); /* cache it */               
682                         } else
683                                 g_printerr ("modest: failed to create account for %s\n",
684                                             account_name);
685                         }
686         }
687         
688         if (type == TNY_ACCOUNT_TYPE_STORE) {           
689                 /* Also add the Memory card account if it is mounted: */
690                 gboolean mmc_is_mounted = FALSE;
691                 GnomeVFSVolumeMonitor* monitor = 
692                         gnome_vfs_get_volume_monitor();
693                 GList* list_volumes = gnome_vfs_volume_monitor_get_mounted_volumes (monitor);
694                 GList *iter = list_volumes;
695                 while (iter) {
696                         GnomeVFSVolume *volume = (GnomeVFSVolume*)iter->data;
697                         if (volume) {
698                                 if (!mmc_is_mounted) {
699                                         gchar *uri = gnome_vfs_volume_get_activation_uri (volume);
700                                         if (uri && (strcmp (uri, MODEST_MCC1_VOLUMEPATH_URI) == 0)) {
701                                                 mmc_is_mounted = TRUE;
702                                         }
703                                         g_free (uri);
704                                 }
705                                 
706                                 gnome_vfs_volume_unref(volume);
707                         }
708                         
709                         iter = g_list_next (iter);
710                 }
711                 g_list_free (list_volumes);
712                 
713                 if (mmc_is_mounted) {
714                         TnyAccount *tny_account =
715                                 modest_tny_account_new_for_local_folders (priv->account_mgr, 
716                                         priv->session, MODEST_MCC1_VOLUMEPATH);
717                         if (list)
718                                 tny_list_prepend (list, G_OBJECT(tny_account));
719                         accounts = g_slist_append (accounts, tny_account); /* cache it */
720                 }
721         }
722
723         /* And add the connection-specific transport accounts, if any.
724          * Note that these server account instances might never be used 
725          * if their connections are never active: */
726         /* Look at each modest account: */
727         if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
728                 GSList *iter_account_names = account_names;
729                 while (iter_account_names) {
730                         const gchar* account_name = (const gchar*)(iter_account_names->data);
731                         GSList *list_specifics = modest_account_mgr_get_list (priv->account_mgr,
732                                 account_name, 
733                                 MODEST_ACCOUNT_CONNECTION_SPECIFIC_SMTP_LIST,
734                                 MODEST_CONF_VALUE_STRING, FALSE);
735                                 
736                         /* Look at each connection-specific transport account for the 
737                          * modest account: */
738                         GSList *iter = list_specifics;
739                         while (iter) {
740                                 /* const gchar* this_connection_name = (const gchar*)(iter->data); */
741                                 iter = g_slist_next (iter);
742                                 if (iter) {
743                                         const gchar* transport_account_name = (const gchar*)(iter->data);
744                                         if (transport_account_name) {
745                                                 TnyAccount * tny_account = NULL;
746                                                 /* Add the account: */
747                                                 tny_account = modest_tny_account_new_from_server_account_name (
748                                                         priv->account_mgr, transport_account_name);
749                                                 if (tny_account) {
750                                                         g_object_set_data (G_OBJECT(tny_account), "account_store",
751                                                                            (gpointer)self);
752                                                         if (list)
753                                                                 tny_list_prepend (list, G_OBJECT(tny_account));
754                                                         
755                                                         accounts = g_slist_append (accounts, tny_account); /* cache it */               
756                                                 } else
757                                                         g_printerr ("modest: failed to create smtp-specific account for %s\n",
758                                                                     transport_account_name);
759                                         }
760                                 }
761                                 
762                                 iter = g_slist_next (iter);
763                         }
764                         
765                         iter_account_names = g_slist_next (iter_account_names);
766                 }               
767         }
768
769         /* free the account_names */
770         modest_account_mgr_free_account_names (account_names);
771         account_names = NULL;
772
773         /* We also create a per-account local outbox folder (a _store_ account) 
774          * for each _transport_ account. */
775         if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
776                 /* Now would be a good time to create the per-account local outbox folder 
777                  * _store_ accounts corresponding to each transport account: */
778                 if (!priv->store_accounts_outboxes) {
779                         create_per_account_local_outbox_folders (self);
780                 }
781         }
782         
783         /* But we only return the per-account local outbox folder when 
784          * _store_ accounts are requested. */
785         if (type == TNY_ACCOUNT_TYPE_STORE) {
786                 /* Create them if necessary, 
787                  * (which also requires creating the transport accounts, 
788                  * if necessary.) */
789                 if (!priv->store_accounts_outboxes) {
790                         create_per_account_local_outbox_folders (self);
791                 }
792         
793                 /* Also add the local folder pseudo-account: */
794                 TnyAccount *tny_account =
795                         modest_tny_account_new_for_local_folders (priv->account_mgr, 
796                                 priv->session, NULL);
797                                         
798                 /* Add them to the TnyList: */
799                 if (priv->store_accounts_outboxes) {
800                         GSList *iter = NULL;
801                         for (iter = priv->store_accounts_outboxes; iter; iter = g_slist_next (iter)) {
802                                 TnyAccount *outbox_account = (TnyAccount*)iter->data;
803                                 if (list && outbox_account)
804                                         tny_list_prepend (list,  G_OBJECT(outbox_account));
805                                         
806                                 g_object_ref (outbox_account);
807                                 accounts = g_slist_append (accounts, outbox_account);
808                         }
809                 }
810                 
811                 /* Add a merged folder, merging all the per-account outbox folders: */
812                 modest_tny_local_folders_account_add_merged_outbox_folders (
813                         MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (tny_account), priv->store_accounts_outboxes);
814                         
815                 if (priv->store_accounts_outboxes) {
816                         /* We have finished with this temporary list, so free it: */
817                         account_list_free (priv->store_accounts_outboxes);
818                         priv->store_accounts_outboxes = NULL;
819                 }
820                 
821                 if (list)
822                         tny_list_prepend (list, G_OBJECT(tny_account));
823                 accounts = g_slist_append (accounts, tny_account); /* cache it */       
824         }
825                 
826         if (type == TNY_ACCOUNT_TYPE_STORE) {
827                         /* Store the cache: */
828                         priv->store_accounts = accounts;
829         } else if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
830                         /* Store the cache: */
831                         priv->transport_accounts = accounts;
832         }
833 }       
834
835
836 static void
837 modest_tny_account_store_get_accounts  (TnyAccountStore *self, TnyList *list,
838                                         TnyGetAccountsRequestType request_type)
839 {
840         ModestTnyAccountStorePrivate *priv;
841         
842         g_return_if_fail (self);
843         g_return_if_fail (TNY_IS_LIST(list));
844         
845         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
846         
847         if (request_type == TNY_ACCOUNT_STORE_BOTH) {
848                 modest_tny_account_store_get_accounts (self, list,
849                                                        TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
850                 modest_tny_account_store_get_accounts (self, list,
851                                                        TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS);
852                 return;
853         }
854         
855         if (request_type == TNY_ACCOUNT_STORE_STORE_ACCOUNTS)  {
856                 if (!priv->store_accounts)
857                         get_server_accounts (self, list, TNY_ACCOUNT_TYPE_STORE);
858                 else
859                         get_cached_accounts (self, list, TNY_ACCOUNT_TYPE_STORE);
860                 
861         } else if (request_type == TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS) {
862                 if (!priv->transport_accounts)
863                         get_server_accounts (self, list, TNY_ACCOUNT_TYPE_TRANSPORT);
864                 else
865                         get_cached_accounts (self, list, TNY_ACCOUNT_TYPE_TRANSPORT);
866         } else
867                 g_return_if_reached (); /* incorrect req type */
868 }
869
870
871 static const gchar*
872 modest_tny_account_store_get_cache_dir (TnyAccountStore *self)
873 {
874         ModestTnyAccountStorePrivate *priv;
875         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
876         
877         if (!priv->cache_dir)
878                 priv->cache_dir = g_build_filename (g_get_home_dir(), 
879                                                     MODEST_DIR, MODEST_CACHE_DIR, NULL);
880         return priv->cache_dir;
881 }
882
883
884 /*
885  * callers need to unref
886  */
887 static TnyDevice*
888 modest_tny_account_store_get_device (TnyAccountStore *self)
889 {
890         ModestTnyAccountStorePrivate *priv;
891
892         g_return_val_if_fail (self, NULL);
893         
894         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
895
896         if (priv->device)
897                 return g_object_ref (G_OBJECT(priv->device));
898         else
899                 return NULL;
900 }
901
902
903 static TnyAccount*
904 modest_tny_account_store_find_account_by_url (TnyAccountStore *self, const gchar* url_string)
905 {
906         return modest_tny_account_store_get_tny_account_by (MODEST_TNY_ACCOUNT_STORE (self), 
907                                                             MODEST_TNY_ACCOUNT_STORE_QUERY_URL,
908                                                             url_string);
909 }
910
911
912
913 static gboolean
914 modest_tny_account_store_alert (TnyAccountStore *self, TnyAlertType type,
915                                 gboolean question, const GError *error)
916 {
917         /* TODO: It would be nice to know what account caused this error. */
918         
919         g_return_val_if_fail (error, FALSE);
920
921         if ((error->domain != TNY_ACCOUNT_ERROR) 
922                 && (error->domain != TNY_ACCOUNT_STORE_ERROR)) {
923                 g_warning("%s: Unexpected error domain: != TNY_ACCOUNT_ERROR: %d, message=%s", 
924                         __FUNCTION__, error->domain, error->message); 
925                 return FALSE;
926         }
927         
928         /* printf("DEBUG: %s: error->message=%s\n", __FUNCTION__, error->message); */
929         
930
931         /* const gchar *prompt = NULL; */
932         gchar *prompt = NULL;
933         switch (error->code) {
934                 case TNY_ACCOUNT_ERROR_TRY_CONNECT:
935                 /* The tinymail camel implementation just sends us this for almost 
936                  * everything, so we have to guess at the cause.
937                  * It could be a wrong password, or inability to resolve a hostname, 
938                  * or lack of network, or incorrect authentication method, or something entirely different: */
939                 /* TODO: Fix camel to provide specific error codes, and then use the 
940                  * specific dialog messages from Chapter 12 of the UI spec.
941                  */
942                 case TNY_ACCOUNT_STORE_ERROR_UNKNOWN_ALERT: 
943 /*                  g_debug ("%s: Handling GError domain=%d, code=%d, message=%s",  */
944 /*                              __FUNCTION__, error->domain, error->code, error->message); */
945                         
946                         /* TODO: Remove the internal error message for the real release.
947                          * This is just so the testers can give us more information: */
948                         /* prompt = _("Modest account not yet fully configured."); */
949                         prompt = g_strdup_printf(
950                                 "%s\n (Internal error message, often very misleading):\n%s", 
951                                 _("Incorrect Account Settings"), 
952                                 error->message);
953                                 
954                         /* TODO: If we can ever determine that the problem is a wrong password:
955                          * In this case, the UI spec wants us to show a banner, and then 
956                          * open the Account Settings dialog. */
957                         /* Note: Sometimes, the get_password() function seems to be called again 
958                          * when a password is wrong, but sometimes this alert_func is called. */
959                         #if 0
960                         GtkWidget *parent_widget = 
961                                 GTK_WIDGET (
962                                         modest_window_mgr_get_main_window (
963                                                 modest_runtime_get_window_mgr ()));
964                         
965                         hildon_banner_show_information (
966                                 parent_widget,
967                                 NULL /* icon name */,
968                                 _("mcen_ib_username_pw_incorrect") );
969                                 
970                         /* Show the Account Settings window: */
971                         ModestAccountSettingsDialog *dialog = modest_account_settings_dialog_new ();
972                         /* TODO: Get the account somehow. Maybe tinymail should send it with the signal. */
973                         const gchar* modest_account_name = 
974                                 modest_tny_account_get_parent_modest_account_name_for_server_account (account);
975                         g_assert (modest_account_name);
976                         modest_account_settings_dialog_set_account_name (dialog, 
977                                 modest_account_name);
978                         
979                         gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (self));
980                         gtk_dialog_run (GTK_DIALOG (dialog));
981                         gtk_widget_destroy (GTK_WIDGET (dialog));
982                         #endif
983                          
984                         break;
985                         
986                 //TODO: We have started receiving errors of 
987                 //domain=TNY_ACCOUNT_ERROR, code=TNY_ACCOUNT_ERROR_TRY_CONNECT, message="Canceled".
988                 //If this is really a result of us cancelling our own operation then 
989                 //a) this probably shouldn't be an error, and
990                 //b) should have its own error code.
991                 
992                 default:
993                         g_warning ("%s: Unhandled GError code: %d, message=%s", 
994                                 __FUNCTION__, error->code, error->message);
995                         prompt = NULL;
996                 break;
997         }
998         
999         if (!prompt)
1000                 return FALSE;
1001
1002 #ifdef MODEST_PLATFORM_MAEMO
1003         /* The Tinymail documentation says that we should show Yes and No buttons, 
1004          * when it is a question.
1005          * Obviously, we need tinymail to use more specific error codes instead,
1006          * so we know what buttons to show. */
1007          GtkWidget *dialog = NULL;
1008          if (question) {
1009                 dialog = GTK_WIDGET (hildon_note_new_confirmation (NULL, 
1010                         prompt));
1011          } else {
1012                 dialog = GTK_WIDGET (hildon_note_new_information (NULL, 
1013                         prompt));
1014          }
1015 #else
1016
1017         GtkMessageType gtktype = GTK_MESSAGE_ERROR;
1018         switch (type)
1019         {
1020                 case TNY_ALERT_TYPE_INFO:
1021                 gtktype = GTK_MESSAGE_INFO;
1022                 break;
1023                 case TNY_ALERT_TYPE_WARNING:
1024                 gtktype = GTK_MESSAGE_WARNING;
1025                 break;
1026                 case TNY_ALERT_TYPE_ERROR:
1027                 default:
1028                 gtktype = GTK_MESSAGE_ERROR;
1029                 break;
1030         }
1031         
1032         GtkWidget *dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL,
1033                 gtktype, GTK_BUTTONS_YES_NO, prompt);
1034 #endif /* #ifdef MODEST_PLATFORM_MAEMO */
1035
1036         gboolean retval = TRUE;
1037         const int response = gtk_dialog_run (GTK_DIALOG (dialog));
1038         if (question) {
1039                 retval = (response == GTK_RESPONSE_YES) ||
1040                                  (response == GTK_RESPONSE_OK); 
1041         }
1042
1043         gtk_widget_destroy (dialog);
1044         
1045         /* TODO: Don't free this when we no longer strdup the message for testers. */
1046         g_free (prompt);
1047
1048
1049         /* printf("DEBUG: %s: returning %d\n", __FUNCTION__, retval); */
1050         return retval;
1051 }
1052
1053
1054 static void
1055 modest_tny_account_store_init (gpointer g, gpointer iface_data)
1056 {
1057         TnyAccountStoreIface *klass;
1058
1059         g_return_if_fail (g);
1060
1061         klass = (TnyAccountStoreIface *)g;
1062
1063         klass->get_accounts_func =
1064                 modest_tny_account_store_get_accounts;
1065         klass->get_cache_dir_func =
1066                 modest_tny_account_store_get_cache_dir;
1067         klass->get_device_func =
1068                 modest_tny_account_store_get_device;
1069         klass->alert_func =
1070                 modest_tny_account_store_alert;
1071         klass->find_account_func =
1072                 modest_tny_account_store_find_account_by_url;
1073 }
1074
1075 void
1076 modest_tny_account_store_set_get_pass_func (ModestTnyAccountStore *self,
1077                                             ModestTnyGetPassFunc func)
1078 {
1079         /* not implemented, we use signals */
1080         g_printerr ("modest: set_get_pass_func not implemented\n");
1081 }
1082
1083 TnySessionCamel*
1084 modest_tny_account_store_get_session  (TnyAccountStore *self)
1085 {
1086         g_return_val_if_fail (self, NULL);
1087         return MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self)->session;
1088 }
1089
1090
1091 TnyAccount*
1092 modest_tny_account_store_get_tny_account_by (ModestTnyAccountStore *self, 
1093                                              ModestTnyAccountStoreQueryType type,
1094                                              const gchar *str)
1095 {
1096         TnyAccount *account = NULL;
1097         ModestTnyAccountStorePrivate *priv;     
1098         GSList *cursor;
1099         const gchar *val = NULL;
1100
1101         g_return_val_if_fail (self, NULL);
1102         g_return_val_if_fail (str, NULL);
1103         
1104         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1105
1106         /* Search in store accounts */
1107         for (cursor = priv->store_accounts; cursor ; cursor = cursor->next) {
1108                 switch (type) {
1109                 case MODEST_TNY_ACCOUNT_STORE_QUERY_ID:
1110                         val = tny_account_get_id (TNY_ACCOUNT(cursor->data));
1111                         break;
1112                 case MODEST_TNY_ACCOUNT_STORE_QUERY_NAME:
1113                         val = modest_tny_account_get_parent_modest_account_name_for_server_account (TNY_ACCOUNT(cursor->data));
1114                         break;
1115                 case MODEST_TNY_ACCOUNT_STORE_QUERY_URL:
1116                         val = tny_account_get_url_string (TNY_ACCOUNT(cursor->data));
1117                         break;
1118                 }
1119                 
1120                 if (type == MODEST_TNY_ACCOUNT_STORE_QUERY_URL && 
1121                     tny_account_matches_url_string (TNY_ACCOUNT(cursor->data), val)) {
1122                         account = TNY_ACCOUNT (cursor->data);
1123                         goto end;
1124                 } else {
1125                         if (strcmp (val, str) == 0) {
1126                                 account = TNY_ACCOUNT(cursor->data);
1127                                 goto end;
1128                         }
1129                 }
1130         }
1131                 
1132         /* if we already found something, no need to search the transport accounts */
1133         for (cursor = priv->transport_accounts; !account && cursor ; cursor = cursor->next) {
1134                 switch (type) {
1135                 case MODEST_TNY_ACCOUNT_STORE_QUERY_ID:
1136                         val = tny_account_get_id (TNY_ACCOUNT(cursor->data));
1137                         break;
1138                 case MODEST_TNY_ACCOUNT_STORE_QUERY_NAME:
1139                         val = tny_account_get_name (TNY_ACCOUNT(cursor->data));
1140                         break;
1141                 case MODEST_TNY_ACCOUNT_STORE_QUERY_URL:
1142                         val = tny_account_get_url_string (TNY_ACCOUNT(cursor->data));
1143                         break;
1144                 }
1145                 
1146                 if (type == MODEST_TNY_ACCOUNT_STORE_QUERY_URL && 
1147                     tny_account_matches_url_string (TNY_ACCOUNT(cursor->data), val)) {
1148                         account = TNY_ACCOUNT (cursor->data);
1149                         goto end;
1150                 } else {
1151                         if (strcmp (val, str) == 0) {
1152                                 account = TNY_ACCOUNT(cursor->data);
1153                                 goto end;
1154                         }
1155                 }
1156         }
1157  end:
1158         if (account)
1159                 g_object_ref (G_OBJECT(account));
1160         
1161         return account;
1162 }
1163
1164 TnyAccount*
1165 modest_tny_account_store_get_server_account (ModestTnyAccountStore *self,
1166                                                      const gchar *account_name,
1167                                                      TnyAccountType type)
1168 {
1169         TnyAccount *account = NULL;
1170         gchar *id = NULL;
1171         ModestTnyAccountStorePrivate *priv;     
1172
1173         g_return_val_if_fail (self, NULL);
1174         g_return_val_if_fail (account_name, NULL);
1175         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || type == TNY_ACCOUNT_TYPE_TRANSPORT,
1176                               NULL);
1177         
1178         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1179
1180         /* Special case for the local account */
1181         if (!strcmp (account_name, MODEST_LOCAL_FOLDERS_ACCOUNT_ID)) {
1182                 if(type == TNY_ACCOUNT_TYPE_STORE)
1183                         id = g_strdup (MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
1184                 else {
1185                         /* The local folders modest account has no transport server account. */
1186                         return NULL;
1187                 }
1188         } else {
1189                 ModestAccountData *account_data;
1190                 account_data = modest_account_mgr_get_account_data (priv->account_mgr, account_name);
1191                 if (!account_data) {
1192                         g_printerr ("modest: %s: cannot get account data for account '%s'\n", __FUNCTION__,
1193                                     account_name);
1194                         return NULL;
1195                 }
1196
1197                 if (type == TNY_ACCOUNT_TYPE_STORE && account_data->store_account)
1198                         id = g_strdup (account_data->store_account->account_name);
1199                 else if (account_data->transport_account)
1200                         id = g_strdup (account_data->transport_account->account_name);
1201
1202                 modest_account_mgr_free_account_data (priv->account_mgr, account_data);
1203         }
1204
1205         if (!id)
1206                 g_printerr ("modest: could not get an id for account %s\n",
1207                             account_name);
1208         else    
1209                 account = modest_tny_account_store_get_tny_account_by (self, MODEST_TNY_ACCOUNT_STORE_QUERY_ID, id);
1210
1211         if (!account)
1212                 g_printerr ("modest: could not get tny %s account for %s (id=%s)\n",
1213                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
1214                             account_name, id ? id : "<none>");
1215
1216         return account; 
1217 }
1218
1219 static TnyAccount*
1220 get_smtp_specific_transport_account_for_open_connection (ModestTnyAccountStore *self,
1221                                                          const gchar *account_name)
1222 {
1223         /* Get the current connection: */
1224         TnyDevice *device = modest_runtime_get_device ();
1225         
1226         if (!tny_device_is_online (device))
1227                 return NULL;
1228
1229 #ifdef MODEST_PLATFORM_MAEMO
1230         g_assert (TNY_IS_MAEMO_CONIC_DEVICE (device));
1231         TnyMaemoConicDevice *maemo_device = TNY_MAEMO_CONIC_DEVICE (device);    
1232         const gchar* iap_id = tny_maemo_conic_device_get_current_iap_id (maemo_device);
1233         /* printf ("DEBUG: %s: iap_id=%s\n", __FUNCTION__, iap_id); */
1234         if (!iap_id)
1235                 return NULL;
1236                 
1237         ConIcIap* connection = tny_maemo_conic_device_get_iap (maemo_device, iap_id);
1238         if (!connection)
1239                 return NULL;
1240                 
1241         const gchar *connection_name = con_ic_iap_get_name (connection);
1242         /* printf ("DEBUG: %s: connection_name=%s\n", __FUNCTION__, connection_name); */
1243         if (!connection_name)
1244                 return NULL;
1245         
1246         /*  Get the connection-specific transport acccount, if any: */
1247         ModestAccountMgr *account_manager = modest_runtime_get_account_mgr ();
1248         gchar* server_account_name = modest_account_mgr_get_connection_specific_smtp (account_manager, 
1249                 account_name, connection_name);
1250
1251         /* printf ("DEBUG: %s: server_account_name=%s\n", __FUNCTION__, server_account_name); */
1252         if (!server_account_name) {
1253                 return NULL; /* No connection-specific SMTP server was specified for this connection. */
1254         }
1255                 
1256         TnyAccount* account = modest_tny_account_store_get_tny_account_by (self, 
1257                                                                            MODEST_TNY_ACCOUNT_STORE_QUERY_ID, 
1258                                                                            server_account_name);
1259
1260         /* printf ("DEBUG: %s: account=%p\n", __FUNCTION__, account); */
1261         g_free (server_account_name);   
1262
1263         /* Unref the get()ed object, as required by the tny_maemo_conic_device_get_iap() documentation. */
1264         g_object_unref (connection);
1265         
1266         return account;
1267 #else
1268         return NULL; /* TODO: Implement this for GNOME, instead of just Maemo? */
1269 #endif /* MODEST_PLATFORM_MAEMO */
1270 }
1271
1272                                                                  
1273 TnyAccount*
1274 modest_tny_account_store_get_transport_account_for_open_connection (ModestTnyAccountStore *self,
1275                                                                     const gchar *account_name)
1276 {
1277         /*  Get the connection-specific transport acccount, if any: */
1278         TnyAccount *account = get_smtp_specific_transport_account_for_open_connection (self, account_name);
1279                         
1280         /* If there is no connection-specific transport account (the common case), 
1281          * just get the regular transport account: */
1282         if (!account) {
1283                 /* printf("DEBUG: %s: using regular transport account for account %s.\n", __FUNCTION__, account_name); */
1284
1285                 /* The special local folders don't have transport accounts. */
1286                 if (strcmp (account_name, MODEST_LOCAL_FOLDERS_ACCOUNT_ID) == 0)
1287                         account = NULL;
1288                 else
1289                         account = modest_tny_account_store_get_server_account (self, account_name, 
1290                                                      TNY_ACCOUNT_TYPE_TRANSPORT);
1291         }
1292                              
1293         return account;
1294 }
1295
1296 gboolean
1297 modest_tny_account_is_virtual_local_folders (TnyAccount *self)
1298 {
1299         /* We should make this more sophisticated if we ever use ModestTnyLocalFoldersAccount 
1300          * for anything else. */
1301         return MODEST_IS_TNY_LOCAL_FOLDERS_ACCOUNT (self);
1302 }
1303
1304 TnyAccount*
1305 modest_tny_account_store_get_local_folders_account (TnyAccountStore *self)
1306 {
1307         TnyAccount *account = NULL;
1308         ModestTnyAccountStorePrivate *priv;     
1309         GSList *cursor;
1310
1311         g_return_val_if_fail (self, NULL);
1312         
1313         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1314
1315         for (cursor = priv->store_accounts; cursor ; cursor = cursor->next) {
1316                 TnyAccount *this_account = TNY_ACCOUNT(cursor->data);
1317                 if (modest_tny_account_is_virtual_local_folders (this_account)) {
1318                                  account = this_account;
1319                                  break;
1320                 }
1321         }
1322
1323         if (account)
1324                 g_object_ref (G_OBJECT(account));
1325         
1326         return account;
1327 }