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