Fixes NB#114489, show the account settings dialog on connection errors
[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-error.h>
34 #include <tny-account.h>
35 #include <tny-account-store.h>
36 #include <tny-store-account.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 #include "modest-text-utils.h"
44 #include <modest-runtime.h>
45 #include <modest-marshal.h>
46 #include <modest-protocol-registry.h>
47 #include <modest-local-folder-info.h>
48 #include "modest-account-protocol.h"
49 #include <modest-tny-account.h>
50 #include <modest-tny-local-folders-account.h>
51 #include <modest-account-mgr.h>
52 #include <modest-account-mgr-helpers.h>
53 #include <widgets/modest-window-mgr.h>
54 #include <modest-signal-mgr.h>
55 #include <modest-debug.h>
56
57 #include <modest-defs.h>
58 #include "modest-tny-account-store.h"
59 #include "modest-tny-platform-factory.h"
60 #include <tny-gtk-lockable.h>
61 #include <camel/camel.h>
62 #include <modest-platform.h>
63 #include "modest-ui-actions.h"
64 #include <widgets/modest-account-settings-dialog.h>
65
66 #ifdef MODEST_PLATFORM_MAEMO
67 #include <tny-maemo-conic-device.h>
68 #include <maemo/modest-maemo-utils.h>
69 #endif
70
71 #include <libgnomevfs/gnome-vfs-volume-monitor.h>
72
73 /* 'private'/'protected' functions */
74 static void    modest_tny_account_store_class_init   (ModestTnyAccountStoreClass *klass);
75 static void    modest_tny_account_store_finalize     (GObject *obj);
76 static void    modest_tny_account_store_instance_init (ModestTnyAccountStore *obj);
77 static void    modest_tny_account_store_init          (gpointer g, gpointer iface_data);
78 static void    modest_tny_account_store_base_init     (gpointer g_class);
79
80 static void    on_account_inserted         (ModestAccountMgr *acc_mgr, 
81                                             const gchar *account,
82                                             gpointer user_data);
83
84 static void   add_existing_accounts       (ModestTnyAccountStore *self);
85
86 static void    insert_account              (ModestTnyAccountStore *self,
87                                             const gchar *account,
88                                             gboolean notify);
89
90 static void    on_account_removed          (ModestAccountMgr *acc_mgr, 
91                                             const gchar *account,
92                                             gpointer user_data);
93
94 static gchar*  get_password                (TnyAccount *account, 
95                                             const gchar * prompt_not_used, 
96                                             gboolean *cancel);
97
98 static void    forget_password             (TnyAccount *account);
99
100 static void    on_vfs_volume_mounted       (GnomeVFSVolumeMonitor *volume_monitor, 
101                                             GnomeVFSVolume *volume, 
102                                             gpointer user_data);
103
104 static void    on_vfs_volume_unmounted     (GnomeVFSVolumeMonitor *volume_monitor, 
105                                             GnomeVFSVolume *volume, 
106                                             gpointer user_data);
107
108 static void    forget_password_in_memory (ModestTnyAccountStore *self, 
109                                           const gchar *server_account_name);
110
111 static void    add_connection_specific_transport_accounts         (ModestTnyAccountStore *self);
112
113 static void    remove_connection_specific_transport_accounts      (ModestTnyAccountStore *self);
114
115 static inline gboolean only_local_accounts        (ModestTnyAccountStore *self);
116
117 /* list my signals */
118 enum {
119         ACCOUNT_CHANGED_SIGNAL,
120         ACCOUNT_INSERTED_SIGNAL,
121         ACCOUNT_REMOVED_SIGNAL,
122
123         PASSWORD_REQUESTED_SIGNAL,
124         LAST_SIGNAL
125 };
126
127 typedef struct _ModestTnyAccountStorePrivate ModestTnyAccountStorePrivate;
128 struct _ModestTnyAccountStorePrivate {
129         gchar              *cache_dir;  
130         GHashTable         *password_hash;
131         ModestAccountMgr   *account_mgr;
132         TnySessionCamel    *session;
133         TnyDevice          *device;
134
135         GSList *sighandlers;
136         
137         /* We cache the lists of accounts here */
138         TnyList             *store_accounts;
139         TnyList             *transport_accounts;
140         TnyList             *store_accounts_outboxes;
141         
142         /* Matches transport accounts and outbox folder */
143         GHashTable          *outbox_of_transport;
144
145         /* is sending mail blocked? */
146         gboolean send_mail_blocked;
147 };
148
149 #define MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
150                                                       MODEST_TYPE_TNY_ACCOUNT_STORE, \
151                                                       ModestTnyAccountStorePrivate))
152
153 /* globals */
154 static GObjectClass *parent_class = NULL;
155
156 static guint signals[LAST_SIGNAL] = {0};
157
158 GType
159 modest_tny_account_store_get_type (void)
160 {
161         static GType my_type = 0;
162
163         if (!my_type) {
164                 static const GTypeInfo my_info = {
165                         sizeof(ModestTnyAccountStoreClass),
166                         modest_tny_account_store_base_init,     /* base init */
167                         NULL,           /* base finalize */
168                         (GClassInitFunc) modest_tny_account_store_class_init,
169                         NULL,           /* class finalize */
170                         NULL,           /* class data */
171                         sizeof(ModestTnyAccountStore),
172                         0,              /* n_preallocs */
173                         (GInstanceInitFunc) modest_tny_account_store_instance_init,
174                         NULL
175                 };
176
177                 static const GInterfaceInfo iface_info = {
178                         (GInterfaceInitFunc) modest_tny_account_store_init,
179                         NULL,         /* interface_finalize */
180                         NULL          /* interface_data */
181                 };
182                 /* hack hack */
183                 my_type = g_type_register_static (G_TYPE_OBJECT,
184                                                   "ModestTnyAccountStore",
185                                                   &my_info, 0);
186                 g_type_add_interface_static (my_type, TNY_TYPE_ACCOUNT_STORE,
187                                              &iface_info);
188         }
189         return my_type;
190 }
191
192
193 static void
194 modest_tny_account_store_base_init (gpointer g_class)
195 {
196         static gboolean tny_account_store_initialized = FALSE;
197
198         if (!tny_account_store_initialized) {
199
200                 signals[ACCOUNT_CHANGED_SIGNAL] =
201                         g_signal_new ("account_changed",
202                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
203                                       G_SIGNAL_RUN_FIRST,
204                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_changed),
205                                       NULL, NULL,
206                                       g_cclosure_marshal_VOID__OBJECT,
207                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
208
209                 signals[ACCOUNT_INSERTED_SIGNAL] =
210                         g_signal_new ("account_inserted",
211                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
212                                       G_SIGNAL_RUN_FIRST,
213                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_inserted),
214                                       NULL, NULL,
215                                       g_cclosure_marshal_VOID__OBJECT,
216                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
217                 
218                 signals[ACCOUNT_REMOVED_SIGNAL] =
219                         g_signal_new ("account_removed",
220                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
221                                       G_SIGNAL_RUN_FIRST,
222                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_removed),
223                                       NULL, NULL,
224                                       g_cclosure_marshal_VOID__OBJECT,
225                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
226
227                 signals[PASSWORD_REQUESTED_SIGNAL] =
228                         g_signal_new ("password_requested",
229                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
230                                       G_SIGNAL_RUN_FIRST,
231                                       G_STRUCT_OFFSET(ModestTnyAccountStoreClass, password_requested),
232                                       NULL, NULL,
233                                       modest_marshal_VOID__STRING_POINTER_POINTER_POINTER_POINTER,
234                                       G_TYPE_NONE, 5, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_POINTER, G_TYPE_POINTER,
235                                       G_TYPE_POINTER);          
236
237                 tny_account_store_initialized = TRUE;
238         }
239 }
240
241
242 static void
243 modest_tny_account_store_class_init (ModestTnyAccountStoreClass *klass)
244 {
245         GObjectClass *gobject_class;
246         gobject_class = (GObjectClass*) klass;
247
248         parent_class            = g_type_class_peek_parent (klass);
249         gobject_class->finalize = modest_tny_account_store_finalize;
250
251         g_type_class_add_private (gobject_class,
252                                   sizeof(ModestTnyAccountStorePrivate));
253 }
254      
255 static void
256 modest_tny_account_store_instance_init (ModestTnyAccountStore *obj)
257 {
258         GnomeVFSVolumeMonitor* monitor = NULL;
259         ModestTnyAccountStorePrivate *priv;
260
261         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
262
263         priv->cache_dir              = NULL;
264         priv->account_mgr            = NULL;
265         priv->session                = NULL;
266         priv->device                 = NULL;
267         priv->sighandlers            = NULL;
268         priv->send_mail_blocked      = FALSE;
269         
270         priv->outbox_of_transport = g_hash_table_new_full (g_direct_hash,
271                                                            g_direct_equal,
272                                                            NULL,
273                                                            NULL);
274
275         /* An in-memory store of passwords, 
276          * for passwords that are not remembered in the configuration,
277          * so they need to be asked for from the user once in each session:
278          */
279         priv->password_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
280                                                      g_free, g_free);
281
282         /* Respond to volume mounts and unmounts, such 
283          * as the insertion/removal of the memory card: */
284         /* This is a singleton, so it does not need to be unrefed. */
285         monitor = gnome_vfs_get_volume_monitor();
286
287         priv->sighandlers = modest_signal_mgr_connect (priv->sighandlers, 
288                                                        G_OBJECT(monitor), 
289                                                        "volume-mounted",
290                                                        G_CALLBACK(on_vfs_volume_mounted),
291                                                        obj);
292         priv->sighandlers = modest_signal_mgr_connect (priv->sighandlers, 
293                                                        G_OBJECT(monitor), "volume-unmounted",
294                                                        G_CALLBACK(on_vfs_volume_unmounted),
295                                                        obj);
296 }
297
298 /* disconnect the list of TnyAccounts */
299 static void
300 account_verify_last_ref (TnyAccount *account, const gchar *str)
301 {
302         gchar *txt;
303
304         g_return_if_fail (account && TNY_IS_ACCOUNT(account));
305
306         txt = g_strdup_printf ("%s: %s", str ? str : "?", tny_account_get_name(account));
307         MODEST_DEBUG_VERIFY_OBJECT_LAST_REF(G_OBJECT(account),txt);
308         g_free (txt);
309 }
310
311 static void
312 foreach_account_append_to_list (gpointer data, 
313                                 gpointer user_data)
314 {
315         TnyList *list;
316         
317         list = TNY_LIST (user_data);
318         tny_list_append (list, G_OBJECT (data));
319 }
320
321 /********************************************************************/
322 /*           Control the state of the MMC local account             */
323 /********************************************************************/
324
325 /** Only call this if the memory card is really mounted.
326  */ 
327 static void
328 add_mmc_account(ModestTnyAccountStore *self, gboolean emit_insert_signal)
329 {
330         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
331         g_return_if_fail (priv->session);
332         
333         TnyAccount *mmc_account = modest_tny_account_new_for_local_folders (priv->account_mgr, 
334                                                                             priv->session, 
335                                                                             g_getenv (MODEST_MMC1_VOLUMEPATH_ENV));
336
337         /* Add to the list of store accounts */
338         tny_list_append (priv->store_accounts, G_OBJECT (mmc_account));
339
340         if (emit_insert_signal) {
341                 g_signal_emit (G_OBJECT (self), 
342                                signals [ACCOUNT_INSERTED_SIGNAL],
343                                0, mmc_account);
344         }
345
346         /* Free */
347         g_object_unref (mmc_account);
348 }
349
350 static void
351 on_vfs_volume_mounted(GnomeVFSVolumeMonitor *volume_monitor, 
352                       GnomeVFSVolume *volume, 
353                       gpointer user_data)
354 {
355         ModestTnyAccountStore *self;
356         ModestTnyAccountStorePrivate *priv;
357         gchar *volume_path_uri;
358  
359         gchar *uri = NULL;
360
361         self = MODEST_TNY_ACCOUNT_STORE(user_data);
362         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
363         
364         /* Check whether this was the external MMC1 card: */
365         uri = gnome_vfs_volume_get_activation_uri (volume);
366
367         volume_path_uri = g_strconcat (MODEST_MMC1_VOLUMEPATH_URI_PREFIX,
368                                        g_getenv (MODEST_MMC1_VOLUMEPATH_ENV),
369                                        NULL);
370         if (uri && (!strcmp (uri, volume_path_uri))) {
371                 add_mmc_account (self, TRUE /* emit the insert signal. */);
372         }
373
374         g_free (volume_path_uri);       
375         g_free (uri);
376 }
377
378 static void
379 on_vfs_volume_unmounted(GnomeVFSVolumeMonitor *volume_monitor, 
380                         GnomeVFSVolume *volume, 
381                         gpointer user_data)
382 {
383         ModestTnyAccountStore *self;
384         ModestTnyAccountStorePrivate *priv;
385         gchar *uri = NULL;
386         gchar *volume_path_uri;
387
388         self = MODEST_TNY_ACCOUNT_STORE(user_data);
389         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
390         
391         /* Check whether this was the external MMC1 card: */
392         uri = gnome_vfs_volume_get_activation_uri (volume);
393         volume_path_uri = g_strconcat (MODEST_MMC1_VOLUMEPATH_URI_PREFIX,
394                                        g_getenv (MODEST_MMC1_VOLUMEPATH_ENV),
395                                        NULL);
396         if (uri && (strcmp (uri, volume_path_uri) == 0)) {
397                 TnyAccount *mmc_account = NULL;
398                 gboolean found = FALSE;
399                 TnyIterator *iter = NULL;
400
401                 iter = tny_list_create_iterator (priv->store_accounts);
402                 while (!tny_iterator_is_done (iter) && !found) {
403                         TnyAccount *account;
404
405                         account = TNY_ACCOUNT (tny_iterator_get_current (iter));
406                         if (modest_tny_account_is_memory_card_account (account)) {
407                                 found = TRUE;
408                                 mmc_account = g_object_ref (account);
409                         }
410                         g_object_unref (account);
411                         tny_iterator_next (iter);
412                 }
413                 g_object_unref (iter);
414
415                 if (found) {
416                         /* Remove from the list */
417                         tny_list_remove (priv->store_accounts, G_OBJECT (mmc_account));
418                         
419                         /* Notify observers */
420                         g_signal_emit (G_OBJECT (self),
421                                        signals [ACCOUNT_REMOVED_SIGNAL],
422                                        0, mmc_account);
423
424                         g_object_unref (mmc_account);
425                 } else {
426                         g_warning ("%s: there was no store account for the unmounted MMC",
427                                    __FUNCTION__);
428                 }
429         }
430         g_free (volume_path_uri);
431         g_free (uri);
432 }
433
434 /**
435  * forget_password_in_memory
436  * @self: a TnyAccountStore instance
437  * @account: A server account.
438  * 
439  * Forget any password stored in memory for this account.
440  * For instance, this should be called when the user has changed the password in the account settings.
441  */
442 static void
443 forget_password_in_memory (ModestTnyAccountStore *self, 
444                            const gchar * server_account_name)
445 {
446         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
447
448         if (server_account_name && priv->password_hash) {
449                 g_hash_table_remove (priv->password_hash, server_account_name);
450         }
451 }
452
453 static void
454 on_account_changed (ModestAccountMgr *acc_mgr, 
455                     const gchar *account_name, 
456                     TnyAccountType account_type,
457                     gpointer user_data)
458 {
459         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
460         ModestTnyAccountStorePrivate *priv;
461         TnyList* account_list;
462         gboolean found = FALSE;
463         TnyIterator *iter = NULL;
464
465         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
466         account_list = (account_type == TNY_ACCOUNT_TYPE_STORE ? 
467                         priv->store_accounts : 
468                         priv->transport_accounts);
469
470         iter = tny_list_create_iterator (account_list);
471         while (!tny_iterator_is_done (iter) && !found) {
472                 TnyAccount *tny_account;
473                 tny_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
474                 if (tny_account) {
475                         if (!strcmp (tny_account_get_id (tny_account), account_name)) {
476                                 found = TRUE;
477                                 modest_tny_account_update_from_account (tny_account, get_password, forget_password);
478                                 g_signal_emit (G_OBJECT(self), signals[ACCOUNT_CHANGED_SIGNAL], 0, tny_account);
479                         }
480                         g_object_unref (tny_account);
481                 }
482                 tny_iterator_next (iter);
483         }
484         g_object_unref (iter);
485 }
486
487 static void 
488 show_password_warning_only (const gchar *msg)
489 {
490         /* Show an explanatory temporary banner: */
491         if (modest_window_mgr_get_num_windows (modest_runtime_get_window_mgr ()))
492                 modest_platform_information_banner (NULL, NULL, msg);
493 }
494
495 static void 
496 show_wrong_password_dialog (TnyAccount *account)
497
498         if (g_object_get_data (G_OBJECT (account), "connection_specific") != NULL) {
499                 modest_ui_actions_on_smtp_servers (NULL, NULL);
500         } else {
501                 ModestAccountProtocol *proto;
502                 ModestProtocolType proto_type;
503                 const gchar *modest_account_name;
504                 modest_account_name = modest_tny_account_get_parent_modest_account_name_for_server_account (account);
505
506                 /* Get proto */
507                 proto_type = modest_account_mgr_get_store_protocol (modest_runtime_get_account_mgr (), 
508                                                                     modest_account_name);
509                 proto = (ModestAccountProtocol *)
510                         modest_protocol_registry_get_protocol_by_type (modest_runtime_get_protocol_registry (), 
511                                                                        proto_type);
512
513                 /* Create and show the dialog */
514                 if (proto && MODEST_IS_ACCOUNT_PROTOCOL (proto)) {
515                         ModestAccountSettingsDialog *dialog =
516                                 modest_account_protocol_get_account_settings_dialog (proto, modest_account_name);
517                         modest_window_mgr_set_modal (modest_runtime_get_window_mgr (), GTK_WINDOW (dialog), NULL);
518                         gtk_widget_show (GTK_WIDGET (dialog));
519                 }
520         }
521         /* Show an explanatory temporary banner: */
522         modest_platform_information_banner (NULL, NULL, _("mcen_ib_username_pw_incorrect"));
523 }
524
525 /* This callback will be called by Tinymail when it needs the password
526  * from the user or the account settings.
527  * It can also call forget_password() before calling this,
528  * so that we clear wrong passwords out of our account settings.
529  * Note that TnyAccount here will be the server account. */
530 static gchar*
531 get_password (TnyAccount *account, const gchar * prompt_not_used, gboolean *cancel)
532 {
533         ModestTnyAccountStore *self = NULL;
534         ModestTnyAccountStorePrivate *priv;
535         gchar *username = NULL;
536         gchar *pwd = NULL;
537         gpointer pwd_ptr = NULL;
538         gboolean already_asked = FALSE;
539         const gchar *server_account_name;
540         gchar *url_string;
541
542         g_return_val_if_fail (account, NULL);
543         
544         MODEST_DEBUG_BLOCK(
545                 g_debug ("%s: prompt (not shown) = %s\n", __FUNCTION__, prompt_not_used);
546         );              
547
548         /* Get a reference to myself */
549         self = MODEST_TNY_ACCOUNT_STORE (g_object_get_data (G_OBJECT(account), "account_store"));
550         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
551
552         /* Ensure that we still have this account. It could happen
553            that a set_online was requested *before* removing an
554            account, and due to tinymail emits the get_password
555            function using a g_idle the account could be actually
556            removed *before* this function was really called */
557         url_string = tny_account_get_url_string (account);
558         if (url_string) {
559                 TnyAccount *tmp_account;
560
561                 tmp_account = tny_account_store_find_account (TNY_ACCOUNT_STORE (self), 
562                                                               url_string);
563                 g_free (url_string);
564
565                 if (!tmp_account) {
566                         *cancel = TRUE;
567                         return NULL;
568                 }
569                 g_object_unref (tmp_account);
570         }
571
572         server_account_name = tny_account_get_id (account);
573         if (!server_account_name || !self) {
574                 g_warning ("modest: %s: could not retrieve account_store for account %s",
575                            __FUNCTION__, server_account_name ? server_account_name : "<NULL>");
576                 if (cancel)
577                         *cancel = TRUE;
578
579                 return NULL;
580         }
581
582         /* This hash map stores passwords, including passwords that are not stored in gconf. */
583         /* Is it in the hash? if it's already there, it must be wrong... */
584         pwd_ptr = (gpointer)&pwd; /* pwd_ptr so the compiler does not complained about
585                                    * type-punned ptrs...*/
586         already_asked = priv->password_hash && 
587                                 g_hash_table_lookup_extended (priv->password_hash,
588                                                       server_account_name,
589                                                       NULL,
590                                                       (gpointer*)&pwd_ptr);
591         MODEST_DEBUG_BLOCK(
592                 g_debug ("%s: Already asked = %d\n", __FUNCTION__, already_asked);
593         );
594
595         /* If the password is not already there, try ModestConf */
596         if (!already_asked) {
597                 pwd  = modest_account_mgr_get_server_account_password (priv->account_mgr,
598                                                                        server_account_name);
599                 g_hash_table_insert (priv->password_hash, g_strdup (server_account_name), g_strdup (pwd));
600         }
601
602         /* If it was already asked, it must have been wrong, so ask again */
603         if (already_asked || !pwd || strlen(pwd) == 0) {
604                 gboolean settings_have_password;
605                 ModestProtocolType protocol_type;
606
607                 /* As per the UI spec, if no password was set in the account settings, 
608                  * ask for it now. But if the password is wrong in the account settings, 
609                  * then show a banner and the account settings dialog so it can be corrected:
610                  */
611                 settings_have_password = 
612                         modest_account_mgr_get_server_account_has_password (priv->account_mgr, server_account_name);
613
614                 protocol_type = modest_tny_account_get_protocol_type (account);
615
616                 /* Show an error and after that ask for a password */
617                 if (modest_protocol_registry_protocol_type_has_tag(modest_runtime_get_protocol_registry (), 
618                                                                    protocol_type, MODEST_PROTOCOL_REGISTRY_TRANSPORT_PROTOCOLS)) {
619                         gchar *username = NULL, *msg = NULL;
620                         username = modest_account_mgr_get_server_account_username (priv->account_mgr,
621                                                                                    server_account_name);
622                         if (!username || strlen(username) == 0) {
623                                 msg = g_strdup_printf (_("emev_ni_ui_smtp_userid_invalid"), 
624                                                        tny_account_get_name (account),
625                                                        tny_account_get_hostname (account));
626                         } else {
627                                 gchar *password;
628                                 password  = modest_account_mgr_get_server_account_password (priv->account_mgr,
629                                                                                             server_account_name);
630
631                                 if (already_asked)
632                                         msg = g_strdup (_("mcen_ib_username_pw_incorrect"));
633                                 else if (!password || strlen(password) == 0)
634                                         msg = g_strdup_printf (_("emev_ni_ui_smtp_passwd_invalid"), 
635                                                                tny_account_get_name (account),
636                                                                tny_account_get_hostname (account));
637                                 else
638                                         msg = g_strdup_printf (_("emev_ni_ui_smtp_authentication_fail_error"), 
639                                                                tny_account_get_hostname (account));
640                                 if (password)
641                                         g_free (password);
642                         }
643                         if (msg) {
644                                 modest_platform_run_information_dialog (NULL, msg, TRUE);
645                                 g_free (msg);
646                         }
647                         if (username)
648                                 g_free (username);
649                 }
650
651                 if (settings_have_password) {
652                         /* The password must be wrong, so show the account settings dialog so it can be corrected: */
653                         show_wrong_password_dialog (account);
654
655                         if (cancel)
656                                 *cancel = TRUE;
657
658                         return NULL;
659                 }
660
661                 /* we don't have it yet. Get the password from the user */
662                 const gchar* account_id = tny_account_get_id (account);
663                 gboolean remember = FALSE;
664                 pwd = NULL;
665
666                 if (already_asked) {
667                         const gchar *msg;
668                         gboolean username_known = 
669                                 modest_account_mgr_get_server_account_username_has_succeeded(priv->account_mgr, 
670                                                                                              server_account_name);
671                         /* If the login has ever succeeded then show a specific message */
672                         if (username_known)
673                                 msg = _CS ("ecdg_ib_set_password_incorrect");
674                         else
675                                 msg = _("mcen_ib_username_pw_incorrect");
676                         show_password_warning_only (msg);
677                 }
678
679                 /* Request password */
680                 g_signal_emit (G_OBJECT (self), signals[PASSWORD_REQUESTED_SIGNAL], 0,
681                                account_id, /* server_account_name */
682                                &username, &pwd, cancel, &remember);
683
684                 
685                 if (!*cancel) {
686                         /* The password will be returned as the result,
687                          * but we need to tell tinymail about the username too: */
688
689                         /* WARNING: I disabled setting username as this can cause locks. Anyway,
690                          * as now we have the password dialog username entry always dimmed
691                          * this shouldn't be a problem */
692
693                         /* if (username) */
694                         /*      tny_account_set_user (account, username); */
695                         
696                         /* Do not save the password in gconf, because
697                          * the UI spec says "The password will never
698                          * be saved in the account": */
699
700                         /* We need to dup the string even knowing that
701                            it's already a dup of the contents of an
702                            entry, because it if it's wrong, then camel
703                            will free it */
704                         g_hash_table_insert (priv->password_hash, g_strdup (server_account_name), g_strdup(pwd));
705                 } else {
706                         g_hash_table_remove (priv->password_hash, server_account_name);
707                         
708                         g_free (pwd);
709                         pwd = NULL;
710                 }
711
712                 g_free (username);
713                 username = NULL;
714         } else
715                 if (cancel)
716                         *cancel = FALSE;        
717         return pwd;
718 }
719
720 void 
721 modest_tny_account_store_forget_already_asked (ModestTnyAccountStore *self, TnyAccount *account)
722 {
723         g_return_if_fail (account);
724           
725         ModestTnyAccountStorePrivate *priv;
726         gchar *pwd = NULL;
727         gpointer pwd_ptr = NULL;
728         gboolean already_asked = FALSE;
729                 
730         const gchar *server_account_name = tny_account_get_id (account);
731
732         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
733         
734         /* This hash map stores passwords, including passwords that are not stored in gconf. */
735         pwd_ptr = (gpointer)&pwd; /* pwd_ptr so the compiler does not complained about
736                                    * type-punned ptrs...*/
737         already_asked = priv->password_hash && 
738                                 g_hash_table_lookup_extended (priv->password_hash,
739                                                       server_account_name,
740                                                       NULL,
741                                                       (gpointer*)&pwd_ptr);
742
743         if (already_asked) {
744                 g_hash_table_remove (priv->password_hash, server_account_name);         
745                 g_free (pwd);
746                 pwd = NULL;
747         }
748
749         return;
750 }
751
752 /* tinymail calls this if the connection failed due to an incorrect password.
753  * And it seems to call this for any general connection failure. */
754 static void
755 forget_password (TnyAccount *account)
756 {
757         ModestTnyAccountStore *self;
758         ModestTnyAccountStorePrivate *priv;
759         const TnyAccountStore *account_store;
760         gchar *pwd;
761         const gchar *key;
762         
763         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
764                                                              "account_store"));
765         self = MODEST_TNY_ACCOUNT_STORE (account_store);
766         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
767         key  = tny_account_get_id (account);
768
769         /* Do not remove the key, this will allow us to detect that we
770            have already asked for it at least once */
771         pwd = g_hash_table_lookup (priv->password_hash, key);
772         if (pwd) {
773                 memset (pwd, 0, strlen (pwd));
774                 g_hash_table_insert (priv->password_hash, g_strdup (key), NULL);
775         }
776
777         /* Remove from configuration system */
778         /*
779         modest_account_mgr_unset (priv->account_mgr,
780                                   key, MODEST_ACCOUNT_PASSWORD, TRUE);
781         */
782 }
783
784 static void
785 modest_tny_account_store_finalize (GObject *obj)
786 {
787         ModestTnyAccountStore *self        = MODEST_TNY_ACCOUNT_STORE(obj);
788         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
789
790         g_free (priv->cache_dir);
791         priv->cache_dir = NULL;
792         
793         if (priv->password_hash) {
794                 g_hash_table_destroy (priv->password_hash);
795                 priv->password_hash = NULL;
796         }
797
798         if (priv->outbox_of_transport) {
799                 g_hash_table_destroy (priv->outbox_of_transport);
800                 priv->outbox_of_transport = NULL;
801         }
802
803         modest_signal_mgr_disconnect_all_and_destroy (priv->sighandlers);
804         priv->sighandlers = NULL;       
805
806         if (priv->account_mgr) {
807                 g_object_unref (G_OBJECT(priv->account_mgr));
808                 priv->account_mgr = NULL;
809         }
810
811         if (priv->device) {
812                 g_object_unref (G_OBJECT(priv->device));
813                 priv->device = NULL;
814         }
815
816         /* Destroy all accounts. Disconnect all accounts before they are destroyed */
817         if (priv->store_accounts) {
818                 tny_list_foreach (priv->store_accounts, (GFunc)account_verify_last_ref, "store");
819                 g_object_unref (priv->store_accounts);
820                 priv->store_accounts = NULL;
821         }
822         
823         if (priv->transport_accounts) {
824                 tny_list_foreach (priv->transport_accounts, (GFunc)account_verify_last_ref, "transport");
825                 g_object_unref (priv->transport_accounts);
826                 priv->transport_accounts = NULL;
827         }
828
829         if (priv->store_accounts_outboxes) {
830                 g_object_unref (priv->store_accounts_outboxes);
831                 priv->store_accounts_outboxes = NULL;
832         }
833                 
834         if (priv->session) {
835                 camel_object_unref (CAMEL_OBJECT(priv->session));
836                 priv->session = NULL;
837         }
838
839         G_OBJECT_CLASS(parent_class)->finalize (obj);
840 }
841
842 gboolean 
843 volume_path_is_mounted (const gchar* path)
844 {
845         g_return_val_if_fail (path, FALSE);
846
847         gboolean result = FALSE;
848         gchar * path_as_uri = g_filename_to_uri (path, NULL, NULL);
849         g_return_val_if_fail (path_as_uri, FALSE);
850
851         /* Get the monitor singleton: */
852         GnomeVFSVolumeMonitor *monitor = gnome_vfs_get_volume_monitor();
853
854         /* This seems like a simpler way to do this, but it returns a   
855          * GnomeVFSVolume even if the drive is not mounted: */
856         /*
857         GnomeVFSVolume *volume = gnome_vfs_volume_monitor_get_volume_for_path (monitor, 
858                                  g_getenv (MODEST_MMC1_VOLUMEPATH_ENV));
859         if (volume) {
860                 gnome_vfs_volume_unref(volume);
861         }
862         */
863
864         /* Get the mounted volumes from the monitor: */
865         GList *list = gnome_vfs_volume_monitor_get_mounted_volumes (monitor);
866         GList *iter = list;
867         for (iter = list; iter; iter = g_list_next (iter)) {
868                 GnomeVFSVolume *volume = (GnomeVFSVolume*)iter->data;
869                 if (volume) {
870                         /*
871                         char *display_name = 
872                                 gnome_vfs_volume_get_display_name (volume);
873                         printf ("volume display name=%s\n", display_name);
874                         g_free (display_name);
875                         */
876                         
877                         char *uri = 
878                                 gnome_vfs_volume_get_activation_uri (volume);
879                         /* printf ("  uri=%s\n", uri); */
880                         if (uri && (strcmp (uri, path_as_uri) == 0))
881                                 result = TRUE;
882
883                         g_free (uri);
884
885                         gnome_vfs_volume_unref (volume);
886                 }
887         }
888
889         g_list_free (list);
890
891         g_free (path_as_uri);
892
893         return result;
894 }
895
896 ModestTnyAccountStore*
897 modest_tny_account_store_new (ModestAccountMgr *account_mgr, 
898                               TnyDevice *device) 
899 {
900         GObject *obj;
901         ModestTnyAccountStorePrivate *priv;
902         TnyAccount *local_account = NULL;
903         TnyLockable *lockable;  
904
905         g_return_val_if_fail (account_mgr, NULL);
906         g_return_val_if_fail (device, NULL);
907
908         obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_ACCOUNT_STORE, NULL));
909         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
910
911         priv->account_mgr = g_object_ref (G_OBJECT(account_mgr));
912         priv->device = g_object_ref (device);
913         
914         priv->session = tny_session_camel_new (TNY_ACCOUNT_STORE(obj));
915         if (!priv->session) {
916                 g_warning ("failed to get TnySessionCamel");
917                 return NULL;
918         }
919
920         /* Set the ui locker */
921         lockable = tny_gtk_lockable_new ();
922         tny_session_camel_set_ui_locker (priv->session, lockable);
923         g_object_unref (lockable);
924         
925         /* Connect signals */
926         priv->sighandlers  =  modest_signal_mgr_connect (priv->sighandlers,
927                                                          G_OBJECT(account_mgr), "account_inserted",
928                                                          G_CALLBACK (on_account_inserted), obj);
929         priv->sighandlers  =  modest_signal_mgr_connect (priv->sighandlers,
930                                                          G_OBJECT(account_mgr), "account_changed",
931                                                          G_CALLBACK (on_account_changed), obj);
932         priv->sighandlers  =  modest_signal_mgr_connect (priv->sighandlers,
933                                                          G_OBJECT(account_mgr), "account_removed",
934                                                          G_CALLBACK (on_account_removed), obj);
935
936         /* Create the lists of accounts */
937         priv->store_accounts = tny_simple_list_new ();
938         priv->transport_accounts = tny_simple_list_new ();
939         priv->store_accounts_outboxes = tny_simple_list_new ();
940
941         /* Create the local folders account */
942         local_account = 
943                 modest_tny_account_new_for_local_folders (priv->account_mgr, priv->session, NULL);
944         tny_list_append (priv->store_accounts, G_OBJECT(local_account));
945         g_object_unref (local_account); 
946
947         /* Add the other remote accounts. Do this after adding the
948            local account, because we need to add our outboxes to the
949            global OUTBOX hosted in the local account */
950         add_existing_accounts (MODEST_TNY_ACCOUNT_STORE (obj));
951         
952         /* Add connection-specific transport accounts if there are any
953            accounts available */
954         if (!only_local_accounts (MODEST_TNY_ACCOUNT_STORE(obj)))
955                 add_connection_specific_transport_accounts (MODEST_TNY_ACCOUNT_STORE(obj));
956         
957         /* This is a singleton, so it does not need to be unrefed. */
958         if (volume_path_is_mounted (g_getenv (MODEST_MMC1_VOLUMEPATH_ENV))) {
959                 /* It is mounted: */
960                 add_mmc_account (MODEST_TNY_ACCOUNT_STORE (obj), FALSE /* don't emit the insert signal. */); 
961         }
962         
963         return MODEST_TNY_ACCOUNT_STORE(obj);
964 }
965
966 static void
967 modest_tny_account_store_get_accounts  (TnyAccountStore *self, 
968                                         TnyList *list,
969                                         TnyGetAccountsRequestType request_type)
970 {
971         ModestTnyAccountStorePrivate *priv;
972         
973         g_return_if_fail (self);
974         g_return_if_fail (TNY_IS_LIST(list));
975         
976         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
977         
978         switch (request_type) {
979         case TNY_ACCOUNT_STORE_BOTH:
980                 tny_list_foreach (priv->store_accounts, foreach_account_append_to_list, list);
981                 tny_list_foreach (priv->transport_accounts, foreach_account_append_to_list, list);
982                 break;
983         case TNY_ACCOUNT_STORE_STORE_ACCOUNTS:
984                 tny_list_foreach (priv->store_accounts, foreach_account_append_to_list, list);
985                 break;
986         case TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS:
987                 tny_list_foreach (priv->transport_accounts, foreach_account_append_to_list, list);
988                 break;
989         default:
990                 g_return_if_reached ();
991         }
992
993         /* Initialize session. Why do we need this ??? */
994         tny_session_camel_set_initialized (priv->session);
995 }
996
997
998 static const gchar*
999 modest_tny_account_store_get_cache_dir (TnyAccountStore *self)
1000 {
1001         ModestTnyAccountStorePrivate *priv;
1002         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1003         
1004         if (!priv->cache_dir)
1005                 priv->cache_dir = g_build_filename (g_get_home_dir(), 
1006                                                     MODEST_DIR, MODEST_CACHE_DIR, NULL);
1007         return priv->cache_dir;
1008 }
1009
1010
1011 /*
1012  * callers need to unref
1013  */
1014 static TnyDevice*
1015 modest_tny_account_store_get_device (TnyAccountStore *self)
1016 {
1017         ModestTnyAccountStorePrivate *priv;
1018
1019         g_return_val_if_fail (self, NULL);
1020         
1021         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1022         
1023         if (priv->device) 
1024                 return g_object_ref (G_OBJECT(priv->device));
1025         else
1026                 return NULL;
1027 }
1028
1029
1030 static TnyAccount*
1031 modest_tny_account_store_find_account_by_url (TnyAccountStore *self, const gchar* url_string)
1032 {
1033         return modest_tny_account_store_get_tny_account_by (MODEST_TNY_ACCOUNT_STORE (self), 
1034                                                             MODEST_TNY_ACCOUNT_STORE_QUERY_URL,
1035                                                             url_string);
1036 }
1037
1038
1039
1040 static gboolean
1041 modest_tny_account_store_alert (TnyAccountStore *self, 
1042                                 TnyAccount *account, 
1043                                 TnyAlertType type,
1044                                 gboolean question, 
1045                                 GError *error)
1046 {
1047         ModestProtocolType protocol_type = MODEST_PROTOCOL_REGISTRY_TYPE_INVALID;
1048         ModestProtocol *protocol = NULL;
1049         const gchar* server_name = "";
1050         gchar *prompt = NULL;
1051         gboolean retval = TRUE;
1052
1053         /* NOTE: account may be NULL in some cases */
1054         g_return_val_if_fail (error, FALSE);
1055         
1056         /* Get the server name: */
1057         if (account) {
1058                 server_name = tny_account_get_hostname (account);
1059                 protocol_type = modest_tny_account_get_protocol_type (account);
1060                 if (protocol_type == MODEST_PROTOCOL_REGISTRY_TYPE_INVALID){
1061                         g_warning("modest: %s: account with id=%s has no proto.\n", __FUNCTION__, 
1062                                   tny_account_get_id (account));
1063                         return FALSE;
1064                 }
1065                 protocol = modest_protocol_registry_get_protocol_by_type (modest_runtime_get_protocol_registry (),
1066                                                                           protocol_type);
1067         }
1068
1069         switch (error->code) {
1070         case TNY_SYSTEM_ERROR_CANCEL:
1071                 /* Don't show waste the user's time by showing him a dialog telling 
1072                  * him that he has just cancelled something: */
1073                 return TRUE;
1074
1075         case TNY_SERVICE_ERROR_PROTOCOL:
1076                 /* Like a BAD from IMAP (protocol error) */
1077         case TNY_SERVICE_ERROR_LOST_CONNECTION:
1078                 /* Lost the connection with the service */
1079         case TNY_SERVICE_ERROR_UNAVAILABLE:
1080                 /* You must be working online for this operation */
1081         case TNY_SERVICE_ERROR_CONNECT:
1082                 if (protocol) {
1083                         prompt = modest_protocol_get_translation (protocol, MODEST_PROTOCOL_TRANSLATION_CONNECT_ERROR, server_name);
1084                 }
1085                 if (!prompt) {
1086                         g_return_val_if_reached (FALSE);
1087                 }
1088                 break;
1089                 
1090         case TNY_SERVICE_ERROR_AUTHENTICATE:
1091                 /* It seems that there's no better error to show with
1092                  * POP and IMAP because TNY_SERVICE_ERROR_AUTHENTICATE
1093                  * may appear if there's a timeout during auth */
1094                 if (protocol) {
1095                         prompt = modest_protocol_get_translation (protocol, MODEST_PROTOCOL_TRANSLATION_AUTH_ERROR, server_name);
1096                 }
1097                 if (!prompt) {
1098                         g_return_val_if_reached (FALSE);
1099                 }
1100                 break;
1101                         
1102         case TNY_SERVICE_ERROR_CERTIFICATE:
1103                 /* We'll show the proper dialog later */
1104                 break;
1105
1106         case TNY_SYSTEM_ERROR_MEMORY:
1107                 /* Can't allocate memory for this operation */
1108
1109         case TNY_SERVICE_ERROR_UNKNOWN: 
1110                 return FALSE;
1111         default:
1112                 g_debug ("Unexpected error %d", error->code);
1113                 g_return_val_if_reached (FALSE);
1114         }
1115
1116
1117         if (error->code == TNY_SERVICE_ERROR_CERTIFICATE)
1118                 retval = modest_platform_run_certificate_confirmation_dialog (server_name,
1119                                                                               error->message);
1120         else if (error->code == TNY_SERVICE_ERROR_AUTHENTICATE ||
1121                  error->code == TNY_SERVICE_ERROR_CONNECT) {
1122                 TnyDevice *device = modest_runtime_get_device ();
1123
1124                 modest_platform_run_information_dialog (NULL, prompt, TRUE);
1125
1126                 /* Show the account dialog. Checking the online status
1127                    allows us to minimize the number of times that we
1128                    incorrectly show the dialog */
1129                 if (tny_device_is_online (device))
1130                         show_wrong_password_dialog (account);
1131
1132                 retval = TRUE;
1133         }
1134
1135         g_debug ("%s: error code %d (%s", __FUNCTION__, error->code, error->message);
1136
1137         if (prompt)
1138                 g_free (prompt);
1139
1140         return retval;
1141 }
1142
1143
1144 static void
1145 modest_tny_account_store_init (gpointer g, gpointer iface_data)
1146 {
1147         TnyAccountStoreIface *klass;
1148
1149         g_return_if_fail (g);
1150
1151         klass = (TnyAccountStoreIface *)g;
1152
1153         klass->get_accounts =
1154                 modest_tny_account_store_get_accounts;
1155         klass->get_cache_dir =
1156                 modest_tny_account_store_get_cache_dir;
1157         klass->get_device =
1158                 modest_tny_account_store_get_device;
1159         klass->alert =
1160                 modest_tny_account_store_alert;
1161         klass->find_account =
1162                 modest_tny_account_store_find_account_by_url;
1163 }
1164
1165 void
1166 modest_tny_account_store_set_get_pass_func (ModestTnyAccountStore *self,
1167                                             ModestTnyGetPassFunc func)
1168 {
1169         /* not implemented, we use signals */
1170         g_printerr ("modest: set_get_pass_func not implemented\n");
1171 }
1172
1173 TnySessionCamel*
1174 modest_tny_account_store_get_session  (TnyAccountStore *self)
1175 {
1176         g_return_val_if_fail (self, NULL);
1177         return MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self)->session;
1178 }
1179
1180 static TnyAccount*
1181 get_tny_account_by (TnyList *accounts,
1182                     ModestTnyAccountStoreQueryType type,
1183                     const gchar *str)
1184 {
1185         TnyIterator *iter = NULL;
1186         gboolean found = FALSE;
1187         TnyAccount *retval = NULL;
1188
1189         g_return_val_if_fail (TNY_IS_LIST(accounts), NULL);
1190
1191         if (tny_list_get_length(accounts) == 0) {
1192                 g_warning ("%s: account list is empty", __FUNCTION__);
1193                 return NULL;
1194         }
1195         
1196         iter = tny_list_create_iterator (accounts);
1197         while (!tny_iterator_is_done (iter) && !found) {
1198                 TnyAccount *tmp_account = NULL;
1199                 const gchar *val = NULL;
1200
1201                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1202                 if (!TNY_IS_ACCOUNT(tmp_account)) {
1203                         g_warning ("%s: not a valid account", __FUNCTION__);
1204                         tmp_account = NULL;
1205                         break;
1206                 }
1207
1208                 switch (type) {
1209                 case MODEST_TNY_ACCOUNT_STORE_QUERY_ID:
1210                         val = tny_account_get_id (tmp_account);
1211                         break;
1212                 case MODEST_TNY_ACCOUNT_STORE_QUERY_URL:
1213                         val = tny_account_get_url_string (tmp_account);
1214                         break;
1215                 }
1216                 
1217                 if (type == MODEST_TNY_ACCOUNT_STORE_QUERY_URL && 
1218                     tny_account_matches_url_string (tmp_account, str)) {
1219                         retval = g_object_ref (tmp_account);
1220                         found = TRUE;
1221                 } else {
1222                         if (val && str && strcmp (val, str) == 0) {
1223                                 retval = g_object_ref (tmp_account);
1224                                 found = TRUE;
1225                         }
1226                 }
1227                 g_object_unref (tmp_account);
1228                 tny_iterator_next (iter);
1229         }
1230         g_object_unref (iter);
1231
1232         return retval;
1233 }
1234
1235 TnyAccount*
1236 modest_tny_account_store_get_tny_account_by (ModestTnyAccountStore *self, 
1237                                              ModestTnyAccountStoreQueryType type,
1238                                              const gchar *str)
1239 {
1240         TnyAccount *account = NULL;
1241         ModestTnyAccountStorePrivate *priv;     
1242         
1243         g_return_val_if_fail (self, NULL);
1244         g_return_val_if_fail (str, NULL);
1245         
1246         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1247         
1248         /* Search in store accounts */
1249         account = get_tny_account_by (priv->store_accounts, type, str);
1250
1251         /* If we already found something, no need to search the transport accounts */
1252         if (!account) {
1253                 account = get_tny_account_by (priv->transport_accounts, type, str);
1254
1255                 /* If we already found something, no need to search the
1256                    per-account outbox accounts */
1257                 if (!account)
1258                         account = get_tny_account_by (priv->store_accounts_outboxes, type, str);
1259         }
1260
1261         /* Warn if nothing was found. This is generally unusual. */
1262         if (!account) {
1263                 g_warning("%s: Failed to find account with %s=%s\n", 
1264                           __FUNCTION__, 
1265                           (type == MODEST_TNY_ACCOUNT_STORE_QUERY_ID) ? "ID" : "URL",                     
1266                           str);
1267         }
1268
1269         /* Returns a new reference to the account if found */   
1270         return account;
1271 }
1272
1273
1274 TnyAccount*
1275 modest_tny_account_store_get_server_account (ModestTnyAccountStore *self,
1276                                              const gchar *account_name,
1277                                              TnyAccountType type)
1278 {
1279         ModestTnyAccountStorePrivate *priv = NULL;
1280         TnyAccount *retval = NULL;
1281         TnyList *account_list = NULL;
1282         TnyIterator *iter = NULL;
1283         gboolean found;
1284
1285         g_return_val_if_fail (self, NULL);
1286         g_return_val_if_fail (account_name, NULL);
1287         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || 
1288                               type == TNY_ACCOUNT_TYPE_TRANSPORT,
1289                               NULL);
1290         
1291         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1292
1293         account_list = (type == TNY_ACCOUNT_TYPE_STORE) ? 
1294                 priv->store_accounts : 
1295                 priv->transport_accounts;
1296
1297         if (!account_list) {
1298                 g_printerr ("%s: No server accounts of type %s\n", __FUNCTION__, 
1299                         (type == TNY_ACCOUNT_TYPE_STORE) ? "store" : "transport");
1300                 return NULL;
1301         }
1302         
1303         /* Look for the server account */
1304         found = FALSE;
1305         iter = tny_list_create_iterator (account_list);
1306         while (!tny_iterator_is_done (iter) && !found) {
1307                 const gchar *modest_acc_name;
1308                 TnyAccount *tmp_account;
1309
1310                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1311                 modest_acc_name = 
1312                         modest_tny_account_get_parent_modest_account_name_for_server_account (tmp_account);
1313                 
1314                 if (account_name && modest_acc_name && !strcmp (account_name, modest_acc_name)) {
1315                         found = TRUE;
1316                         retval = g_object_ref (tmp_account);
1317                 }
1318                 /* Free and continue */
1319                 g_object_unref (tmp_account);
1320                 tny_iterator_next (iter);
1321         }
1322         g_object_unref (iter);
1323
1324         if (!found) {
1325                 g_printerr ("modest: %s: could not get tny %s account for %s\n." \
1326                             "Number of server accounts of this type=%d\n", __FUNCTION__,
1327                             (type == TNY_ACCOUNT_TYPE_STORE) ? "store" : "transport",
1328                             account_name, tny_list_get_length (account_list));
1329         }
1330
1331         /* Returns a new reference */
1332         return retval;
1333 }
1334
1335 TnyAccount*
1336 modest_tny_account_store_get_smtp_specific_transport_account_for_open_connection (
1337         ModestTnyAccountStore *self, const gchar *account_name)
1338 {
1339         TnyDevice *device;
1340
1341         g_return_val_if_fail (self && MODEST_IS_TNY_ACCOUNT_STORE(self), NULL);
1342         g_return_val_if_fail (account_name, NULL);
1343
1344         /* Get the current connection: */
1345         device = modest_runtime_get_device ();
1346
1347         if (!device) {
1348                 g_warning ("%s: could not get device", __FUNCTION__);
1349                 return NULL;
1350         }
1351                 
1352         if (!tny_device_is_online (device))
1353                 return NULL;
1354         
1355 #ifdef MODEST_HAVE_CONIC
1356         g_return_val_if_fail (TNY_IS_MAEMO_CONIC_DEVICE (device), NULL);
1357         
1358         TnyMaemoConicDevice *maemo_device = TNY_MAEMO_CONIC_DEVICE (device);    
1359         const gchar* iap_id = tny_maemo_conic_device_get_current_iap_id (maemo_device);
1360         /* printf ("DEBUG: %s: iap_id=%s\n", __FUNCTION__, iap_id); */
1361         if (!iap_id)
1362                 return NULL;
1363                 
1364         ConIcIap* connection = tny_maemo_conic_device_get_iap (maemo_device, iap_id);
1365         if (!connection)
1366                 return NULL;
1367                 
1368         const gchar *connection_id = con_ic_iap_get_id (connection);
1369         /* printf ("DEBUG: %s: connection_id=%s\n", __FUNCTION__, connection_id); */
1370         if (!connection_id)
1371                 return NULL;
1372         
1373         /*  Get the connection-specific transport acccount, if any: */
1374         ModestAccountMgr *account_manager = modest_runtime_get_account_mgr ();
1375
1376         /* Check if this account has connection-specific SMTP enabled */
1377         if (!modest_account_mgr_get_use_connection_specific_smtp (account_manager, account_name)) {
1378                 return NULL;
1379         }
1380
1381         gchar* server_account_name = modest_account_mgr_get_connection_specific_smtp (account_manager, 
1382                 connection_id);
1383
1384         /* printf ("DEBUG: %s: server_account_name=%s\n", __FUNCTION__, server_account_name); */
1385         if (!server_account_name) {
1386                 return NULL; /* No connection-specific SMTP server was specified for this connection. */
1387         }
1388
1389         TnyAccount* account = modest_tny_account_store_get_tny_account_by (self, 
1390                                                                            MODEST_TNY_ACCOUNT_STORE_QUERY_ID, 
1391                                                                            server_account_name);
1392
1393         /* printf ("DEBUG: %s: account=%p\n", __FUNCTION__, account); */
1394         g_free (server_account_name);
1395
1396         /* Unref the get()ed object, as required by the tny_maemo_conic_device_get_iap() documentation. */
1397         g_object_unref (connection);
1398
1399         return account;
1400 #else
1401         return NULL; /* TODO: Implement this for GNOME, instead of just Maemo? */
1402 #endif /* MODEST_HAVE_CONIC */
1403 }
1404
1405                                                                  
1406 TnyAccount*
1407 modest_tny_account_store_get_transport_account_for_open_connection (ModestTnyAccountStore *self,
1408                                                                     const gchar *account_name)
1409 {
1410         g_return_val_if_fail (self, NULL);
1411         g_return_val_if_fail (account_name, NULL);
1412
1413         if (!account_name || !self)
1414                 return NULL;
1415         
1416         /*  Get the connection-specific transport acccount, if any: */
1417         /* Note: This gives us a reference: */
1418         TnyAccount *account =
1419                 modest_tny_account_store_get_smtp_specific_transport_account_for_open_connection (self, account_name);
1420                         
1421         /* If there is no connection-specific transport account (the common case), 
1422          * just get the regular transport account: */
1423         if (!account) {
1424                 /* The special local folders don't have transport accounts. */
1425                 if (strcmp (account_name, MODEST_LOCAL_FOLDERS_ACCOUNT_ID) == 0)
1426                         account = NULL;
1427                 else {
1428                         /* Note: This gives us a reference: */
1429                         account = modest_tny_account_store_get_server_account (self, account_name, 
1430                                                      TNY_ACCOUNT_TYPE_TRANSPORT);
1431                 }
1432         }
1433                         
1434         /* returns a reference. */     
1435         return account;
1436 }
1437
1438 TnyAccount*
1439 modest_tny_account_store_get_local_folders_account (ModestTnyAccountStore *self)
1440 {
1441         TnyAccount *account = NULL;
1442         ModestTnyAccountStorePrivate *priv;
1443         TnyIterator *iter;
1444         gboolean found;
1445
1446         g_return_val_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (self), NULL);
1447         
1448         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1449
1450         found = FALSE;
1451         iter = tny_list_create_iterator (priv->store_accounts);
1452         while (!tny_iterator_is_done (iter) && !found) {
1453                 TnyAccount *tmp_account;
1454
1455                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1456                 if (modest_tny_account_is_virtual_local_folders (tmp_account)) {
1457                         account = g_object_ref (tmp_account);
1458                         found = TRUE;
1459                 }
1460                 g_object_unref (tmp_account);
1461                 tny_iterator_next (iter);
1462         }
1463         g_object_unref (iter);
1464
1465         /* Returns a new reference to the account */
1466         return account;
1467 }
1468
1469 TnyAccount*
1470 modest_tny_account_store_get_mmc_folders_account (ModestTnyAccountStore *self)
1471 {
1472         g_return_val_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (self), NULL);
1473         
1474         /* New reference */
1475         return modest_tny_account_store_get_tny_account_by (self, MODEST_TNY_ACCOUNT_STORE_QUERY_ID,
1476                                                             MODEST_MMC_ACCOUNT_ID);
1477
1478 }
1479
1480 /*********************************************************************************/
1481 static void
1482 add_existing_accounts (ModestTnyAccountStore *self)
1483 {
1484         GSList *account_names = NULL, *iter = NULL;
1485         ModestTnyAccountStorePrivate *priv = NULL;
1486         
1487         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1488
1489         /* These are account names, not server_account names */
1490         account_names = modest_account_mgr_account_names (priv->account_mgr, FALSE);
1491
1492         for (iter = account_names; iter != NULL; iter = g_slist_next (iter)) {
1493                 const gchar *account_name = (const gchar*) iter->data;
1494                 
1495                 /* Insert all enabled accounts without notifying */
1496                 if (modest_account_mgr_get_enabled (priv->account_mgr, account_name))
1497                         insert_account (self, account_name, FALSE);
1498         }
1499         modest_account_mgr_free_account_names (account_names);
1500 }
1501
1502 static TnyAccount*
1503 create_tny_account (ModestTnyAccountStore *self,
1504                     const gchar *name,
1505                     TnyAccountType type,
1506                     gboolean notify)
1507 {
1508         TnyAccount *account = NULL;
1509         ModestTnyAccountStorePrivate *priv = NULL;
1510
1511         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1512
1513         account = modest_tny_account_new_from_account (priv->account_mgr,
1514                                                        name, type, 
1515                                                        priv->session,
1516                                                        get_password,
1517                                                        forget_password);
1518
1519         if (account) {
1520                 /* Forget any cached password for the account, so that
1521                    we use a new account if any */
1522                 forget_password_in_memory (self, tny_account_get_id (account));
1523
1524                 /* Set the account store */
1525                 g_object_set_data (G_OBJECT(account), "account_store", self);
1526         } else {
1527                 g_printerr ("modest: failed to create account for %s\n", name);
1528         }
1529
1530         return account;
1531 }
1532
1533 typedef struct _AddOutboxInfo {
1534         ModestTnyAccountStore *account_store;
1535         TnyAccount *transport_account;
1536 } AddOutboxInfo;
1537
1538 static void
1539 add_outbox_from_transport_account_to_global_outbox_get_folders_cb (TnyFolderStore *folder_store,
1540                                                                    gboolean cancelled,
1541                                                                    TnyList *list,
1542                                                                    GError *err,
1543                                                                    gpointer userdata)
1544 {
1545         TnyIterator *iter_folders;
1546         TnyFolder *per_account_outbox;
1547         TnyAccount *local_account = NULL;
1548         AddOutboxInfo *info = (AddOutboxInfo *) userdata;
1549         ModestTnyAccountStorePrivate *priv = NULL;
1550         ModestTnyAccountStore *self;
1551
1552         self = MODEST_TNY_ACCOUNT_STORE (info->account_store);
1553         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1554         
1555         /* Note that this could happen if there is not enough space
1556            available on disk, then the outbox folder could not be
1557            created */
1558         if (tny_list_get_length (list) != 1) {
1559                 g_warning ("%s: could not create outbox folder (%d folders found)", __FUNCTION__,
1560                            tny_list_get_length (list));
1561                 goto frees;
1562         }
1563                         
1564         iter_folders = tny_list_create_iterator (list);
1565         per_account_outbox = TNY_FOLDER (tny_iterator_get_current (iter_folders));
1566         g_object_unref (iter_folders);
1567         g_object_unref (list);
1568
1569         /* Add the outbox of the new per-account-local-outbox account
1570            to the global local merged OUTBOX of the local folders
1571            account */
1572         local_account = modest_tny_account_store_get_local_folders_account (info->account_store);
1573         modest_tny_local_folders_account_add_folder_to_outbox (MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (local_account),
1574                                                                per_account_outbox);
1575         /* Add the pair to the hash table */
1576         g_hash_table_insert (priv->outbox_of_transport,
1577                              info->transport_account,
1578                              per_account_outbox);
1579         
1580         /* Notify that the local account changed */
1581         g_signal_emit (G_OBJECT (self), signals [ACCOUNT_CHANGED_SIGNAL], 0, local_account);
1582         g_object_unref (local_account);
1583         g_object_unref (per_account_outbox);
1584
1585  frees:
1586         g_object_unref (info->transport_account);
1587         g_slice_free (AddOutboxInfo, info);
1588 }
1589                                                                    
1590
1591 static void
1592 add_outbox_from_transport_account_to_global_outbox (ModestTnyAccountStore *self,
1593                                                     const gchar *account_name,
1594                                                     TnyAccount *transport_account)
1595 {
1596         TnyList *folders = NULL;
1597         TnyAccount *account_outbox = NULL;
1598         ModestTnyAccountStorePrivate *priv = NULL;
1599         AddOutboxInfo *info;
1600
1601         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1602
1603         /* Create per account local outbox */
1604         account_outbox = 
1605                 modest_tny_account_new_for_per_account_local_outbox_folder (priv->account_mgr, 
1606                                                                             account_name, 
1607                                                                             priv->session);
1608
1609         if (!G_IS_OBJECT (account_outbox)) {
1610                 g_warning ("%s: could not create per account local outbox folder", __FUNCTION__);
1611                 return;
1612         }
1613
1614         tny_list_append (priv->store_accounts_outboxes, G_OBJECT (account_outbox));
1615         
1616         /* Get the outbox folder */
1617         folders = tny_simple_list_new ();
1618         info = g_slice_new0 (AddOutboxInfo);
1619         info->account_store = self;
1620         info->transport_account = g_object_ref (transport_account);
1621         tny_folder_store_get_folders_async (TNY_FOLDER_STORE (account_outbox), folders, NULL, FALSE, 
1622                                             add_outbox_from_transport_account_to_global_outbox_get_folders_cb, NULL, (gpointer) info);
1623         g_object_unref (account_outbox);
1624 }
1625
1626 /*
1627  * This function will be used for both adding new accounts and for the
1628  * initialization. In the initialization we do not want to emit
1629  * signals so notify will be FALSE, in the case of account additions
1630  * we do want to notify the observers
1631  */
1632 static void
1633 insert_account (ModestTnyAccountStore *self,
1634                 const gchar *account,
1635                 gboolean notify)
1636 {
1637         ModestTnyAccountStorePrivate *priv = NULL;
1638         TnyAccount *store_account = NULL, *transport_account = NULL;
1639         
1640         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1641
1642         /* Get the server and the transport account */
1643         store_account = create_tny_account (self, account, TNY_ACCOUNT_TYPE_STORE, notify);
1644         if (!store_account || !TNY_IS_ACCOUNT(store_account)) {
1645                 g_warning ("%s: failed to create store account", __FUNCTION__);
1646                 return;
1647         }
1648
1649         transport_account = create_tny_account (self, account, TNY_ACCOUNT_TYPE_TRANSPORT, notify);
1650         if (!transport_account || !TNY_IS_ACCOUNT(transport_account)) {
1651                 g_warning ("%s: failed to create transport account", __FUNCTION__);
1652                 g_object_unref (store_account);
1653                 return;
1654         }
1655
1656         /* Add accounts to the lists */
1657         tny_list_append (priv->store_accounts, G_OBJECT (store_account));
1658         tny_list_append (priv->transport_accounts, G_OBJECT (transport_account));
1659         
1660         /* Create a new pseudo-account with an outbox for this
1661            transport account and add it to the global outbox
1662            in the local account */
1663         add_outbox_from_transport_account_to_global_outbox (self, account, transport_account);  
1664
1665         /* Notify the observers. We do it after everything is
1666            created */
1667         if (notify) {
1668                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_INSERTED_SIGNAL], 0, store_account);   
1669                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_INSERTED_SIGNAL], 0, transport_account);
1670         }
1671
1672         /* Frees */
1673         g_object_unref (store_account);
1674         g_object_unref (transport_account);
1675 }
1676
1677 static inline gboolean
1678 only_local_accounts (ModestTnyAccountStore *self)
1679 {
1680         return (modest_tny_account_store_get_num_remote_accounts (self) > 0) ? FALSE : TRUE;
1681 }
1682
1683 static void
1684 on_account_inserted (ModestAccountMgr *acc_mgr, 
1685                      const gchar *account,
1686                      gpointer user_data)
1687 {
1688         gboolean add_specific;
1689
1690         add_specific = only_local_accounts (MODEST_TNY_ACCOUNT_STORE (user_data));
1691                 
1692         /* Insert the account and notify the observers */
1693         insert_account (MODEST_TNY_ACCOUNT_STORE (user_data), account, TRUE);
1694
1695         /* If it's the first remote account then add the connection
1696            specific SMTP servers as well */
1697         if (add_specific)
1698                 add_connection_specific_transport_accounts (MODEST_TNY_ACCOUNT_STORE (user_data));
1699
1700 }
1701
1702 /* This is the callback of the tny_camel_account_set_online called in
1703    on_account_removed to disconnect the account */
1704 static void
1705 on_account_disconnect_when_removing (TnyCamelAccount *account, 
1706                                      gboolean canceled, 
1707                                      GError *err, 
1708                                      gpointer user_data)
1709 {
1710         ModestTnyAccountStore *self;
1711         ModestTnyAccountStorePrivate *priv;
1712
1713         self = MODEST_TNY_ACCOUNT_STORE (user_data);
1714         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self);
1715
1716         /* Cancel all pending operations */
1717         tny_account_cancel (TNY_ACCOUNT (account));
1718         
1719         /* Unref the extra reference added by get_server_account */
1720         g_object_unref (account);
1721
1722         /* Clear the cache if it's an store account */
1723         if (TNY_IS_STORE_ACCOUNT (account)) {
1724                 tny_store_account_delete_cache (TNY_STORE_ACCOUNT (account));
1725         } else if (TNY_IS_TRANSPORT_ACCOUNT (account)) {
1726                 ModestTnySendQueue* send_queue;
1727                 send_queue = modest_runtime_get_send_queue (TNY_TRANSPORT_ACCOUNT (account), FALSE);
1728                 if (TNY_IS_SEND_QUEUE (send_queue)) {
1729                         if (modest_tny_send_queue_sending_in_progress (send_queue))
1730                                 tny_send_queue_cancel (TNY_SEND_QUEUE (send_queue),
1731                                                        TNY_SEND_QUEUE_CANCEL_ACTION_REMOVE, 
1732                                                        NULL);
1733                         modest_runtime_remove_send_queue (TNY_TRANSPORT_ACCOUNT (account));
1734                 }
1735         }
1736 }
1737
1738 /*
1739  * We use this one for both removing "normal" and "connection
1740  * specific" transport accounts
1741  */
1742 static void
1743 remove_transport_account (ModestTnyAccountStore *self,
1744                           TnyTransportAccount *transport_account)
1745 {
1746         ModestTnyAccountStorePrivate *priv;
1747         TnyFolder *outbox = NULL;
1748         
1749         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self);
1750
1751         /* Remove it from the list of accounts and notify the
1752            observers. Do not need to wait for account
1753            disconnection */
1754         g_signal_emit (G_OBJECT (self), signals [ACCOUNT_REMOVED_SIGNAL], 0, transport_account);
1755         tny_list_remove (priv->transport_accounts, (GObject *) transport_account);
1756                 
1757         /* Remove the OUTBOX of the account from the global outbox */
1758         outbox = g_hash_table_lookup (priv->outbox_of_transport, transport_account);
1759
1760         if (TNY_IS_FOLDER (outbox)) {
1761                 TnyAccount *local_account = NULL;
1762                 TnyAccount *outbox_account = tny_folder_get_account (outbox);
1763
1764                 if (outbox_account) {
1765                         tny_list_remove (priv->store_accounts_outboxes, G_OBJECT (outbox_account));
1766                         /* Remove existing emails to send */
1767                         tny_store_account_delete_cache (TNY_STORE_ACCOUNT (outbox_account));
1768                         g_object_unref (outbox_account);
1769                 }
1770
1771                 local_account = modest_tny_account_store_get_local_folders_account (self);
1772                 modest_tny_local_folders_account_remove_folder_from_outbox (MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (local_account),
1773                                                                             outbox);
1774
1775                 g_hash_table_remove (priv->outbox_of_transport, transport_account);
1776
1777                 /* Notify the change in the local account */
1778                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_CHANGED_SIGNAL], 0, local_account);
1779                 g_object_unref (local_account);
1780         } else {
1781                 g_warning ("Removing a transport account that has no outbox");
1782         }
1783
1784         /* Cancel all pending operations */
1785         tny_account_cancel (TNY_ACCOUNT (transport_account));
1786
1787         /* Disconnect and notify the observers. The callback will free the reference */
1788         tny_camel_account_set_online (TNY_CAMEL_ACCOUNT (transport_account), FALSE,
1789                                       on_account_disconnect_when_removing, self);
1790 }
1791
1792 static gboolean
1793 images_cache_remove_filter (TnyStreamCache *self, const gchar *id, const gchar *account_name)
1794 {
1795         gchar *account_name_with_separator;
1796         gboolean result;
1797         if (account_name == NULL || account_name[0] == '\0')
1798                 return FALSE;
1799
1800         if (id == NULL || id[0] == '\0')
1801                 return FALSE;
1802
1803         account_name_with_separator = g_strconcat (account_name, "__", NULL);
1804
1805         result = (g_str_has_prefix (id, account_name));
1806         g_free (account_name_with_separator);
1807
1808         return result;
1809 }
1810
1811 static void
1812 on_account_removed (ModestAccountMgr *acc_mgr, 
1813                     const gchar *account,
1814                     gpointer user_data)
1815 {
1816         TnyAccount *store_account = NULL, *transport_account = NULL;
1817         ModestTnyAccountStore *self;
1818         ModestTnyAccountStorePrivate *priv;
1819         TnyStreamCache *stream_cache;
1820         
1821         self = MODEST_TNY_ACCOUNT_STORE (user_data);
1822         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self);
1823
1824         /* Get the server and the transport account */
1825         store_account = 
1826                 modest_tny_account_store_get_server_account (self, account, 
1827                                                              TNY_ACCOUNT_TYPE_STORE);
1828         transport_account = 
1829                 modest_tny_account_store_get_server_account (self, account,
1830                                                              TNY_ACCOUNT_TYPE_TRANSPORT);
1831         
1832         /* If there was any problem creating the account, for example,
1833            with the configuration system this could not exist */
1834         if (TNY_IS_STORE_ACCOUNT(store_account)) {
1835                 /* Forget any cached password for the account */
1836                 forget_password_in_memory (self, tny_account_get_id (store_account));
1837
1838                 /* Remove it from the list of accounts and notify the
1839                    observers. Do not need to wait for account
1840                    disconnection */
1841                 tny_list_remove (priv->store_accounts, (GObject *) store_account);
1842                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_REMOVED_SIGNAL], 0, store_account);
1843
1844                 /* Cancel all pending operations */
1845                 tny_account_cancel (TNY_ACCOUNT (store_account));
1846
1847                 /* Disconnect before deleting the cache, because the
1848                    disconnection will rewrite the cache to the
1849                    disk */
1850                 tny_camel_account_set_online (TNY_CAMEL_ACCOUNT (store_account), FALSE,
1851                                               on_account_disconnect_when_removing, self);
1852         } else {
1853                 g_warning ("%s: no store account for account %s\n", 
1854                            __FUNCTION__, account);
1855         }
1856
1857         /* If there was any problem creating the account, for example,
1858            with the configuration system this could not exist */
1859         if (TNY_IS_TRANSPORT_ACCOUNT(transport_account)) {
1860
1861                 /* Forget any cached password for the account */
1862                 forget_password_in_memory (self, tny_account_get_id (transport_account));
1863
1864                 /* Remove transport account. It'll free the reference
1865                    added by get_server_account */
1866                 remove_transport_account (self, TNY_TRANSPORT_ACCOUNT (transport_account));
1867         } else {
1868                 g_warning ("%s: no transport account for account %s\n", 
1869                            __FUNCTION__, account);
1870         }
1871
1872         /* Remove cached images */
1873         stream_cache = modest_runtime_get_images_cache ();
1874         tny_stream_cache_remove (stream_cache, (TnyStreamCacheRemoveFilter) images_cache_remove_filter, (gpointer) account);
1875
1876         /* If there are no more user accounts then delete the
1877            transport specific SMTP servers */
1878         if (only_local_accounts (self))
1879                 remove_connection_specific_transport_accounts (self);
1880 }
1881
1882 TnyTransportAccount *
1883 modest_tny_account_store_new_connection_specific_transport_account (ModestTnyAccountStore *self,
1884                                                                     const gchar *name)
1885 {
1886         ModestTnyAccountStorePrivate *priv = NULL;
1887         TnyAccount * tny_account = NULL;
1888
1889         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1890
1891         /* Add the account: */
1892         tny_account = 
1893                 modest_tny_account_new_from_server_account_name (priv->account_mgr, 
1894                                                                  priv->session, 
1895                                                                  name,
1896                                                                  get_password,
1897                                                                  forget_password);
1898         if (tny_account) {
1899                 g_object_set_data (G_OBJECT(tny_account), 
1900                                    "account_store", 
1901                                    (gpointer)self);
1902                 g_object_set_data (G_OBJECT(tny_account), 
1903                                    "connection_specific", 
1904                                    GINT_TO_POINTER (TRUE));
1905                 
1906                 tny_list_append (priv->transport_accounts, G_OBJECT (tny_account));
1907                 add_outbox_from_transport_account_to_global_outbox (self, 
1908                                                                     name, 
1909                                                                     tny_account);
1910                 
1911         } else
1912                 g_printerr ("modest: failed to create smtp-specific account for %s\n",
1913                             name);
1914
1915         return TNY_TRANSPORT_ACCOUNT (tny_account);
1916 }
1917
1918 static void 
1919 foreach_free_string(gpointer data,
1920                     gpointer user_data)
1921 {
1922         g_free (data);
1923 }
1924
1925 static void
1926 add_connection_specific_transport_accounts (ModestTnyAccountStore *self)
1927 {
1928         ModestTnyAccountStorePrivate *priv = NULL;
1929         GSList *list_specifics = NULL, *iter = NULL;
1930         GError *err = NULL;
1931
1932         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1933
1934         list_specifics = modest_conf_get_list (modest_runtime_get_conf (),
1935                                                MODEST_CONF_CONNECTION_SPECIFIC_SMTP_LIST,
1936                                                MODEST_CONF_VALUE_STRING, &err);
1937         if (err) {
1938                 g_error_free (err);
1939                 g_return_if_reached ();
1940                 return;
1941         }
1942                                 
1943         /* Look at each connection-specific transport account for the 
1944          * modest account: */
1945         iter = list_specifics;
1946         while (iter) {
1947                 /* The list alternates between the connection name and the transport name: */
1948                 iter = g_slist_next (iter);
1949                 if (iter) {
1950                         const gchar* transport_account_name = (const gchar*) (iter->data);
1951                         TnyTransportAccount * account = NULL;
1952                         account = modest_tny_account_store_new_connection_specific_transport_account (
1953                                 self, transport_account_name);
1954                         if (account)
1955                                 g_object_unref (account);
1956                 }                               
1957                 iter = g_slist_next (iter);
1958         }
1959
1960         /* Free the list */
1961         g_slist_foreach (list_specifics, foreach_free_string, NULL);
1962         g_slist_free (list_specifics);
1963 }
1964
1965 static void
1966 remove_connection_specific_transport_accounts (ModestTnyAccountStore *self)
1967 {
1968         ModestTnyAccountStorePrivate *priv = NULL;
1969         GSList *list_specifics = NULL, *iter = NULL;
1970         GError *err = NULL;
1971
1972         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1973
1974         err = NULL;
1975         list_specifics = modest_conf_get_list (modest_runtime_get_conf (),
1976                                                MODEST_CONF_CONNECTION_SPECIFIC_SMTP_LIST,
1977                                                MODEST_CONF_VALUE_STRING, &err);
1978         if (err) {
1979                 g_error_free (err);
1980                 g_return_if_reached ();
1981                 return;
1982         }
1983                                 
1984         /* Look at each connection-specific transport account for the 
1985          * modest account: */
1986         iter = list_specifics;
1987         while (iter) {
1988                 /* The list alternates between the connection name and the transport name: */
1989                 iter = g_slist_next (iter);
1990                 if (iter) {
1991                         const gchar* transport_account_name = (const gchar*) (iter->data);
1992                         TnyAccount * account;
1993                         account = modest_tny_account_store_get_server_account (self,
1994                                                                                transport_account_name,
1995                                                                                TNY_ACCOUNT_TYPE_TRANSPORT);
1996
1997                         /* the call will free the reference */
1998                         if (account)
1999                                 remove_transport_account (self, TNY_TRANSPORT_ACCOUNT (account));
2000                 }                               
2001                 iter = g_slist_next (iter);
2002         }
2003
2004         /* Free the list */
2005         g_slist_foreach (list_specifics, foreach_free_string, NULL);
2006         g_slist_free (list_specifics);
2007 }
2008
2009
2010 TnyMsg *
2011 modest_tny_account_store_find_msg_in_outboxes (ModestTnyAccountStore *self, 
2012                                                const gchar *uri,
2013                                                TnyAccount **ac_out)
2014 {
2015         TnyIterator *acc_iter;
2016         ModestTnyAccountStorePrivate *priv;
2017         TnyMsg *msg = NULL;
2018         TnyAccount *msg_account = NULL;
2019
2020         g_return_val_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (self), NULL);
2021         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self);
2022
2023         acc_iter = tny_list_create_iterator (priv->store_accounts_outboxes);
2024         while (!msg && !tny_iterator_is_done (acc_iter)) {
2025                 TnyList *folders = tny_simple_list_new ();
2026                 TnyAccount *account = TNY_ACCOUNT (tny_iterator_get_current (acc_iter));
2027                 TnyIterator *folders_iter = NULL;
2028
2029                 tny_folder_store_get_folders (TNY_FOLDER_STORE (account), folders, NULL, FALSE, NULL);
2030                 folders_iter = tny_list_create_iterator (folders);
2031
2032                 while (msg == NULL && !tny_iterator_is_done (folders_iter)) {
2033                         TnyFolder *folder = TNY_FOLDER (tny_iterator_get_current (folders_iter));
2034                         msg = tny_folder_find_msg (folder, uri, NULL);
2035
2036                         if (msg)
2037                                 msg_account = g_object_ref (account);
2038
2039                         g_object_unref (folder);
2040                         tny_iterator_next (folders_iter);
2041                 }
2042                 g_object_unref (folders_iter);
2043
2044                 g_object_unref (folders);
2045                 g_object_unref (account);
2046                 tny_iterator_next (acc_iter);
2047         }
2048
2049         g_object_unref (acc_iter);
2050
2051         if (ac_out != NULL)
2052                 *ac_out = msg_account;
2053
2054         return msg;
2055 }
2056
2057 TnyTransportAccount *
2058 modest_tny_account_store_get_transport_account_from_outbox_header(ModestTnyAccountStore *self, TnyHeader *header)
2059 {
2060         TnyIterator *acc_iter;
2061         ModestTnyAccountStorePrivate *priv;
2062         TnyTransportAccount *header_acc = NULL;
2063         gchar *msg_id;
2064
2065         g_return_val_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (self), NULL);
2066         g_return_val_if_fail (TNY_IS_HEADER (header), NULL);
2067         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self);
2068         msg_id = modest_tny_send_queue_get_msg_id (header);
2069         acc_iter = tny_list_create_iterator (priv->transport_accounts);
2070         while (!header_acc && !tny_iterator_is_done (acc_iter)) {
2071                 TnyTransportAccount *account = TNY_TRANSPORT_ACCOUNT (tny_iterator_get_current (acc_iter));
2072                 ModestTnySendQueue *send_queue;
2073                 ModestTnySendQueueStatus status;
2074                 send_queue = modest_runtime_get_send_queue(TNY_TRANSPORT_ACCOUNT(account), TRUE);
2075                 if (TNY_IS_SEND_QUEUE (send_queue)) {
2076                         status = modest_tny_send_queue_get_msg_status(send_queue, msg_id);
2077                         if (status != MODEST_TNY_SEND_QUEUE_UNKNOWN)
2078                                 header_acc = g_object_ref(account);
2079                 }
2080                 g_object_unref (account);
2081                 tny_iterator_next (acc_iter);
2082         }
2083         g_object_unref(acc_iter);
2084         g_free (msg_id);
2085
2086         /* New reference */
2087         return header_acc;
2088 }
2089
2090 typedef struct {
2091         ModestTnyAccountStore *account_store;
2092         ModestTnyAccountStoreShutdownCallback callback;
2093         gpointer userdata;
2094         gint pending;
2095 } ShutdownOpData;
2096
2097 static void
2098 account_shutdown_callback (TnyCamelAccount *account, gboolean canceled, GError *err, gpointer userdata)
2099 {
2100         ShutdownOpData *op_data = (ShutdownOpData *) userdata;
2101         op_data->pending--;
2102         if (op_data->pending == 0) {
2103                 if (op_data->callback)
2104                         op_data->callback (op_data->account_store, op_data->userdata);
2105                 g_object_unref (op_data->account_store);
2106                 g_free (op_data);
2107         } else {
2108                 g_object_unref (op_data->account_store);
2109         }
2110 }
2111
2112 static void
2113 account_shutdown (TnyAccount *account, ShutdownOpData *op_data)
2114 {
2115         g_return_if_fail (account && TNY_IS_ACCOUNT(account));
2116
2117         if (TNY_IS_STORE_ACCOUNT (account) && 
2118             !modest_tny_folder_store_is_remote (TNY_FOLDER_STORE (account)))
2119                 goto frees;
2120
2121         /* Disconnect account */
2122         if (tny_account_get_connection_status (account) == TNY_CONNECTION_STATUS_CONNECTED) {
2123                 tny_camel_account_set_online (TNY_CAMEL_ACCOUNT(account), FALSE, 
2124                                               account_shutdown_callback, op_data);
2125                 return;
2126         }
2127
2128  frees:
2129         op_data->pending--;
2130         g_object_unref (op_data->account_store);
2131 }
2132
2133
2134 void
2135 modest_tny_account_store_shutdown (ModestTnyAccountStore *self,
2136                                    ModestTnyAccountStoreShutdownCallback callback,
2137                                    gpointer userdata)
2138 {
2139         gint i, num_accounts;
2140         ShutdownOpData *op_data;
2141         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self);
2142
2143         /* Get references */
2144         num_accounts = 0;
2145         if (priv->store_accounts)
2146                 num_accounts += tny_list_get_length (priv->store_accounts);
2147         if (priv->transport_accounts)
2148                 num_accounts += tny_list_get_length (priv->transport_accounts);
2149
2150         for (i = 0 ; i < num_accounts ; i++)
2151                 g_object_ref (self);
2152
2153         /* Create the helper object */
2154         op_data = g_new0 (ShutdownOpData, 1);
2155         op_data->callback = callback;
2156         op_data->userdata = userdata;
2157         op_data->pending = num_accounts;
2158         op_data->account_store = self;
2159
2160         /* Destroy all accounts. Disconnect all accounts before they are destroyed */
2161         if (priv->store_accounts) {
2162                 tny_list_foreach (priv->store_accounts, (GFunc)account_shutdown, op_data);
2163         }
2164
2165         if (priv->transport_accounts) {
2166                 tny_list_foreach (priv->transport_accounts, (GFunc)account_shutdown, op_data);
2167         }
2168
2169         if (op_data->pending == 0) {
2170                 if (op_data->callback)
2171                         op_data->callback (op_data->account_store, op_data->userdata);
2172                 g_free (op_data);
2173         }
2174 }
2175
2176 gboolean 
2177 modest_tny_account_store_is_send_mail_blocked (ModestTnyAccountStore *self)
2178 {
2179         ModestTnyAccountStorePrivate *priv;
2180
2181         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
2182
2183         return priv->send_mail_blocked;
2184 }
2185
2186 void 
2187 modest_tny_account_store_set_send_mail_blocked (ModestTnyAccountStore *self, 
2188                                                 gboolean blocked)
2189 {
2190         ModestTnyAccountStorePrivate *priv;
2191
2192         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
2193
2194         priv->send_mail_blocked = blocked;
2195 }
2196
2197 static void
2198 count_remote_accounts (gpointer data, gpointer user_data)
2199 {
2200         TnyFolderStore *account = TNY_FOLDER_STORE (data);
2201         gint *count = (gint *) user_data;
2202
2203         if (modest_tny_folder_store_is_remote (account))
2204                 (*count)++;
2205 }
2206
2207 guint
2208 modest_tny_account_store_get_num_remote_accounts (ModestTnyAccountStore *self)
2209 {
2210         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self);
2211         gint count = 0;
2212
2213         /* Count remote accounts */
2214         tny_list_foreach (priv->store_accounts, (GFunc) count_remote_accounts, &count);
2215
2216         return count;
2217 }