* do lazy initialization of the server accounts; this avoids
[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_HAVE_HILDON0_WIDGETS
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  * It also calls forget_password() before calling this,
385  * so that we clear wrong passwords out of our account settings.
386  * Note that TnyAccount here will be the server account. */
387 static gchar*
388 get_password (TnyAccount *account, const gchar * prompt_not_used, gboolean *cancel)
389 {
390         /* Initialize the output parameter: */
391           
392         g_return_val_if_fail (account, NULL);
393           
394         const gchar *key;
395         const TnyAccountStore *account_store;
396         ModestTnyAccountStore *self;
397         ModestTnyAccountStorePrivate *priv;
398         gchar *username = NULL;
399         gchar *pwd = NULL;
400         gpointer pwd_ptr;
401         gboolean already_asked;
402
403         if (cancel)
404                 *cancel = FALSE;
405                 
406         key           = tny_account_get_id (account);
407         account_store = TNY_ACCOUNT_STORE(get_account_store_for_account (account));
408
409         if (!key || !account_store) {
410                 g_warning ("BUG: could not retrieve account_store for account %s",
411                            key ? key : "<NULL>");
412                 if (cancel)
413                         *cancel = TRUE;
414                 
415                 return NULL;
416         }
417
418         self = MODEST_TNY_ACCOUNT_STORE (account_store);
419         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
420         
421         /* This hash map stores passwords, including passwords that are not stored in gconf. */
422         /* is it in the hash? if it's already there, it must be wrong... */
423         pwd_ptr = (gpointer)&pwd; /* pwd_ptr so the compiler does not complained about
424                                    * type-punned ptrs...*/
425         already_asked = priv->password_hash && 
426                                 g_hash_table_lookup_extended (priv->password_hash,
427                                                       key,
428                                                       NULL,
429                                                       (gpointer*)&pwd_ptr);
430
431         /* if the password is not already there, try ModestConf */
432         if (!already_asked) {
433                 pwd  = modest_account_mgr_get_string (priv->account_mgr,
434                                                       key, MODEST_ACCOUNT_PASSWORD, TRUE);
435                 g_hash_table_insert (priv->password_hash, g_strdup (key), g_strdup (pwd));
436         }
437
438         /* if it was already asked, it must have been wrong, so ask again */
439         /* TODO: However, when we supply a wrong password to tinymail, 
440          * it seems to (at least sometimes) call our alert_func() instead of 
441          * asking for the password again.
442          */
443         if (already_asked || !pwd || strlen(pwd) == 0) {
444                 /* we don't have it yet. Get the password from the user */
445                 const gchar* account_id = tny_account_get_id (account);
446                 gboolean remember = FALSE;
447                 pwd = NULL;
448                 
449                 g_signal_emit (G_OBJECT(self), signals[PASSWORD_REQUESTED_SIGNAL], 0,
450                                account_id, /* server_account_name */
451                                &username, &pwd, cancel, &remember);
452                 
453                 if (!*cancel) {
454                         /* The password will be returned as the result,
455                          * but we need to tell tinymail about the username too: */
456                         tny_account_set_user (account, username);
457                         
458                         if (remember) {
459                                 printf ("%s: Storing username=%s, password=%s\n", 
460                                         __FUNCTION__, username, pwd);
461                                 modest_account_mgr_set_string (priv->account_mgr,key,
462                                                                MODEST_ACCOUNT_USERNAME,
463                                                                username, TRUE);
464                                 modest_account_mgr_set_string (priv->account_mgr,key,
465                                                                MODEST_ACCOUNT_PASSWORD,
466                                                                pwd, TRUE);
467                         }
468                         /* We need to dup the string even knowing that
469                            it's already a dup of the contents of an
470                            entry, because it if it's wrong, then camel
471                            will free it */
472                         g_hash_table_insert (priv->password_hash, g_strdup (key), g_strdup(pwd));
473                 } else {
474                         g_hash_table_remove (priv->password_hash, key);
475                         
476                         g_free (pwd);
477                         pwd = NULL;
478                 }
479
480                 g_free (username);
481                 username = NULL;
482         } else
483                 *cancel = FALSE;
484  
485     /* printf("  DEBUG: %s: returning %s\n", __FUNCTION__, pwd); */
486         
487         return pwd;
488 }
489
490 /* tinymail calls this if the connection failed due to an incorrect password.
491  * And it seems to call this for any general connection failure. */
492 static void
493 forget_password (TnyAccount *account)
494 {
495         printf ("DEBUG: %s\n", __FUNCTION__);
496         ModestTnyAccountStore *self;
497         ModestTnyAccountStorePrivate *priv;
498         const TnyAccountStore *account_store;
499         gchar *pwd;
500         const gchar *key;
501         
502         account_store = TNY_ACCOUNT_STORE(get_account_store_for_account (account));
503         self = MODEST_TNY_ACCOUNT_STORE (account_store);
504         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
505         key  = tny_account_get_id (account);
506
507         /* Do not remove the key, this will allow us to detect that we
508            have already asked for it at least once */
509         pwd = g_hash_table_lookup (priv->password_hash, key);
510         if (pwd) {
511                 memset (pwd, 0, strlen (pwd));
512                 g_hash_table_insert (priv->password_hash, g_strdup (key), NULL);
513         }
514
515         /* Remove from configuration system */
516         modest_account_mgr_unset (priv->account_mgr,
517                                   key, MODEST_ACCOUNT_PASSWORD, TRUE);
518 }
519
520
521 static void
522 modest_tny_account_store_finalize (GObject *obj)
523 {
524         ModestTnyAccountStore *self        = MODEST_TNY_ACCOUNT_STORE(obj);
525         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
526         
527         //gboolean debug = modest_runtime_get_debug_flags() & MODEST_RUNTIME_DEBUG_DEBUG_OBJECTS;
528
529         g_free (priv->cache_dir);
530         priv->cache_dir = NULL;
531         
532         if (priv->password_hash) {
533                 g_hash_table_destroy (priv->password_hash);
534                 priv->password_hash = NULL;
535         }
536
537         if (priv->account_mgr) {
538                 g_object_unref (G_OBJECT(priv->account_mgr));
539                 priv->account_mgr = NULL;
540         }
541
542         if (priv->device) {
543                 g_object_unref (G_OBJECT(priv->device));
544                 priv->device = NULL;
545         }
546
547         /* this includes the local folder */
548         account_list_free (priv->store_accounts);
549         priv->store_accounts = NULL;
550         
551         account_list_free (priv->transport_accounts);
552         priv->transport_accounts = NULL;
553
554         if (priv->session) {
555                 camel_object_unref (CAMEL_OBJECT(priv->session));
556                 priv->session = NULL;
557         }
558         
559         G_OBJECT_CLASS(parent_class)->finalize (obj);
560 }
561
562
563 ModestTnyAccountStore*
564 modest_tny_account_store_new (ModestAccountMgr *account_mgr, TnyDevice *device) {
565
566         GObject *obj;
567         ModestTnyAccountStorePrivate *priv;
568 //      TnyList *list; 
569         
570         g_return_val_if_fail (account_mgr, NULL);
571         g_return_val_if_fail (device, NULL);
572
573         obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_ACCOUNT_STORE, NULL));
574         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
575
576         priv->account_mgr = g_object_ref (G_OBJECT(account_mgr));
577         priv->device = g_object_ref (device);
578         
579         priv->session = tny_session_camel_new (TNY_ACCOUNT_STORE(obj));
580         
581         tny_session_camel_set_ui_locker (priv->session,  tny_gtk_lockable_new ());
582         /* FIXME: unref this in the end? */
583         tny_session_camel_set_async_connecting (priv->session, TRUE);
584         
585         /* force a cache fill... ugly */
586         /* list = TNY_LIST(tny_simple_list_new()); */
587 /*      tny_account_store_get_accounts (TNY_ACCOUNT_STORE(obj), list, */
588 /*                                      TNY_ACCOUNT_STORE_BOTH); */
589 /*      g_object_unref(list); */
590         
591         /* Connect signals */
592         g_signal_connect (G_OBJECT(account_mgr), "account_changed",
593                                        G_CALLBACK (on_account_changed), obj);
594         g_signal_connect (G_OBJECT(account_mgr), "account_removed",
595                                        G_CALLBACK (on_account_removed), obj);
596
597         return MODEST_TNY_ACCOUNT_STORE(obj);
598 }
599
600 /** Fill the TnyList from the appropriate cached GSList of accounts. */
601 static void
602 get_cached_accounts (TnyAccountStore *self, TnyList *list, TnyAccountType type)
603 {
604         ModestTnyAccountStorePrivate *priv;
605         GSList                       *accounts, *cursor;
606         
607         priv     = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
608         accounts = (type == TNY_ACCOUNT_TYPE_STORE ? priv->store_accounts : priv->transport_accounts);
609
610         cursor = accounts;
611         while (cursor) {
612                 if (cursor->data) {
613                         GObject *object = G_OBJECT(cursor->data);
614                         tny_list_prepend (list, object);
615                 }
616                         
617                 cursor = cursor->next;
618         }
619 }
620
621 static void
622 create_per_account_local_outbox_folders (TnyAccountStore *self)
623 {
624         g_return_if_fail (self);
625         
626         ModestTnyAccountStorePrivate *priv = 
627                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
628         
629         /* printf("DEBUG: %s: priv->store_accounts_outboxes = %p\n", __FUNCTION__, priv->store_accounts_outboxes); */
630         
631         GSList *accounts = NULL;
632         
633         GSList *account_names  = modest_account_mgr_account_names (priv->account_mgr, 
634                 TRUE /* including disabled accounts */);
635         
636         GSList *iter = NULL;
637         for (iter = account_names; iter; iter = g_slist_next (iter)) {
638                 
639                 const gchar* account_name = (const gchar*)iter->data;
640                 
641                 /* Create a per-account local outbox folder (a _store_ account) 
642                  * for each _transport_ account: */
643                 TnyAccount *tny_account_outbox =
644                         modest_tny_account_new_for_per_account_local_outbox_folder (
645                                 priv->account_mgr, account_name, priv->session);
646                                 
647                 accounts = g_slist_append (accounts, tny_account_outbox); /* cache it */
648         };
649
650         modest_account_mgr_free_account_names (account_names);
651         account_names = NULL;
652         
653         priv->store_accounts_outboxes = accounts;
654 }
655
656 /* This function fills the TnyList, and also stores a GSList of the accounts,
657  * for caching purposes. It creates the TnyAccount objects if necessary.
658  * The @list parameter may be NULL, if you just want to fill the cache.
659  */
660 static void
661 get_server_accounts  (TnyAccountStore *self, TnyList *list, TnyAccountType type)
662 {
663         g_return_if_fail (self);
664                 
665         ModestTnyAccountStorePrivate *priv = 
666                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
667                 
668         /* Do nothing if the accounts are already cached: */
669         if (type == TNY_ACCOUNT_TYPE_STORE) {
670                 if (priv->store_accounts)
671                         return;
672         } else if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
673                 if (priv->transport_accounts)
674                         return;
675         }
676         
677         GSList *account_names = NULL, *cursor = NULL;
678         GSList *accounts = NULL;
679
680         /* These are account names, not server_account names */
681         account_names = modest_account_mgr_account_names (priv->account_mgr,FALSE);
682                 
683         for (cursor = account_names; cursor; cursor = cursor->next) {
684                 
685                 gchar *account_name = (gchar*)cursor->data;
686                 
687                 /* we get the server_accounts for enabled accounts */
688                 if (modest_account_mgr_get_enabled(priv->account_mgr, account_name)) {
689                                 
690                         /* Add the account: */
691                         TnyAccount *tny_account = 
692                                 modest_tny_account_new_from_account (priv->account_mgr,
693                                                                      account_name,
694                                                                      type, priv->session,
695                                                                      get_password,
696                                                                      forget_password);
697                         if (tny_account) {
698                                 g_object_set_data (G_OBJECT(tny_account), "account_store",
699                                                    (gpointer)self);
700                                 if (list)
701                                         tny_list_prepend (list, G_OBJECT(tny_account));
702                                 
703                                 accounts = g_slist_append (accounts, tny_account); /* cache it */               
704                         } else
705                                 g_printerr ("modest: failed to create account for %s\n",
706                                             account_name);
707                         }
708         }
709         
710         if (type == TNY_ACCOUNT_TYPE_STORE) {           
711                 /* Also add the Memory card account if it is mounted: */
712                 gboolean mmc_is_mounted = FALSE;
713                 GnomeVFSVolumeMonitor* monitor = 
714                         gnome_vfs_get_volume_monitor();
715                 GList* list_volumes = gnome_vfs_volume_monitor_get_mounted_volumes (monitor);
716                 GList *iter = list_volumes;
717                 while (iter) {
718                         GnomeVFSVolume *volume = (GnomeVFSVolume*)iter->data;
719                         if (volume) {
720                                 if (!mmc_is_mounted) {
721                                         gchar *uri = gnome_vfs_volume_get_activation_uri (volume);
722                                         if (uri && (strcmp (uri, MODEST_MCC1_VOLUMEPATH_URI) == 0)) {
723                                                 mmc_is_mounted = TRUE;
724                                         }
725                                         g_free (uri);
726                                 }
727                                 
728                                 gnome_vfs_volume_unref(volume);
729                         }
730                         
731                         iter = g_list_next (iter);
732                 }
733                 g_list_free (list_volumes);
734                 
735                 if (mmc_is_mounted) {
736                         TnyAccount *tny_account =
737                                 modest_tny_account_new_for_local_folders (priv->account_mgr, 
738                                         priv->session, MODEST_MCC1_VOLUMEPATH);
739                         if (list)
740                                 tny_list_prepend (list, G_OBJECT(tny_account));
741                         accounts = g_slist_append (accounts, tny_account); /* cache it */
742                 }
743         }
744
745         /* And add the connection-specific transport accounts, if any.
746          * Note that these server account instances might never be used 
747          * if their connections are never active: */
748         /* Look at each modest account: */
749         if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
750                 GSList *iter_account_names = account_names;
751                 while (iter_account_names) {
752                         const gchar* account_name = (const gchar*)(iter_account_names->data);
753                         GSList *list_specifics = modest_account_mgr_get_list (priv->account_mgr,
754                                 account_name, 
755                                 MODEST_ACCOUNT_CONNECTION_SPECIFIC_SMTP_LIST,
756                                 MODEST_CONF_VALUE_STRING, FALSE);
757                                 
758                         /* Look at each connection-specific transport account for the 
759                          * modest account: */
760                         GSList *iter = list_specifics;
761                         while (iter) {
762                                 /* const gchar* this_connection_name = (const gchar*)(iter->data); */
763                                 iter = g_slist_next (iter);
764                                 if (iter) {
765                                         const gchar* transport_account_name = (const gchar*)(iter->data);
766                                         if (transport_account_name) {
767                                                 TnyAccount * tny_account = NULL;
768                                                 /* Add the account: */
769                                                 tny_account = modest_tny_account_new_from_server_account_name (
770                                                         priv->account_mgr, transport_account_name);
771                                                 if (tny_account) {
772                                                         g_object_set_data (G_OBJECT(tny_account), "account_store",
773                                                                            (gpointer)self);
774                                                         if (list)
775                                                                 tny_list_prepend (list, G_OBJECT(tny_account));
776                                                         
777                                                         accounts = g_slist_append (accounts, tny_account); /* cache it */               
778                                                 } else
779                                                         g_printerr ("modest: failed to create smtp-specific account for %s\n",
780                                                                     transport_account_name);
781                                         }
782                                 }
783                                 
784                                 iter = g_slist_next (iter);
785                         }
786                         
787                         iter_account_names = g_slist_next (iter_account_names);
788                 }               
789         }
790
791         /* free the account_names */
792         modest_account_mgr_free_account_names (account_names);
793         account_names = NULL;
794
795         /* We also create a per-account local outbox folder (a _store_ account) 
796          * for each _transport_ account. */
797         if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
798                 /* Now would be a good time to create the per-account local outbox folder 
799                  * _store_ accounts corresponding to each transport account: */
800                 if (!priv->store_accounts_outboxes) {
801                         create_per_account_local_outbox_folders (self);
802                 }
803         }
804         
805         /* But we only return the per-account local outbox folder when 
806          * _store_ accounts are requested. */
807         if (type == TNY_ACCOUNT_TYPE_STORE) {
808                 /* Create them if necessary, 
809                  * (which also requires creating the transport accounts, 
810                  * if necessary.) */
811                 if (!priv->store_accounts_outboxes) {
812                         create_per_account_local_outbox_folders (self);
813                 }
814         
815                 /* Also add the local folder pseudo-account: */
816                 TnyAccount *tny_account =
817                         modest_tny_account_new_for_local_folders (priv->account_mgr, 
818                                 priv->session, NULL);
819                                         
820                 /* Add them to the TnyList: */
821                 if (priv->store_accounts_outboxes) {
822                         GSList *iter = NULL;
823                         for (iter = priv->store_accounts_outboxes; iter; iter = g_slist_next (iter)) {
824                                 TnyAccount *outbox_account = (TnyAccount*)iter->data;
825                                 if (list && outbox_account)
826                                         tny_list_prepend (list,  G_OBJECT(outbox_account));
827                                         
828                                 g_object_ref (outbox_account);
829                                 accounts = g_slist_append (accounts, outbox_account);
830                         }
831                 }
832                 
833                 /* Add a merged folder, merging all the per-account outbox folders: */
834                 modest_tny_local_folders_account_add_merged_outbox_folders (
835                         MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (tny_account), priv->store_accounts_outboxes);
836                         
837                 if (priv->store_accounts_outboxes) {
838                         /* We have finished with this temporary list, so free it: */
839                         account_list_free (priv->store_accounts_outboxes);
840                         priv->store_accounts_outboxes = NULL;
841                 }
842                 
843                 if (list)
844                         tny_list_prepend (list, G_OBJECT(tny_account));
845                 accounts = g_slist_append (accounts, tny_account); /* cache it */       
846         }
847                 
848         if (type == TNY_ACCOUNT_TYPE_STORE) {
849                         /* Store the cache: */
850                         priv->store_accounts = accounts;
851         } else if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
852                         /* Store the cache: */
853                         priv->transport_accounts = accounts;
854         }
855 }       
856
857
858 static void
859 modest_tny_account_store_get_accounts  (TnyAccountStore *self, TnyList *list,
860                                         TnyGetAccountsRequestType request_type)
861 {
862         ModestTnyAccountStorePrivate *priv;
863         
864         g_return_if_fail (self);
865         g_return_if_fail (TNY_IS_LIST(list));
866         
867         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
868         
869         if (request_type == TNY_ACCOUNT_STORE_BOTH) {
870                 modest_tny_account_store_get_accounts (self, list,
871                                                        TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
872                 modest_tny_account_store_get_accounts (self, list,
873                                                        TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS);
874                 return;
875         }
876         
877         if (request_type == TNY_ACCOUNT_STORE_STORE_ACCOUNTS)  {
878                 if (!priv->store_accounts)
879                         get_server_accounts (self, list, TNY_ACCOUNT_TYPE_STORE);
880                 else
881                         get_cached_accounts (self, list, TNY_ACCOUNT_TYPE_STORE);
882                 
883         } else if (request_type == TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS) {
884                 if (!priv->transport_accounts)
885                         get_server_accounts (self, list, TNY_ACCOUNT_TYPE_TRANSPORT);
886                 else
887                         get_cached_accounts (self, list, TNY_ACCOUNT_TYPE_TRANSPORT);
888         } else
889                 g_return_if_reached (); /* incorrect req type */
890 }
891
892
893 static const gchar*
894 modest_tny_account_store_get_cache_dir (TnyAccountStore *self)
895 {
896         ModestTnyAccountStorePrivate *priv;
897         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
898         
899         if (!priv->cache_dir)
900                 priv->cache_dir = g_build_filename (g_get_home_dir(), 
901                                                     MODEST_DIR, MODEST_CACHE_DIR, NULL);
902         return priv->cache_dir;
903 }
904
905
906 /*
907  * callers need to unref
908  */
909 static TnyDevice*
910 modest_tny_account_store_get_device (TnyAccountStore *self)
911 {
912         ModestTnyAccountStorePrivate *priv;
913
914         g_return_val_if_fail (self, NULL);
915         
916         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
917
918         if (priv->device)
919                 return g_object_ref (G_OBJECT(priv->device));
920         else
921                 return NULL;
922 }
923
924
925 static TnyAccount*
926 modest_tny_account_store_find_account_by_url (TnyAccountStore *self, const gchar* url_string)
927 {
928         return modest_tny_account_store_get_tny_account_by (MODEST_TNY_ACCOUNT_STORE (self), 
929                                                             MODEST_TNY_ACCOUNT_STORE_QUERY_URL,
930                                                             url_string);
931 }
932
933
934
935 static gboolean
936 modest_tny_account_store_alert (TnyAccountStore *self, TnyAlertType type,
937                                 gboolean question, const GError *error)
938 {
939         /* TODO: It would be nice to know what account caused this error. */
940         
941         g_return_val_if_fail (error, FALSE);
942
943         if ((error->domain != TNY_ACCOUNT_ERROR) 
944                 && (error->domain != TNY_ACCOUNT_STORE_ERROR)) {
945                 g_warning("%s: Unexpected error domain: != TNY_ACCOUNT_ERROR: %d, message=%s", 
946                         __FUNCTION__, error->domain, error->message); 
947                 return FALSE;
948         }
949         
950         /* printf("DEBUG: %s: error->message=%s\n", __FUNCTION__, error->message); */
951         
952
953         /* const gchar *prompt = NULL; */
954         gchar *prompt = NULL;
955         switch (error->code) {
956                 case TNY_ACCOUNT_ERROR_TRY_CONNECT:
957                 /* The tinymail camel implementation just sends us this for almost 
958                  * everything, so we have to guess at the cause.
959                  * It could be a wrong password, or inability to resolve a hostname, 
960                  * or lack of network, or incorrect authentication method, or something entirely different: */
961                 /* TODO: Fix camel to provide specific error codes, and then use the 
962                  * specific dialog messages from Chapter 12 of the UI spec.
963                  */
964                 case TNY_ACCOUNT_STORE_ERROR_UNKNOWN_ALERT: 
965 /*                  g_debug ("%s: Handling GError domain=%d, code=%d, message=%s",  */
966 /*                              __FUNCTION__, error->domain, error->code, error->message); */
967                         
968                         /* TODO: Remove the internal error message for the real release.
969                          * This is just so the testers can give us more information: */
970                         /* prompt = _("Modest account not yet fully configured."); */
971                         prompt = g_strdup_printf(
972                                 "%s\n (Internal error message, often very misleading):\n%s", 
973                                 _("Incorrect Account Settings"), 
974                                 error->message);
975                                 
976                         /* TODO: If we can ever determine that the problem is a wrong password:
977                          * In this case, the UI spec wants us to show a banner, and then 
978                          * open the Account Settings dialog. */
979                         /* Note: Sometimes, the get_password() function seems to be called again 
980                          * when a password is wrong, but sometimes this alert_func is called. */
981                         #if 0
982                         GtkWidget *parent_widget = 
983                                 GTK_WIDGET (
984                                         modest_window_mgr_get_main_window (
985                                                 modest_runtime_get_window_mgr ()));
986                         
987                         hildon_banner_show_information (
988                                 parent_widget,
989                                 NULL /* icon name */,
990                                 _("mcen_ib_username_pw_incorrect") );
991                                 
992                         /* Show the Account Settings window: */
993                         ModestAccountSettingsDialog *dialog = modest_account_settings_dialog_new ();
994                         /* TODO: Get the account somehow. Maybe tinymail should send it with the signal. */
995                         const gchar* modest_account_name = 
996                                 modest_tny_account_get_parent_modest_account_name_for_server_account (account);
997                         g_assert (modest_account_name);
998                         modest_account_settings_dialog_set_account_name (dialog, 
999                                 modest_account_name);
1000                         
1001                         gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (self));
1002                         gtk_dialog_run (GTK_DIALOG (dialog));
1003                         gtk_widget_destroy (GTK_WIDGET (dialog));
1004                         #endif
1005                          
1006                         break;
1007                         
1008                 //TODO: We have started receiving errors of 
1009                 //domain=TNY_ACCOUNT_ERROR, code=TNY_ACCOUNT_ERROR_TRY_CONNECT, message="Canceled".
1010                 //If this is really a result of us cancelling our own operation then 
1011                 //a) this probably shouldn't be an error, and
1012                 //b) should have its own error code.
1013                 
1014                 default:
1015                         g_warning ("%s: Unhandled GError code: %d, message=%s", 
1016                                 __FUNCTION__, error->code, error->message);
1017                         prompt = NULL;
1018                 break;
1019         }
1020         
1021         if (!prompt)
1022                 return FALSE;
1023
1024 #ifdef MODEST_PLATFORM_MAEMO
1025         /* The Tinymail documentation says that we should show Yes and No buttons, 
1026          * when it is a question.
1027          * Obviously, we need tinymail to use more specific error codes instead,
1028          * so we know what buttons to show. */
1029          GtkWidget *dialog = NULL;
1030          if (question) {
1031                 dialog = GTK_WIDGET (hildon_note_new_confirmation (NULL, 
1032                         prompt));
1033          } else {
1034                 dialog = GTK_WIDGET (hildon_note_new_information (NULL, 
1035                         prompt));
1036          }
1037 #else
1038
1039         GtkMessageType gtktype = GTK_MESSAGE_ERROR;
1040         switch (type)
1041         {
1042                 case TNY_ALERT_TYPE_INFO:
1043                 gtktype = GTK_MESSAGE_INFO;
1044                 break;
1045                 case TNY_ALERT_TYPE_WARNING:
1046                 gtktype = GTK_MESSAGE_WARNING;
1047                 break;
1048                 case TNY_ALERT_TYPE_ERROR:
1049                 default:
1050                 gtktype = GTK_MESSAGE_ERROR;
1051                 break;
1052         }
1053         
1054         GtkWidget *dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL,
1055                 gtktype, GTK_BUTTONS_YES_NO, prompt);
1056 #endif /* #ifdef MODEST_PLATFORM_MAEMO */
1057
1058         gboolean retval = TRUE;
1059         const int response = gtk_dialog_run (GTK_DIALOG (dialog));
1060         if (question) {
1061                 retval = (response == GTK_RESPONSE_YES) ||
1062                                  (response == GTK_RESPONSE_OK); 
1063         }
1064
1065         gtk_widget_destroy (dialog);
1066         
1067         /* TODO: Don't free this when we no longer strdup the message for testers. */
1068         g_free (prompt);
1069
1070
1071         /* printf("DEBUG: %s: returning %d\n", __FUNCTION__, retval); */
1072         return retval;
1073 }
1074
1075
1076 static void
1077 modest_tny_account_store_init (gpointer g, gpointer iface_data)
1078 {
1079         TnyAccountStoreIface *klass;
1080
1081         g_return_if_fail (g);
1082
1083         klass = (TnyAccountStoreIface *)g;
1084
1085         klass->get_accounts_func =
1086                 modest_tny_account_store_get_accounts;
1087         klass->get_cache_dir_func =
1088                 modest_tny_account_store_get_cache_dir;
1089         klass->get_device_func =
1090                 modest_tny_account_store_get_device;
1091         klass->alert_func =
1092                 modest_tny_account_store_alert;
1093         klass->find_account_func =
1094                 modest_tny_account_store_find_account_by_url;
1095 }
1096
1097 void
1098 modest_tny_account_store_set_get_pass_func (ModestTnyAccountStore *self,
1099                                             ModestTnyGetPassFunc func)
1100 {
1101         /* not implemented, we use signals */
1102         g_printerr ("modest: set_get_pass_func not implemented\n");
1103 }
1104
1105 TnySessionCamel*
1106 modest_tny_account_store_get_session  (TnyAccountStore *self)
1107 {
1108         g_return_val_if_fail (self, NULL);
1109         return MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self)->session;
1110 }
1111
1112
1113 static void
1114 fill_server_account_cache_if_needed (ModestTnyAccountStore *self)
1115 {
1116         /* cache if needed */
1117         ModestTnyAccountStorePrivate *priv;     
1118         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1119
1120         TnyList* list = TNY_LIST(tny_simple_list_new());
1121         if (!priv->store_accounts)
1122                 modest_tny_account_store_get_accounts  (TNY_ACCOUNT_STORE(self),
1123                                                         list, TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
1124         g_object_unref (list);
1125
1126         list = TNY_LIST(tny_simple_list_new());
1127         if (!priv->transport_accounts)
1128                 modest_tny_account_store_get_accounts  (TNY_ACCOUNT_STORE(self),
1129                                                         list, TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS);
1130         g_object_unref (list);
1131 }
1132
1133
1134 TnyAccount*
1135 modest_tny_account_store_get_tny_account_by (ModestTnyAccountStore *self, 
1136                                              ModestTnyAccountStoreQueryType type,
1137                                              const gchar *str)
1138 {
1139         TnyAccount *account = NULL;
1140         ModestTnyAccountStorePrivate *priv;     
1141         GSList *cursor;
1142         const gchar *val = NULL;
1143
1144         g_return_val_if_fail (self, NULL);
1145         g_return_val_if_fail (str, NULL);
1146         
1147         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1148
1149         fill_server_account_cache_if_needed (self);
1150                 
1151         /* Search in store accounts */
1152         for (cursor = priv->store_accounts; cursor ; cursor = cursor->next) {
1153                 switch (type) {
1154                 case MODEST_TNY_ACCOUNT_STORE_QUERY_ID:
1155                         val = tny_account_get_id (TNY_ACCOUNT(cursor->data));
1156                         break;
1157                 case MODEST_TNY_ACCOUNT_STORE_QUERY_NAME:
1158                         val = modest_tny_account_get_parent_modest_account_name_for_server_account (TNY_ACCOUNT(cursor->data));
1159                         break;
1160                 case MODEST_TNY_ACCOUNT_STORE_QUERY_URL:
1161                         val = tny_account_get_url_string (TNY_ACCOUNT(cursor->data));
1162                         break;
1163                 }
1164                 
1165                 if (type == MODEST_TNY_ACCOUNT_STORE_QUERY_URL && 
1166                     tny_account_matches_url_string (TNY_ACCOUNT(cursor->data), str)) {
1167                         account = TNY_ACCOUNT (cursor->data);
1168                         goto end;
1169                 } else {
1170                         if (strcmp (val, str) == 0) {
1171                                 account = TNY_ACCOUNT(cursor->data);
1172                                 goto end;
1173                         }
1174                 }
1175         }
1176                 
1177         /* if we already found something, no need to search the transport accounts */
1178         for (cursor = priv->transport_accounts; !account && cursor ; cursor = cursor->next) {
1179                 switch (type) {
1180                 case MODEST_TNY_ACCOUNT_STORE_QUERY_ID:
1181                         val = tny_account_get_id (TNY_ACCOUNT(cursor->data));
1182                         break;
1183                 case MODEST_TNY_ACCOUNT_STORE_QUERY_NAME:
1184                         val = tny_account_get_name (TNY_ACCOUNT(cursor->data));
1185                         break;
1186                 case MODEST_TNY_ACCOUNT_STORE_QUERY_URL:
1187                         val = tny_account_get_url_string (TNY_ACCOUNT(cursor->data));
1188                         break;
1189                 }
1190                 
1191                 if (type == MODEST_TNY_ACCOUNT_STORE_QUERY_URL && 
1192                     tny_account_matches_url_string (TNY_ACCOUNT(cursor->data), val)) {
1193                         account = TNY_ACCOUNT (cursor->data);
1194                         goto end;
1195                 } else {
1196                         if (strcmp (val, str) == 0) {
1197                                 account = TNY_ACCOUNT(cursor->data);
1198                                 goto end;
1199                         }
1200                 }
1201         }
1202  end:
1203         if (account)
1204                 g_object_ref (G_OBJECT(account));
1205         
1206         return account;
1207 }
1208
1209 TnyAccount*
1210 modest_tny_account_store_get_server_account (ModestTnyAccountStore *self,
1211                                                      const gchar *account_name,
1212                                                      TnyAccountType type)
1213 {
1214         TnyAccount *account = NULL;
1215         gchar *id = NULL;
1216         ModestTnyAccountStorePrivate *priv;     
1217
1218         g_return_val_if_fail (self, NULL);
1219         g_return_val_if_fail (account_name, NULL);
1220         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || type == TNY_ACCOUNT_TYPE_TRANSPORT,
1221                               NULL);
1222         
1223         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1224
1225         /* Special case for the local account */
1226         if (!strcmp (account_name, MODEST_LOCAL_FOLDERS_ACCOUNT_ID)) {
1227                 if(type == TNY_ACCOUNT_TYPE_STORE)
1228                         id = g_strdup (MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
1229                 else {
1230                         /* The local folders modest account has no transport server account. */
1231                         return NULL;
1232                 }
1233         } else {
1234                 ModestAccountData *account_data;
1235                 account_data = modest_account_mgr_get_account_data (priv->account_mgr, account_name);
1236                 if (!account_data) {
1237                         g_printerr ("modest: %s: cannot get account data for account '%s'\n", __FUNCTION__,
1238                                     account_name);
1239                         return NULL;
1240                 }
1241
1242                 if (type == TNY_ACCOUNT_TYPE_STORE && account_data->store_account)
1243                         id = g_strdup (account_data->store_account->account_name);
1244                 else if (account_data->transport_account)
1245                         id = g_strdup (account_data->transport_account->account_name);
1246
1247                 modest_account_mgr_free_account_data (priv->account_mgr, account_data);
1248         }
1249
1250         if (!id)
1251                 g_printerr ("modest: could not get an id for account %s\n",
1252                             account_name);
1253         else    
1254                 account = modest_tny_account_store_get_tny_account_by (self, MODEST_TNY_ACCOUNT_STORE_QUERY_ID, id);
1255
1256         if (!account)
1257                 g_printerr ("modest: could not get tny %s account for %s (id=%s)\n",
1258                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
1259                             account_name, id ? id : "<none>");
1260
1261         return account; 
1262 }
1263
1264 static TnyAccount*
1265 get_smtp_specific_transport_account_for_open_connection (ModestTnyAccountStore *self,
1266                                                          const gchar *account_name)
1267 {
1268         /* Get the current connection: */
1269         TnyDevice *device = modest_runtime_get_device ();
1270         
1271         if (!tny_device_is_online (device))
1272                 return NULL;
1273
1274 #ifdef MODEST_PLATFORM_MAEMO
1275         g_assert (TNY_IS_MAEMO_CONIC_DEVICE (device));
1276         TnyMaemoConicDevice *maemo_device = TNY_MAEMO_CONIC_DEVICE (device);    
1277         const gchar* iap_id = tny_maemo_conic_device_get_current_iap_id (maemo_device);
1278         /* printf ("DEBUG: %s: iap_id=%s\n", __FUNCTION__, iap_id); */
1279         if (!iap_id)
1280                 return NULL;
1281                 
1282         ConIcIap* connection = tny_maemo_conic_device_get_iap (maemo_device, iap_id);
1283         if (!connection)
1284                 return NULL;
1285                 
1286         const gchar *connection_name = con_ic_iap_get_name (connection);
1287         /* printf ("DEBUG: %s: connection_name=%s\n", __FUNCTION__, connection_name); */
1288         if (!connection_name)
1289                 return NULL;
1290         
1291         /*  Get the connection-specific transport acccount, if any: */
1292         ModestAccountMgr *account_manager = modest_runtime_get_account_mgr ();
1293         gchar* server_account_name = modest_account_mgr_get_connection_specific_smtp (account_manager, 
1294                 account_name, connection_name);
1295
1296         /* printf ("DEBUG: %s: server_account_name=%s\n", __FUNCTION__, server_account_name); */
1297         if (!server_account_name) {
1298                 return NULL; /* No connection-specific SMTP server was specified for this connection. */
1299         }
1300                 
1301         TnyAccount* account = modest_tny_account_store_get_tny_account_by (self, 
1302                                                                            MODEST_TNY_ACCOUNT_STORE_QUERY_ID, 
1303                                                                            server_account_name);
1304
1305         /* printf ("DEBUG: %s: account=%p\n", __FUNCTION__, account); */
1306         g_free (server_account_name);   
1307
1308         /* Unref the get()ed object, as required by the tny_maemo_conic_device_get_iap() documentation. */
1309         g_object_unref (connection);
1310         
1311         return account;
1312 #else
1313         return NULL; /* TODO: Implement this for GNOME, instead of just Maemo? */
1314 #endif /* MODEST_PLATFORM_MAEMO */
1315 }
1316
1317                                                                  
1318 TnyAccount*
1319 modest_tny_account_store_get_transport_account_for_open_connection (ModestTnyAccountStore *self,
1320                                                                     const gchar *account_name)
1321 {
1322         /*  Get the connection-specific transport acccount, if any: */
1323         TnyAccount *account = get_smtp_specific_transport_account_for_open_connection (self, account_name);
1324                         
1325         /* If there is no connection-specific transport account (the common case), 
1326          * just get the regular transport account: */
1327         if (!account) {
1328                 /* printf("DEBUG: %s: using regular transport account for account %s.\n", __FUNCTION__, account_name); */
1329
1330                 /* The special local folders don't have transport accounts. */
1331                 if (strcmp (account_name, MODEST_LOCAL_FOLDERS_ACCOUNT_ID) == 0)
1332                         account = NULL;
1333                 else
1334                         account = modest_tny_account_store_get_server_account (self, account_name, 
1335                                                      TNY_ACCOUNT_TYPE_TRANSPORT);
1336         }
1337                              
1338         return account;
1339 }
1340
1341 gboolean
1342 modest_tny_account_is_virtual_local_folders (TnyAccount *self)
1343 {
1344         /* We should make this more sophisticated if we ever use ModestTnyLocalFoldersAccount 
1345          * for anything else. */
1346         return MODEST_IS_TNY_LOCAL_FOLDERS_ACCOUNT (self);
1347 }
1348
1349 TnyAccount*
1350 modest_tny_account_store_get_local_folders_account (TnyAccountStore *self)
1351 {
1352         TnyAccount *account = NULL;
1353         ModestTnyAccountStorePrivate *priv;     
1354         GSList *cursor;
1355
1356         g_return_val_if_fail (self, NULL);
1357         
1358         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1359
1360         for (cursor = priv->store_accounts; cursor ; cursor = cursor->next) {
1361                 TnyAccount *this_account = TNY_ACCOUNT(cursor->data);
1362                 if (modest_tny_account_is_virtual_local_folders (this_account)) {
1363                                  account = this_account;
1364                                  break;
1365                 }
1366         }
1367
1368         if (account)
1369                 g_object_ref (G_OBJECT(account));
1370         
1371         return account;
1372 }