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