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