78a67d4d93872a32cc8a76692e7e767a5b4cbc21
[modest] / src / modest-tny-account-store.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <string.h>
31 #include <glib/gi18n.h>
32
33 #include <tny-account.h>
34 #include <tny-account-store.h>
35 #include <tny-store-account.h>
36 #include <tny-error.h>
37 #include <tny-transport-account.h>
38 #include <tny-simple-list.h>
39 #include <tny-account-store.h>
40 #include <tny-camel-transport-account.h>
41 #include <tny-camel-imap-store-account.h>
42 #include <tny-camel-pop-store-account.h>
43
44 #include <modest-runtime.h>
45 #include <modest-marshal.h>
46 #include <modest-protocol-info.h>
47 #include <modest-local-folder-info.h>
48 #include <modest-tny-account.h>
49 #include <modest-tny-local-folders-account.h>
50 #include <modest-account-mgr.h>
51 #include <modest-account-mgr-helpers.h>
52 #include <widgets/modest-window-mgr.h>
53 #include <modest-account-settings-dialog.h>
54 #include <maemo/modest-maemo-utils.h>
55
56
57 #include "modest-tny-account-store.h"
58 #include "modest-tny-platform-factory.h"
59 #include <tny-gtk-lockable.h>
60 #include <camel/camel.h>
61
62 #ifdef MODEST_PLATFORM_MAEMO
63 #include <tny-maemo-conic-device.h>
64 #ifdef MODEST_HAVE_HILDON0_WIDGETS
65 #include <hildon-widgets/hildon-note.h>
66 #include <hildon-widgets/hildon-banner.h>
67 #else
68 #include <hildon/hildon-note.h>
69 #include <hildon/hildon-banner.h>
70 #endif
71 #endif
72
73 #include <libgnomevfs/gnome-vfs-volume-monitor.h>
74
75 /* 'private'/'protected' functions */
76 static void    modest_tny_account_store_class_init   (ModestTnyAccountStoreClass *klass);
77
78 static void    modest_tny_account_store_finalize     (GObject *obj);
79
80 static void    modest_tny_account_store_instance_init (ModestTnyAccountStore *obj);
81
82 static void    modest_tny_account_store_init          (gpointer g, gpointer iface_data);
83
84 static void    modest_tny_account_store_base_init     (gpointer g_class);
85
86 static void    on_account_inserted         (ModestAccountMgr *acc_mgr, 
87                                             const gchar *account,
88                                             gpointer user_data);
89
90 static void    add_existing_accounts       (ModestTnyAccountStore *self);
91
92 static void    insert_account              (ModestTnyAccountStore *self,
93                                             const gchar *account,
94                                             gboolean notify);
95
96 static void    on_account_removed          (ModestAccountMgr *acc_mgr, 
97                                             const gchar *account,
98                                             gpointer user_data);
99
100 static gchar*  get_password                (TnyAccount *account, 
101                                             const gchar * prompt_not_used, 
102                                             gboolean *cancel);
103
104 static void    forget_password             (TnyAccount *account);
105
106 static void    on_vfs_volume_mounted       (GnomeVFSVolumeMonitor *volume_monitor, 
107                                             GnomeVFSVolume *volume, 
108                                             gpointer user_data);
109
110 static void    on_vfs_volume_unmounted     (GnomeVFSVolumeMonitor *volume_monitor, 
111                                             GnomeVFSVolume *volume, 
112                                             gpointer user_data);
113
114 static void    modest_tny_account_store_forget_password_in_memory (ModestTnyAccountStore *self, 
115                                                                    const gchar *server_account_name);
116
117 static void    add_connection_specific_transport_accounts         (ModestTnyAccountStore *self,
118                                                                    const gchar *account_name);
119
120 /* list my signals */
121 enum {
122         ACCOUNT_CHANGED_SIGNAL,
123         ACCOUNT_INSERTED_SIGNAL,
124         ACCOUNT_REMOVED_SIGNAL,
125
126         PASSWORD_REQUESTED_SIGNAL,
127         LAST_SIGNAL
128 };
129
130 typedef struct _ModestTnyAccountStorePrivate ModestTnyAccountStorePrivate;
131 struct _ModestTnyAccountStorePrivate {
132         gchar              *cache_dir;  
133         GHashTable         *password_hash;
134         GHashTable         *account_settings_dialog_hash;
135         ModestAccountMgr   *account_mgr;
136         TnySessionCamel    *session;
137         TnyDevice          *device;
138
139         gulong acc_inserted_handler;
140         gulong acc_changed_handler;
141         gulong acc_removed_handler;
142         gulong volume_mounted_handler;
143         gulong volume_unmounted_handler;
144         
145         /* We cache the lists of accounts here */
146         TnyList             *store_accounts;
147         TnyList             *transport_accounts;
148         TnyList             *store_accounts_outboxes;
149 };
150
151 #define MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
152                                                       MODEST_TYPE_TNY_ACCOUNT_STORE, \
153                                                       ModestTnyAccountStorePrivate))
154
155 /* globals */
156 static GObjectClass *parent_class = NULL;
157
158 static guint signals[LAST_SIGNAL] = {0};
159
160 GType
161 modest_tny_account_store_get_type (void)
162 {
163         static GType my_type = 0;
164
165         if (!my_type) {
166                 static const GTypeInfo my_info = {
167                         sizeof(ModestTnyAccountStoreClass),
168                         modest_tny_account_store_base_init,     /* base init */
169                         NULL,           /* base finalize */
170                         (GClassInitFunc) modest_tny_account_store_class_init,
171                         NULL,           /* class finalize */
172                         NULL,           /* class data */
173                         sizeof(ModestTnyAccountStore),
174                         0,              /* n_preallocs */
175                         (GInstanceInitFunc) modest_tny_account_store_instance_init,
176                         NULL
177                 };
178
179                 static const GInterfaceInfo iface_info = {
180                         (GInterfaceInitFunc) modest_tny_account_store_init,
181                         NULL,         /* interface_finalize */
182                         NULL          /* interface_data */
183                 };
184                 /* hack hack */
185                 my_type = g_type_register_static (G_TYPE_OBJECT,
186                                                   "ModestTnyAccountStore",
187                                                   &my_info, 0);
188                 g_type_add_interface_static (my_type, TNY_TYPE_ACCOUNT_STORE,
189                                              &iface_info);
190         }
191         return my_type;
192 }
193
194
195 static void
196 modest_tny_account_store_base_init (gpointer g_class)
197 {
198         static gboolean tny_account_store_initialized = FALSE;
199
200         if (!tny_account_store_initialized) {
201
202                 signals[ACCOUNT_CHANGED_SIGNAL] =
203                         g_signal_new ("account_changed",
204                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
205                                       G_SIGNAL_RUN_FIRST,
206                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_changed),
207                                       NULL, NULL,
208                                       g_cclosure_marshal_VOID__OBJECT,
209                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
210
211                 signals[ACCOUNT_INSERTED_SIGNAL] =
212                         g_signal_new ("account_inserted",
213                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
214                                       G_SIGNAL_RUN_FIRST,
215                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_inserted),
216                                       NULL, NULL,
217                                       g_cclosure_marshal_VOID__OBJECT,
218                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
219                 
220                 signals[ACCOUNT_REMOVED_SIGNAL] =
221                         g_signal_new ("account_removed",
222                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
223                                       G_SIGNAL_RUN_FIRST,
224                                       G_STRUCT_OFFSET (ModestTnyAccountStoreClass, account_removed),
225                                       NULL, NULL,
226                                       g_cclosure_marshal_VOID__OBJECT,
227                                       G_TYPE_NONE, 1, TNY_TYPE_ACCOUNT);
228                 
229 /*              signals[TNY_ACCOUNT_STORE_CONNECTING_FINISHED] = */
230 /*                      g_signal_new ("connecting_finished", */
231 /*                                    TNY_TYPE_ACCOUNT_STORE, */
232 /*                                    G_SIGNAL_RUN_FIRST, */
233 /*                                    G_STRUCT_OFFSET (TnyAccountStoreIface, connecting_finished), */
234 /*                                    NULL, NULL, */
235 /*                                    g_cclosure_marshal_VOID__VOID,  */
236 /*                                    G_TYPE_NONE, 0); */
237
238                 signals[PASSWORD_REQUESTED_SIGNAL] =
239                         g_signal_new ("password_requested",
240                                       MODEST_TYPE_TNY_ACCOUNT_STORE,
241                                       G_SIGNAL_RUN_FIRST,
242                                       G_STRUCT_OFFSET(ModestTnyAccountStoreClass, password_requested),
243                                       NULL, NULL,
244                                       modest_marshal_VOID__STRING_POINTER_POINTER_POINTER_POINTER,
245                                       G_TYPE_NONE, 5, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_POINTER, G_TYPE_POINTER,
246                                       G_TYPE_POINTER);          
247
248                 tny_account_store_initialized = TRUE;
249         }
250 }
251
252
253 static void
254 modest_tny_account_store_class_init (ModestTnyAccountStoreClass *klass)
255 {
256         GObjectClass *gobject_class;
257         gobject_class = (GObjectClass*) klass;
258
259         parent_class            = g_type_class_peek_parent (klass);
260         gobject_class->finalize = modest_tny_account_store_finalize;
261
262         g_type_class_add_private (gobject_class,
263                                   sizeof(ModestTnyAccountStorePrivate));
264 }
265      
266 static void
267 modest_tny_account_store_instance_init (ModestTnyAccountStore *obj)
268 {
269         GnomeVFSVolumeMonitor* monitor = NULL;
270         ModestTnyAccountStorePrivate *priv;
271
272         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
273
274         priv->cache_dir              = NULL;
275         priv->account_mgr            = NULL;
276         priv->session                = NULL;
277         priv->device                 = NULL;
278         
279         /* An in-memory store of passwords, 
280          * for passwords that are not remembered in the configuration,
281          * so they need to be asked for from the user once in each session:
282          */
283         priv->password_hash = g_hash_table_new_full (g_str_hash, g_str_equal,
284                                                      g_free, g_free);
285                                                              
286         /* A hash-map of modest account names to dialog pointers,
287          * so we can avoid showing the account settings twice for the same modest account: */                                 
288         priv->account_settings_dialog_hash = g_hash_table_new_full (g_str_hash, g_str_equal, 
289                                                                     g_free, NULL);
290                                                               
291         /* Respond to volume mounts and unmounts, such 
292          * as the insertion/removal of the memory card: */
293         monitor = gnome_vfs_get_volume_monitor();
294
295         priv->volume_mounted_handler = g_signal_connect (G_OBJECT(monitor), 
296                                                          "volume-mounted",
297                                                          G_CALLBACK(on_vfs_volume_mounted),
298                                                          obj);
299
300         priv->volume_unmounted_handler = g_signal_connect (G_OBJECT(monitor), "volume-unmounted",
301                                                            G_CALLBACK(on_vfs_volume_unmounted),
302                                                            obj);
303 }
304
305 /* disconnect the list of TnyAccounts */
306 static void
307 foreach_account_disconnect (gpointer data, 
308                             gpointer user_data)
309 {
310         tny_camel_account_set_online (TNY_CAMEL_ACCOUNT(data), FALSE, NULL);
311 }
312
313
314 static void
315 foreach_account_append_to_list (gpointer data, 
316                                 gpointer user_data)
317 {
318         TnyList *list;
319
320         list = TNY_LIST (user_data);
321         tny_list_append (list, G_OBJECT (data));
322 }
323
324 /********************************************************************/
325 /*           Control the state of the MMC local account             */
326 /********************************************************************/
327 static void
328 on_vfs_volume_mounted(GnomeVFSVolumeMonitor *volume_monitor, 
329                       GnomeVFSVolume *volume, 
330                       gpointer user_data)
331 {
332         ModestTnyAccountStore *self;
333         ModestTnyAccountStorePrivate *priv;
334  
335         gchar *uri = NULL;
336
337         self = MODEST_TNY_ACCOUNT_STORE(user_data);
338         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
339         
340         /* Check whether this was the external MMC1 card: */
341         uri = gnome_vfs_volume_get_activation_uri (volume);
342
343         if (uri && (!strcmp (uri, MODEST_MCC1_VOLUMEPATH_URI))) {
344                 TnyAccount *mmc_account;
345
346                 mmc_account = modest_tny_account_new_for_local_folders (priv->account_mgr, 
347                                                                         priv->session, 
348                                                                         MODEST_MCC1_VOLUMEPATH);
349
350                 /* Add to the list of store accounts */
351                 tny_list_append (priv->store_accounts, G_OBJECT (mmc_account));
352
353                 g_signal_emit (G_OBJECT (self), 
354                                signals [ACCOUNT_INSERTED_SIGNAL],
355                                0, mmc_account);
356                 /* Free */
357                 g_object_unref (mmc_account);
358         }
359         g_free (uri);
360 }
361
362 static void
363 on_vfs_volume_unmounted(GnomeVFSVolumeMonitor *volume_monitor, 
364                         GnomeVFSVolume *volume, 
365                         gpointer user_data)
366 {
367         ModestTnyAccountStore *self;
368         ModestTnyAccountStorePrivate *priv;
369         gchar *uri = NULL;
370
371         self = MODEST_TNY_ACCOUNT_STORE(user_data);
372         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
373         
374         /* Check whether this was the external MMC1 card: */
375         uri = gnome_vfs_volume_get_activation_uri (volume);
376         if (uri && (strcmp (uri, MODEST_MCC1_VOLUMEPATH_URI) == 0)) {
377                 TnyAccount *mmc_account = NULL;
378                 gboolean found = FALSE;
379                 TnyIterator *iter = NULL;
380
381                 iter = tny_list_create_iterator (priv->store_accounts);
382                 while (!tny_iterator_is_done (iter) && !found) {
383                         TnyAccount *account;
384
385                         account = TNY_ACCOUNT (tny_iterator_get_current (iter));
386                         if (modest_tny_account_is_memory_card_account (account)) {
387                                 found = TRUE;
388                                 mmc_account = g_object_ref (account);
389                         }
390                         g_object_unref (account);
391                         tny_iterator_next (iter);
392                 }
393                 g_object_unref (iter);
394
395                 if (found) {
396                         /* Remove from the list */
397                         tny_list_remove (priv->store_accounts, G_OBJECT (mmc_account));
398                        
399                         /* Notify observers */
400                         g_signal_emit (G_OBJECT (self),
401                                        signals [ACCOUNT_REMOVED_SIGNAL],
402                                        0, mmc_account);
403
404                         g_object_unref (mmc_account);
405                 } else {
406                         g_warning ("%s: there was no store account for the unmounted MMC",
407                                    __FUNCTION__);
408                 }
409         }
410         g_free (uri);
411 }
412
413 /**
414  * modest_tny_account_store_forget_password_in_memory
415  * @self: a TnyAccountStore instance
416  * @account: A server account.
417  * 
418  * Forget any password stored in memory for this account.
419  * For instance, this should be called when the user has changed the password in the account settings.
420  */
421 static void
422 modest_tny_account_store_forget_password_in_memory (ModestTnyAccountStore *self, const gchar * server_account_name)
423 {
424         /* printf ("DEBUG: %s\n", __FUNCTION__); */
425         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
426
427         if (server_account_name && priv->password_hash) {
428                 g_hash_table_remove (priv->password_hash, server_account_name);
429         }
430 }
431
432 static void
433 on_account_changed (ModestAccountMgr *acc_mgr, 
434                     const gchar *account,
435                     const GSList *keys, 
436                     gboolean server_account, 
437                     gpointer user_data)
438 {
439         printf ("DEBUG: modest: %s\n", __FUNCTION__);
440         
441         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
442         
443         /*
444         printf ("DEBUG: %s\n", __FUNCTION__);
445         const GSList *iter = keys;
446         for (iter = keys; iter; iter = g_slist_next (iter)) {
447                 printf ("  DEBUG: %s: key=%s\n", __FUNCTION__, (const gchar*)iter->data);
448         }
449         */
450         
451         
452         /* Ignore the change if it's a change in the last_updated value */
453         if (g_slist_length ((GSList *)keys) == 1 &&
454                 g_str_has_suffix ((const gchar *) keys->data, MODEST_ACCOUNT_LAST_UPDATED)) {
455                 return;
456         }
457
458         /* FIXME: make this more finegrained; changes do not really affect _all_
459          * accounts
460          */
461 /*      recreate_all_accounts (self); */
462         
463         /* TODO: This doesn't actually work, because
464          * a) The account name is not sent correctly per key:
465          * b) We should test the end of the key, not the whole keym
466          * c) We don't seem to be getting all keys here.
467          * Instead, we just forget the password for all accounts when we create them, for now.
468          */
469         #if 0
470         /* If a password has changed, then forget the previously cached password for this account: */
471         if (server_account && keys && g_slist_find_custom ((GSList *)keys, MODEST_ACCOUNT_PASSWORD, (GCompareFunc)strcmp)) {
472                 printf ("DEBUG: %s: Forgetting cached password for account ID=%s\n", __FUNCTION__, account);
473                 modest_tny_account_store_forget_password_in_memory (self,  account);
474         }
475         #endif
476
477         g_signal_emit (G_OBJECT(self), signals[ACCOUNT_CHANGED_SIGNAL], 0, account);
478 }
479
480 static void 
481 on_account_settings_hide (GtkWidget *widget, gpointer user_data)
482 {
483         TnyAccount *account = (TnyAccount*)user_data;
484         
485         /* This is easier than using a struct for the user_data: */
486         ModestTnyAccountStore *self = modest_runtime_get_account_store();
487         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
488         
489         const gchar *modest_account_name = 
490                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
491         if (modest_account_name)
492                 g_hash_table_remove (priv->account_settings_dialog_hash, modest_account_name);
493 }
494
495 static gboolean 
496 on_idle_wrong_password_warning_only (gpointer user_data)
497 {
498         gdk_threads_enter();
499         
500         ModestWindow *main_window = 
501                                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
502                                 
503         /* Show an explanatory temporary banner: */
504         hildon_banner_show_information ( 
505                 GTK_WIDGET(main_window), NULL, _("mcen_ib_username_pw_incorrect"));
506                 
507         gdk_threads_leave();
508         
509         return FALSE; /* Don't show again. */
510 }
511                 
512 static gboolean 
513 on_idle_wrong_password (gpointer user_data)
514
515         TnyAccount *account = (TnyAccount*)user_data;
516         /* This is easier than using a struct for the user_data: */
517         ModestTnyAccountStore *self = modest_runtime_get_account_store();
518         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
519         
520         const gchar *modest_account_name = 
521                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
522         if (!modest_account_name) {
523                 g_warning ("%s: modest_tny_account_get_parent_modest_account_name_for_server_account() failed.\n", 
524                         __FUNCTION__);
525                         
526                 g_object_unref (account);
527                 return FALSE;
528         }
529         
530         
531         /* Check whether this window is already open,
532          * for instance because of a previous get_password() call: 
533          */
534         gpointer dialog_as_gpointer = NULL;
535         gboolean found = FALSE;
536         if (priv->account_settings_dialog_hash) {
537                 found = g_hash_table_lookup_extended (priv->account_settings_dialog_hash,
538                         modest_account_name, NULL, (gpointer*)&dialog_as_gpointer);
539         }
540         ModestAccountSettingsDialog *dialog = dialog_as_gpointer;
541                                         
542         ModestWindow *main_window = 
543                                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
544
545         gdk_threads_enter ();
546         gboolean created_dialog = FALSE;
547         if (!found || !dialog) {
548                 dialog = modest_account_settings_dialog_new ();
549                 modest_account_settings_dialog_set_account_name (dialog, modest_account_name);
550                 modest_account_settings_dialog_switch_to_user_info (dialog);
551                 
552                 g_hash_table_insert (priv->account_settings_dialog_hash, g_strdup (modest_account_name), dialog);
553                 
554                 created_dialog = TRUE;
555         }
556         
557         /* Show an explanatory temporary banner: */
558         hildon_banner_show_information ( 
559                 GTK_WIDGET(dialog), NULL, _("mcen_ib_username_pw_incorrect"));
560                 
561         if (created_dialog) {
562                 /* Forget it when it closes: */
563                 g_signal_connect_object (G_OBJECT (dialog), "hide", G_CALLBACK (on_account_settings_hide), 
564                         account, 0);
565                         
566                 /* Show it and delete it when it closes: */
567                 modest_maemo_show_dialog_and_forget (GTK_WINDOW (main_window), GTK_DIALOG (dialog));
568         }
569         else {
570                 /* Just show it instead of showing it and deleting it when it closes,
571                  * though it is probably open already: */
572                 gtk_window_present (GTK_WINDOW (dialog));
573         }
574         
575         g_object_unref (account);
576         gdk_threads_leave ();
577         
578         return FALSE; /* Dont' call this again. */
579 }
580
581 typedef struct 
582 {
583         GMainLoop *loop;
584         ModestTnyAccountStore* account_store;
585         const gchar* server_account_id;
586         gchar **username;
587         gchar **password;
588         gboolean *cancel;
589         gboolean *remember;
590 } IdlePasswordRequest;
591
592 static gboolean 
593 on_idle_request_password (gpointer user_data)
594 {
595         gdk_threads_enter();
596         
597         IdlePasswordRequest* info = (IdlePasswordRequest*)user_data;
598         g_signal_emit (G_OBJECT(info->account_store), signals[PASSWORD_REQUESTED_SIGNAL], 0,
599                                info->server_account_id, /* server_account_name */
600                                info->username, info->password, info->cancel, info->remember);
601                                
602         if (info->loop)
603                 g_main_loop_quit (info->loop);
604         
605         gdk_threads_leave();
606         
607         return FALSE; /* Don't call again. */
608 }
609
610 static void
611 request_password_in_main_loop_and_wait (ModestTnyAccountStore *account_store, 
612                                          const gchar* server_account_id,
613                                          gchar **username,
614                                          gchar **password,
615                                          gboolean *cancel, 
616                                          gboolean *remember)
617 {
618         IdlePasswordRequest *data = g_slice_new0 (IdlePasswordRequest);
619         data->account_store = account_store;
620         data->server_account_id = server_account_id;
621         data->username = username;
622         data->password = password;
623         data->cancel = cancel;
624         data->remember = remember;
625
626         data->loop = g_main_loop_new (NULL, FALSE /* not running */);
627         
628         /* Cause the function to be run in an idle-handler, which is always 
629          * in the main thread:
630          */
631         g_idle_add (&on_idle_request_password, data);
632         
633         /* This main loop will run until the idle handler has stopped it: */
634         printf ("DEBUG: %s: before g_main_loop_run()\n", __FUNCTION__);
635         GDK_THREADS_LEAVE();
636         g_main_loop_run (data->loop);
637         GDK_THREADS_ENTER();
638         printf ("DEBUG: %s: after g_main_loop_run()\n", __FUNCTION__);
639         printf ("DEBUG: %s: Finished\n", __FUNCTION__);
640         g_main_loop_unref (data->loop);
641
642         g_slice_free (IdlePasswordRequest, data);
643 }
644
645 /* This callback will be called by Tinymail when it needs the password
646  * from the user or the account settings.
647  * It can also call forget_password() before calling this,
648  * so that we clear wrong passwords out of our account settings.
649  * Note that TnyAccount here will be the server account. */
650 static gchar*
651 get_password (TnyAccount *account, const gchar * prompt_not_used, gboolean *cancel)
652 {
653         /* TODO: Settting cancel to FALSE does not actually cancel everything.
654          * We still get multiple requests afterwards, so we end up showing the 
655          * same dialogs repeatedly.
656          */
657          
658         printf ("DEBUG: modest: %s: prompt (not shown) = %s\n", __FUNCTION__, prompt_not_used);
659           
660         g_return_val_if_fail (account, NULL);
661           
662         const TnyAccountStore *account_store = NULL;
663         ModestTnyAccountStore *self = NULL;
664         ModestTnyAccountStorePrivate *priv;
665         gchar *username = NULL;
666         gchar *pwd = NULL;
667         gpointer pwd_ptr = NULL;
668         gboolean already_asked = FALSE;
669
670         /* Initialize the output parameter: */
671         if (cancel)
672                 *cancel = FALSE;
673                 
674         const gchar *server_account_name = tny_account_get_id (account);
675         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
676                                                              "account_store"));
677
678         if (!server_account_name || !account_store) {
679                 g_warning ("modest: %s: could not retrieve account_store for account %s",
680                            __FUNCTION__, server_account_name ? server_account_name : "<NULL>");
681                 if (cancel)
682                         *cancel = TRUE;
683                 
684                 return NULL;
685         }
686
687         self = MODEST_TNY_ACCOUNT_STORE (account_store);
688         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
689         
690         /* This hash map stores passwords, including passwords that are not stored in gconf. */
691         /* Is it in the hash? if it's already there, it must be wrong... */
692         pwd_ptr = (gpointer)&pwd; /* pwd_ptr so the compiler does not complained about
693                                    * type-punned ptrs...*/
694         already_asked = priv->password_hash && 
695                                 g_hash_table_lookup_extended (priv->password_hash,
696                                                       server_account_name,
697                                                       NULL,
698                                                       (gpointer*)&pwd_ptr);
699                                                       
700         printf ("DEBUG: modest: %s: Already asked = %d\n", __FUNCTION__, already_asked);
701
702         /* If the password is not already there, try ModestConf */
703         if (!already_asked) {
704                 pwd  = modest_server_account_get_password (priv->account_mgr,
705                                                       server_account_name);
706                 g_hash_table_insert (priv->password_hash, g_strdup (server_account_name), g_strdup (pwd));
707         }
708
709         /* If it was already asked, it must have been wrong, so ask again */
710         if (already_asked || !pwd || strlen(pwd) == 0) {
711                 /* As per the UI spec, if no password was set in the account settings, 
712                  * ask for it now. But if the password is wrong in the account settings, 
713                  * then show a banner and the account settings dialog so it can be corrected:
714                  */
715                 const gboolean settings_have_password = 
716                         modest_server_account_get_has_password (priv->account_mgr, server_account_name);
717                 printf ("DEBUG: modest: %s: settings_have_password=%d\n", __FUNCTION__, settings_have_password);
718                 if (settings_have_password) {
719         
720                         
721                         /* The password must be wrong, so show the account settings dialog so it can be corrected: */
722                         /* We show it in the main loop, because this function might not be in the main loop. */
723                         g_object_ref (account); /* unrefed in the idle handler. */
724                         g_idle_add (on_idle_wrong_password, account);
725                         
726                         if (cancel)
727                                 *cancel = TRUE;
728                                 
729                         return NULL;
730                 }
731         
732                 /* we don't have it yet. Get the password from the user */
733                 const gchar* account_id = tny_account_get_id (account);
734                 gboolean remember = FALSE;
735                 pwd = NULL;
736                 
737                 if (already_asked) {
738                         /* Show an info banner, before we show the protected password dialog: */
739                         g_idle_add (on_idle_wrong_password_warning_only, NULL);
740                 }
741                 
742                 request_password_in_main_loop_and_wait (self, account_id, 
743                                &username, &pwd, cancel, &remember);
744                 
745                 if (!*cancel) {
746                         /* The password will be returned as the result,
747                          * but we need to tell tinymail about the username too: */
748                         tny_account_set_user (account, username);
749                         
750                         /* Do not save the password in gconf, 
751                          * because the UI spec says "The password will never be saved in the account": */
752                         /*
753                         if (remember) {
754                                 printf ("%s: Storing username=%s, password=%s\n", 
755                                         __FUNCTION__, username, pwd);
756                                 modest_server_account_set_username (priv->account_mgr, server_account_name,
757                                                                username);
758                                 modest_server_account_set_password (priv->account_mgr, server_account_name,
759                                                                pwd);
760                         }
761                         */
762
763                         /* We need to dup the string even knowing that
764                            it's already a dup of the contents of an
765                            entry, because it if it's wrong, then camel
766                            will free it */
767                         g_hash_table_insert (priv->password_hash, g_strdup (server_account_name), g_strdup(pwd));
768                 } else {
769                         g_hash_table_remove (priv->password_hash, server_account_name);
770                         
771                         g_free (pwd);
772                         pwd = NULL;
773                 }
774
775                 g_free (username);
776                 username = NULL;
777         } else
778                 *cancel = FALSE;
779  
780     /* printf("  DEBUG: %s: returning %s\n", __FUNCTION__, pwd); */
781         
782         return pwd;
783 }
784
785 /* tinymail calls this if the connection failed due to an incorrect password.
786  * And it seems to call this for any general connection failure. */
787 static void
788 forget_password (TnyAccount *account)
789 {
790         printf ("DEBUG: %s\n", __FUNCTION__);
791         ModestTnyAccountStore *self;
792         ModestTnyAccountStorePrivate *priv;
793         const TnyAccountStore *account_store;
794         gchar *pwd;
795         const gchar *key;
796         
797         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
798                                                              "account_store"));
799         self = MODEST_TNY_ACCOUNT_STORE (account_store);
800         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
801         key  = tny_account_get_id (account);
802
803         /* Do not remove the key, this will allow us to detect that we
804            have already asked for it at least once */
805         pwd = g_hash_table_lookup (priv->password_hash, key);
806         if (pwd) {
807                 memset (pwd, 0, strlen (pwd));
808                 g_hash_table_insert (priv->password_hash, g_strdup (key), NULL);
809         }
810
811         /* Remove from configuration system */
812         /*
813         modest_account_mgr_unset (priv->account_mgr,
814                                   key, MODEST_ACCOUNT_PASSWORD, TRUE);
815         */
816 }
817
818 static void
819 modest_tny_account_store_finalize (GObject *obj)
820 {
821         GnomeVFSVolumeMonitor *volume_monitor;
822         ModestTnyAccountStore *self        = MODEST_TNY_ACCOUNT_STORE(obj);
823         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
824
825         g_free (priv->cache_dir);
826         priv->cache_dir = NULL;
827         
828         if (priv->password_hash) {
829                 g_hash_table_destroy (priv->password_hash);
830                 priv->password_hash = NULL;
831         }
832
833         /* Disconnect VFS signals */
834         volume_monitor = gnome_vfs_get_volume_monitor ();
835         if (g_signal_handler_is_connected (volume_monitor, 
836                                            priv->volume_mounted_handler))
837                 g_signal_handler_disconnect (volume_monitor, 
838                                              priv->volume_mounted_handler);
839         if (g_signal_handler_is_connected (volume_monitor, 
840                                            priv->volume_unmounted_handler))
841                 g_signal_handler_disconnect (volume_monitor, 
842                                              priv->volume_unmounted_handler);
843
844         if (priv->account_mgr) {
845                 /* Disconnect signals */
846                 if (g_signal_handler_is_connected (priv->account_mgr, 
847                                                    priv->acc_inserted_handler))
848                         g_signal_handler_disconnect (priv->account_mgr, 
849                                                      priv->acc_inserted_handler);
850                 if (g_signal_handler_is_connected (priv->account_mgr, 
851                                                    priv->acc_changed_handler))
852                         g_signal_handler_disconnect (priv->account_mgr, 
853                                                      priv->acc_changed_handler);
854                 if (g_signal_handler_is_connected (priv->account_mgr, 
855                                                    priv->acc_removed_handler))
856                         g_signal_handler_disconnect (priv->account_mgr, 
857                                                      priv->acc_removed_handler);
858
859                 g_object_unref (G_OBJECT(priv->account_mgr));
860                 priv->account_mgr = NULL;
861         }
862
863         if (priv->device) {
864                 g_object_unref (G_OBJECT(priv->device));
865                 priv->device = NULL;
866         }
867
868         /* Destroy all accounts. Disconnect all accounts before they are destroyed */
869         if (priv->store_accounts) {
870                 tny_list_foreach (priv->store_accounts, foreach_account_disconnect, NULL);
871                 g_object_unref (priv->store_accounts);
872                 priv->store_accounts = NULL;
873         }
874
875         if (priv->transport_accounts) {
876                 tny_list_foreach (priv->transport_accounts, foreach_account_disconnect, NULL);
877                 g_object_unref (priv->transport_accounts);
878                 priv->transport_accounts = NULL;
879         }
880
881         if (priv->store_accounts_outboxes) {
882                 g_object_unref (priv->store_accounts_outboxes);
883                 priv->store_accounts_outboxes = NULL;
884         }
885                 
886         if (priv->session) {
887                 camel_object_unref (CAMEL_OBJECT(priv->session));
888                 priv->session = NULL;
889         }
890         
891         G_OBJECT_CLASS(parent_class)->finalize (obj);
892 }
893
894
895 ModestTnyAccountStore*
896 modest_tny_account_store_new (ModestAccountMgr *account_mgr, 
897                               TnyDevice *device) 
898 {
899         GObject *obj;
900         ModestTnyAccountStorePrivate *priv;
901         TnyAccount *local_account = NULL;
902         
903         g_return_val_if_fail (account_mgr, NULL);
904         g_return_val_if_fail (device, NULL);
905
906         obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_ACCOUNT_STORE, NULL));
907         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
908
909         priv->account_mgr = g_object_ref (G_OBJECT(account_mgr));
910         priv->device = g_object_ref (device);
911         
912         priv->session = tny_session_camel_new (TNY_ACCOUNT_STORE(obj));
913         if (!priv->session) {
914                 g_warning ("failed to get TnySessionCamel");
915                 return NULL;
916         }
917
918         /* Set the ui locker */ 
919         tny_session_camel_set_ui_locker (priv->session,  tny_gtk_lockable_new ());
920                 
921         /* Connect signals */
922         priv->acc_inserted_handler = g_signal_connect (G_OBJECT(account_mgr), "account_inserted",
923                                                       G_CALLBACK (on_account_inserted), obj);
924         priv->acc_changed_handler = g_signal_connect (G_OBJECT(account_mgr), "account_changed",
925                                                       G_CALLBACK (on_account_changed), obj);
926         priv->acc_removed_handler = g_signal_connect (G_OBJECT(account_mgr), "account_removed",
927                                                       G_CALLBACK (on_account_removed), obj);
928
929         /* Create the lists of accounts */
930         priv->store_accounts = tny_simple_list_new ();
931         priv->transport_accounts = tny_simple_list_new ();
932         priv->store_accounts_outboxes = tny_simple_list_new ();
933
934         /* Create the local folders account */
935         local_account = 
936                 modest_tny_account_new_for_local_folders (priv->account_mgr, priv->session, NULL);
937         tny_list_append (priv->store_accounts, G_OBJECT(local_account));
938         g_object_unref (local_account); 
939
940         /* Add the other remote accounts. Do this before adding the
941            local account, because we need to add our outboxes to the
942            global OUTBOX hosted in the local account */
943         add_existing_accounts (MODEST_TNY_ACCOUNT_STORE (obj));
944
945         return MODEST_TNY_ACCOUNT_STORE(obj);
946 }
947
948 static void
949 modest_tny_account_store_get_accounts  (TnyAccountStore *self, 
950                                         TnyList *list,
951                                         TnyGetAccountsRequestType request_type)
952 {
953         ModestTnyAccountStorePrivate *priv;
954         
955         g_return_if_fail (self);
956         g_return_if_fail (TNY_IS_LIST(list));
957         
958         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
959         
960         switch (request_type) {
961         case TNY_ACCOUNT_STORE_BOTH:
962                 tny_list_foreach (priv->store_accounts, foreach_account_append_to_list, list);
963                 tny_list_foreach (priv->transport_accounts, foreach_account_append_to_list, list);
964                 break;
965         case TNY_ACCOUNT_STORE_STORE_ACCOUNTS:
966                 tny_list_foreach (priv->store_accounts, foreach_account_append_to_list, list);
967                 break;
968         case TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS:
969                 tny_list_foreach (priv->transport_accounts, foreach_account_append_to_list, list);
970                 break;
971         default:
972                 g_return_if_reached ();
973         }
974
975         /* Initialize session. Why do we need this ??? */
976         tny_session_camel_set_initialized (priv->session);
977 }
978
979
980 static const gchar*
981 modest_tny_account_store_get_cache_dir (TnyAccountStore *self)
982 {
983         ModestTnyAccountStorePrivate *priv;
984         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
985         
986         if (!priv->cache_dir)
987                 priv->cache_dir = g_build_filename (g_get_home_dir(), 
988                                                     MODEST_DIR, MODEST_CACHE_DIR, NULL);
989         return priv->cache_dir;
990 }
991
992
993 /*
994  * callers need to unref
995  */
996 static TnyDevice*
997 modest_tny_account_store_get_device (TnyAccountStore *self)
998 {
999         ModestTnyAccountStorePrivate *priv;
1000
1001         g_return_val_if_fail (self, NULL);
1002         
1003         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1004
1005         if (priv->device)
1006                 return g_object_ref (G_OBJECT(priv->device));
1007         else
1008                 return NULL;
1009 }
1010
1011
1012 static TnyAccount*
1013 modest_tny_account_store_find_account_by_url (TnyAccountStore *self, const gchar* url_string)
1014 {
1015         return modest_tny_account_store_get_tny_account_by (MODEST_TNY_ACCOUNT_STORE (self), 
1016                                                             MODEST_TNY_ACCOUNT_STORE_QUERY_URL,
1017                                                             url_string);
1018 }
1019
1020
1021
1022 static gboolean
1023 modest_tny_account_store_alert (TnyAccountStore *self, TnyAccount *account, TnyAlertType type,
1024                                 gboolean question, const GError *error)
1025 {
1026         g_return_val_if_fail (error, FALSE);
1027
1028         if ((error->domain != TNY_ACCOUNT_ERROR) 
1029                 && (error->domain != TNY_ACCOUNT_STORE_ERROR)) {
1030                 g_warning("modest: %s: Unexpected error domain: != TNY_ACCOUNT_ERROR: %d, message=%s", 
1031                         __FUNCTION__, error->domain, error->message); 
1032                         
1033                 return FALSE;
1034         }
1035         
1036         printf("DEBUG: %s: GError code: %d, message=%s\n", 
1037                                 __FUNCTION__, error->code, error->message);
1038         
1039         /* Get the server name: */
1040         const gchar* server_name = NULL;
1041         if (account && TNY_IS_ACCOUNT (account)) {
1042                 server_name = tny_account_get_hostname (account);
1043                 printf ("modest: %s: account name = %s, server_name=%s\n", __FUNCTION__, 
1044                         tny_account_get_id (account), server_name);
1045         }
1046         
1047         if (!server_name)
1048                 server_name = _("Unknown Server");      
1049                 
1050         ModestTransportStoreProtocol proto = MODEST_PROTOCOL_STORE_POP; /* Arbitrary default. */
1051         if (account) {
1052                 const gchar *proto_name = tny_account_get_proto (account);
1053                 if (proto_name)
1054                         proto = modest_protocol_info_get_transport_store_protocol (proto_name);
1055                 else {
1056                         g_warning("modest: %s: account with id=%s has no proto.\n", __FUNCTION__, 
1057                                 tny_account_get_id (account));
1058                 }
1059         }
1060                 
1061         /* const gchar *prompt = NULL; */
1062         gchar *prompt = NULL;
1063         switch (error->code) {
1064                 case TNY_ACCOUNT_STORE_ERROR_CANCEL_ALERT:
1065                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_USER_CANCEL:
1066                         /* Don't show waste the user's time by showing him a dialog telling 
1067                          * him that he has just cancelled something: */
1068                         g_debug ("%s: Handling GError domain=%d, code=%d (cancelled) without showing a dialog, message=%s", 
1069                                 __FUNCTION__, error->domain, error->code, error->message);
1070                         prompt = NULL;
1071                         break;
1072                         
1073                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_HOST_LOOKUP_FAILED:
1074                         /* TODO: Show the appropriate message, depending on whether it's POP or IMAP: */
1075                         g_debug ("%s: Handling GError domain=%d, code=%d (lookup failed), message=%s", 
1076                                 __FUNCTION__, error->domain, error->code, error->message);
1077                                 
1078                         switch (proto) {
1079                                 case MODEST_PROTOCOL_STORE_POP:
1080                                         prompt = g_strdup_printf (_("emev_ni_ui_pop3_msg_connect_error"), server_name);
1081                                         break;
1082                                 case MODEST_PROTOCOL_STORE_IMAP:
1083                                         prompt = g_strdup_printf (_("emev_ni_ui_imap_connect_server_error"), server_name);
1084                                         break;
1085                                 case MODEST_PROTOCOL_TRANSPORT_SMTP:
1086                                 default: /* Arbitrary default. */
1087                                         prompt = g_strdup_printf (_("emev_ib_ui_smtp_server_invalid"), server_name);
1088                                         break;
1089                         }
1090         
1091                         /*
1092                         prompt = g_strdup_printf(
1093                                 _("Incorrect Account Settings:\n Host lookup failed.%s"), 
1094                                 error->message);
1095                         */
1096                         break;
1097                         
1098                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_AUTHENTICATION_NOT_SUPPORTED:
1099                         g_debug ("%s: Handling GError domain=%d, code=%d (authentication not supported), message=%s", 
1100                                 __FUNCTION__, error->domain, error->code, error->message);
1101                         /* TODO: This needs a logical ID for the string: */
1102                         prompt = g_strdup_printf(
1103                                 _("Incorrect Account Settings:\nThe secure authentication method is not supported.\n%s"), 
1104                                 error->message);
1105                         break;
1106                         
1107                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_CERTIFICATE:
1108                         g_debug ("%s: Handling GError domain=%d, code=%d (certificatae), message=%s", 
1109                                 __FUNCTION__, error->domain, error->code, error->message);
1110                         prompt = g_strdup_printf(
1111                                 _("Certificate Problem:\n%s"), 
1112                                 error->message);
1113                         break;
1114                 
1115                 case TNY_ACCOUNT_ERROR_TRY_CONNECT:
1116                 /* The tinymail camel implementation just sends us this for almost 
1117                  * everything, so we have to guess at the cause.
1118                  * It could be a wrong password, or inability to resolve a hostname, 
1119                  * or lack of network, or incorrect authentication method, or something entirely different: */
1120                 /* TODO: Fix camel to provide specific error codes, and then use the 
1121                  * specific dialog messages from Chapter 12 of the UI spec.
1122                  */
1123                 case TNY_ACCOUNT_STORE_ERROR_UNKNOWN_ALERT: 
1124                         /* This debug output is useful. Please keep it uncommented until 
1125                          * we have fixed the problems in this function: */
1126                         g_debug ("%s: Handling GError domain=%d, code=%d, message=%s", 
1127                                 __FUNCTION__, error->domain, error->code, error->message);
1128                         
1129                         /* TODO: Remove the internal error message for the real release.
1130                          * This is just so the testers can give us more information: */
1131                         /* prompt = _("Modest account not yet fully configured."); */
1132                         prompt = g_strdup_printf(
1133                                 "%s\n (Internal error message, often very misleading):\n%s", 
1134                                 _("Incorrect Account Settings"), 
1135                                 error->message);
1136                                 
1137                         /* Note: If the password was wrong then get_password() would be called again,
1138                          * instead of this vfunc being called. */
1139                          
1140                         break;
1141                 
1142                 default:
1143                         g_warning ("%s: Unhandled GError code: %d, message=%s", 
1144                                 __FUNCTION__, error->code, error->message);
1145                         prompt = NULL;
1146                 break;
1147         }
1148         
1149         if (!prompt)
1150                 return FALSE;
1151
1152         ModestWindow *main_window = 
1153                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
1154         gboolean retval = TRUE;
1155         if (question) {
1156                 /* The Tinymail documentation says that we should show Yes and No buttons, 
1157                  * when it is a question.
1158                  * Obviously, we need tinymail to use more specific error codes instead,
1159                  * so we know what buttons to show. */
1160          
1161                 /* TODO: Do this in the main context: */
1162                 GtkWidget *dialog = GTK_WIDGET (hildon_note_new_confirmation (GTK_WINDOW (main_window), 
1163                         prompt));
1164                 const int response = gtk_dialog_run (GTK_DIALOG (dialog));
1165                 if (question) {
1166                         retval = (response == GTK_RESPONSE_YES) ||
1167                                          (response == GTK_RESPONSE_OK);
1168                 }
1169         
1170                 gtk_widget_destroy (dialog);
1171         
1172          } else {
1173                 /* Just show the error text and use the default response: */
1174                 modest_maemo_show_information_note_in_main_context_and_forget (GTK_WINDOW (main_window), 
1175                         prompt);
1176          }
1177         
1178         /* TODO: Don't free this when we no longer strdup the message for testers. */
1179         g_free (prompt);
1180
1181
1182         /* printf("DEBUG: %s: returning %d\n", __FUNCTION__, retval); */
1183         return retval;
1184 }
1185
1186
1187 static void
1188 modest_tny_account_store_init (gpointer g, gpointer iface_data)
1189 {
1190         TnyAccountStoreIface *klass;
1191
1192         g_return_if_fail (g);
1193
1194         klass = (TnyAccountStoreIface *)g;
1195
1196         klass->get_accounts_func =
1197                 modest_tny_account_store_get_accounts;
1198         klass->get_cache_dir_func =
1199                 modest_tny_account_store_get_cache_dir;
1200         klass->get_device_func =
1201                 modest_tny_account_store_get_device;
1202         klass->alert_func =
1203                 modest_tny_account_store_alert;
1204         klass->find_account_func =
1205                 modest_tny_account_store_find_account_by_url;
1206 }
1207
1208 void
1209 modest_tny_account_store_set_get_pass_func (ModestTnyAccountStore *self,
1210                                             ModestTnyGetPassFunc func)
1211 {
1212         /* not implemented, we use signals */
1213         g_printerr ("modest: set_get_pass_func not implemented\n");
1214 }
1215
1216 TnySessionCamel*
1217 modest_tny_account_store_get_session  (TnyAccountStore *self)
1218 {
1219         g_return_val_if_fail (self, NULL);
1220         return MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self)->session;
1221 }
1222
1223 static TnyAccount*
1224 get_tny_account_by (TnyList *accounts,
1225                     ModestTnyAccountStoreQueryType type,
1226                     const gchar *str)
1227 {
1228         TnyIterator *iter = NULL;
1229         gboolean found = FALSE;
1230         TnyAccount *retval = NULL;
1231
1232         iter = tny_list_create_iterator (accounts);
1233         while (!tny_iterator_is_done (iter) && !found) {
1234                 TnyAccount *tmp_account = NULL;
1235                 const gchar *val = NULL;
1236
1237                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1238                 switch (type) {
1239                 case MODEST_TNY_ACCOUNT_STORE_QUERY_ID:
1240                         val = tny_account_get_id (tmp_account);
1241                         break;
1242                 case MODEST_TNY_ACCOUNT_STORE_QUERY_URL:
1243                         val = tny_account_get_url_string (tmp_account);
1244                         break;
1245                 }
1246                 
1247                 if (type == MODEST_TNY_ACCOUNT_STORE_QUERY_URL && 
1248                     tny_account_matches_url_string (tmp_account, str)) {
1249                         retval = g_object_ref (tmp_account);
1250                         found = TRUE;
1251                 } else {
1252                         if (strcmp (val, str) == 0) {
1253                                 retval = g_object_ref (tmp_account);
1254                                 found = TRUE;
1255                         }
1256                 }
1257                 g_object_unref (tmp_account);
1258                 tny_iterator_next (iter);
1259         }
1260         g_object_unref (iter);
1261
1262         return retval;
1263 }
1264
1265 TnyAccount*
1266 modest_tny_account_store_get_tny_account_by (ModestTnyAccountStore *self, 
1267                                              ModestTnyAccountStoreQueryType type,
1268                                              const gchar *str)
1269 {
1270         TnyAccount *account = NULL;
1271         ModestTnyAccountStorePrivate *priv;     
1272         
1273         g_return_val_if_fail (self, NULL);
1274         g_return_val_if_fail (str, NULL);
1275         
1276         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1277         
1278         /* Search in store accounts */
1279         account = get_tny_account_by (priv->store_accounts, type, str);
1280
1281         /* If we already found something, no need to search the transport accounts */
1282         if (!account) {
1283                 account = get_tny_account_by (priv->transport_accounts, type, str);
1284
1285                 /* If we already found something, no need to search the
1286                    per-account outbox accounts */
1287                 if (!account)
1288                         account = get_tny_account_by (priv->store_accounts_outboxes, type, str);
1289         }
1290
1291         /* Warn if nothing was found. This is generally unusual. */
1292         if (!account) {
1293                 g_warning("%s: Failed to find account with %s=%s\n", 
1294                           __FUNCTION__, 
1295                           (type == MODEST_TNY_ACCOUNT_STORE_QUERY_ID) ? "ID" : "URL",                     
1296                           str);
1297         }
1298
1299         /* Returns a new reference to the account if found */   
1300         return account;
1301 }
1302
1303 TnyAccount*
1304 modest_tny_account_store_get_server_account (ModestTnyAccountStore *self,
1305                                              const gchar *account_name,
1306                                              TnyAccountType type)
1307 {
1308         ModestTnyAccountStorePrivate *priv = NULL;
1309         TnyAccount *retval = NULL;
1310         TnyList *account_list = NULL;
1311         TnyIterator *iter = NULL;
1312         gboolean found;
1313
1314         g_return_val_if_fail (self, NULL);
1315         g_return_val_if_fail (account_name, NULL);
1316         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || 
1317                               type == TNY_ACCOUNT_TYPE_TRANSPORT,
1318                               NULL);
1319         
1320         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1321
1322         account_list = (type == TNY_ACCOUNT_TYPE_STORE) ? 
1323                 priv->store_accounts : 
1324                 priv->transport_accounts;
1325
1326         if (!account_list) {
1327                 g_printerr ("%s: No server accounts of type %s\n", __FUNCTION__, 
1328                         (type == TNY_ACCOUNT_TYPE_STORE) ? "store" : "transport");
1329                 return NULL;
1330         }
1331         
1332         /* Look for the server account */
1333         found = FALSE;
1334         iter = tny_list_create_iterator (account_list);
1335         while (!tny_iterator_is_done (iter) && !found) {
1336                 const gchar *modest_acc_name;
1337                 TnyAccount *tmp_account;
1338
1339                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1340                 modest_acc_name = 
1341                         modest_tny_account_get_parent_modest_account_name_for_server_account (tmp_account);
1342                 
1343                 if (!strcmp (account_name, modest_acc_name)) {
1344                         found = TRUE;
1345                         retval = g_object_ref (tmp_account);
1346                 }
1347                 /* Free and continue */
1348                 g_object_unref (tmp_account);
1349                 tny_iterator_next (iter);
1350         }
1351
1352         if (!found) {
1353                 g_printerr ("modest: %s: could not get tny %s account for %s\n." \
1354                             "Number of server accounts of this type=%d\n", __FUNCTION__,
1355                             (type == TNY_ACCOUNT_TYPE_STORE) ? "store" : "transport",
1356                             account_name, tny_list_get_length (account_list));
1357         }
1358
1359         /* Returns a new reference */
1360         return retval;
1361 }
1362
1363 static TnyAccount*
1364 get_smtp_specific_transport_account_for_open_connection (ModestTnyAccountStore *self,
1365                                                          const gchar *account_name)
1366 {
1367         /* Get the current connection: */
1368         TnyDevice *device = modest_runtime_get_device ();
1369         
1370         if (!tny_device_is_online (device))
1371                 return NULL;
1372
1373         g_return_val_if_fail (self, NULL);
1374         g_return_val_if_fail (account_name, NULL);
1375         
1376         
1377 #ifdef MODEST_PLATFORM_MAEMO
1378         g_assert (TNY_IS_MAEMO_CONIC_DEVICE (device));
1379         TnyMaemoConicDevice *maemo_device = TNY_MAEMO_CONIC_DEVICE (device);    
1380         const gchar* iap_id = tny_maemo_conic_device_get_current_iap_id (maemo_device);
1381         /* printf ("DEBUG: %s: iap_id=%s\n", __FUNCTION__, iap_id); */
1382         if (!iap_id)
1383                 return NULL;
1384                 
1385         ConIcIap* connection = tny_maemo_conic_device_get_iap (maemo_device, iap_id);
1386         if (!connection)
1387                 return NULL;
1388                 
1389         const gchar *connection_name = con_ic_iap_get_name (connection);
1390         /* printf ("DEBUG: %s: connection_name=%s\n", __FUNCTION__, connection_name); */
1391         if (!connection_name)
1392                 return NULL;
1393         
1394         /*  Get the connection-specific transport acccount, if any: */
1395         ModestAccountMgr *account_manager = modest_runtime_get_account_mgr ();
1396         gchar* server_account_name = modest_account_mgr_get_connection_specific_smtp (account_manager, 
1397                 account_name, connection_name);
1398
1399         /* printf ("DEBUG: %s: server_account_name=%s\n", __FUNCTION__, server_account_name); */
1400         if (!server_account_name) {
1401                 return NULL; /* No connection-specific SMTP server was specified for this connection. */
1402         }
1403                 
1404         TnyAccount* account = modest_tny_account_store_get_tny_account_by (self, 
1405                                                                            MODEST_TNY_ACCOUNT_STORE_QUERY_ID, 
1406                                                                            server_account_name);
1407
1408         /* printf ("DEBUG: %s: account=%p\n", __FUNCTION__, account); */
1409         g_free (server_account_name);   
1410
1411         /* Unref the get()ed object, as required by the tny_maemo_conic_device_get_iap() documentation. */
1412         g_object_unref (connection);
1413         
1414         return account;
1415 #else
1416         return NULL; /* TODO: Implement this for GNOME, instead of just Maemo? */
1417 #endif /* MODEST_PLATFORM_MAEMO */
1418 }
1419
1420                                                                  
1421 TnyAccount*
1422 modest_tny_account_store_get_transport_account_for_open_connection (ModestTnyAccountStore *self,
1423                                                                     const gchar *account_name)
1424 {
1425         g_return_val_if_fail (self, NULL);
1426         g_return_val_if_fail (account_name, NULL);
1427
1428         if (!account_name || !self)
1429                 return NULL;
1430         
1431         /*  Get the connection-specific transport acccount, if any: */
1432         TnyAccount *account =
1433                 get_smtp_specific_transport_account_for_open_connection (self, account_name);
1434                         
1435         /* If there is no connection-specific transport account (the common case), 
1436          * just get the regular transport account: */
1437         if (!account) {
1438                 /* The special local folders don't have transport accounts. */
1439                 if (strcmp (account_name, MODEST_LOCAL_FOLDERS_ACCOUNT_ID) == 0)
1440                         account = NULL;
1441                 else
1442                         account = modest_tny_account_store_get_server_account (self, account_name, 
1443                                                      TNY_ACCOUNT_TYPE_TRANSPORT);
1444         }
1445                              
1446         return account;
1447 }
1448
1449 TnyAccount*
1450 modest_tny_account_store_get_local_folders_account (ModestTnyAccountStore *self)
1451 {
1452         TnyAccount *account = NULL;
1453         ModestTnyAccountStorePrivate *priv;
1454         TnyIterator *iter;
1455         gboolean found;
1456
1457         g_return_val_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (self), NULL);
1458         
1459         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1460
1461         found = FALSE;
1462         iter = tny_list_create_iterator (priv->store_accounts);
1463         while (!tny_iterator_is_done (iter) && !found) {
1464                 TnyAccount *tmp_account;
1465
1466                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1467                 if (modest_tny_account_is_virtual_local_folders (tmp_account)) {
1468                         account = g_object_ref (tmp_account);
1469                         found = TRUE;
1470                 }
1471                 g_object_unref (tmp_account);
1472                 tny_iterator_next (iter);
1473         }
1474         g_object_unref (iter);
1475
1476         /* Returns a new reference to the account */
1477         return account;
1478 }
1479
1480 /*********************************************************************************/
1481 static void
1482 add_existing_accounts (ModestTnyAccountStore *self)
1483 {
1484         GSList *account_names = NULL, *iter = NULL;
1485         ModestTnyAccountStorePrivate *priv = NULL;
1486         
1487         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1488
1489         /* These are account names, not server_account names */
1490         account_names = modest_account_mgr_account_names (priv->account_mgr, FALSE);
1491
1492         for (iter = account_names; iter != NULL; iter = g_slist_next (iter)) {
1493                 const gchar *account_name = (const gchar*) iter->data;
1494                 
1495                 /* Insert all enabled accounts without notifying */
1496                 if (modest_account_mgr_get_enabled (priv->account_mgr, account_name))
1497                         insert_account (self, account_name, FALSE);
1498         }
1499         modest_account_mgr_free_account_names (account_names);
1500 }
1501
1502 static TnyAccount*
1503 create_tny_account (ModestTnyAccountStore *self,
1504                     const gchar *name,
1505                     TnyAccountType type)
1506 {
1507         TnyAccount *account = NULL;
1508         ModestTnyAccountStorePrivate *priv = NULL;
1509         
1510         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1511
1512         account = modest_tny_account_new_from_account (priv->account_mgr,
1513                                                        name, type, 
1514                                                        priv->session,
1515                                                        get_password,
1516                                                        forget_password);
1517
1518         if (account) {
1519                 /* Forget any cached password for the account, so that
1520                    we use a new account if any */
1521                 modest_tny_account_store_forget_password_in_memory (self, 
1522                                                                     tny_account_get_id (account));
1523                 /* Set the account store */                             
1524                 g_object_set_data (G_OBJECT(account), "account_store", self);
1525         } else {
1526                 g_printerr ("modest: failed to create account for %s\n", name);
1527         }
1528
1529         return account;
1530 }
1531
1532 /*
1533  * This function will be used for both adding new accounts and for the
1534  * initialization. In the initialization we do not want to emit
1535  * signals so notify will be FALSE, in the case of account additions
1536  * we do want to notify the observers
1537  */
1538 static void
1539 insert_account (ModestTnyAccountStore *self,
1540                 const gchar *account,
1541                 gboolean notify)
1542 {
1543         ModestTnyAccountStorePrivate *priv = NULL;
1544         TnyAccount *store_account = NULL, *transport_account = NULL;
1545         
1546         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1547
1548         /* Get the server and the transport account */
1549         store_account = create_tny_account (self, account, TNY_ACCOUNT_TYPE_STORE);
1550         transport_account = create_tny_account (self, account, TNY_ACCOUNT_TYPE_TRANSPORT);
1551
1552         /* Add to the list, and notify the observers */
1553         if (store_account) {
1554                 tny_list_append (priv->store_accounts, G_OBJECT (store_account));
1555                 if (notify)
1556                         g_signal_emit (G_OBJECT (self), signals [ACCOUNT_INSERTED_SIGNAL], 0, store_account);
1557                 g_object_unref (store_account);
1558         }
1559
1560         /* Add to the list, and notify the observers */
1561         if (transport_account) {
1562                 TnyAccount *account_outbox = NULL, *local_account = NULL;
1563                 TnyFolder *per_account_outbox = NULL;
1564                 TnyList *folders;
1565                 TnyIterator *iter_folders;
1566
1567                 /* Add account to the list */
1568                 tny_list_append (priv->transport_accounts, G_OBJECT (transport_account));
1569
1570                 /* Add connection-specific transport accounts */
1571                 add_connection_specific_transport_accounts (self, account);
1572
1573                 /* Create per account local outbox */
1574                 account_outbox = 
1575                         modest_tny_account_new_for_per_account_local_outbox_folder (priv->account_mgr, 
1576                                                                                     account, 
1577                                                                                     priv->session);
1578                 tny_list_append (priv->store_accounts_outboxes, G_OBJECT (account_outbox));
1579
1580                 /* Get the outbox folder */
1581                 folders = tny_simple_list_new ();
1582                 tny_folder_store_get_folders (TNY_FOLDER_STORE (account_outbox),
1583                                               folders, NULL, NULL);
1584                 g_assert (tny_list_get_length (folders) == 1);
1585                 iter_folders = tny_list_create_iterator (folders);
1586                 per_account_outbox = TNY_FOLDER (tny_iterator_get_current (iter_folders));
1587                 g_object_unref (iter_folders);
1588                 g_object_unref (account_outbox);
1589
1590                 /* Add the outbox of the new per-account-local-outbox
1591                    account to the global local merged OUTBOX of the
1592                    local folders account */
1593                 local_account = modest_tny_account_store_get_local_folders_account (MODEST_TNY_ACCOUNT_STORE (self));
1594                 modest_tny_local_folders_account_add_folder_to_outbox (MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (local_account), 
1595                                                                        per_account_outbox);
1596                 g_object_unref (local_account);
1597                 g_object_unref (per_account_outbox);
1598
1599                 /* Notify the observers */
1600                 if (notify)
1601                         g_signal_emit (G_OBJECT (self), signals [ACCOUNT_INSERTED_SIGNAL], 0, transport_account);
1602                 g_object_unref (transport_account);
1603         }
1604 }
1605
1606 static void
1607 on_account_inserted (ModestAccountMgr *acc_mgr, 
1608                      const gchar *account,
1609                      gpointer user_data)
1610 {
1611         /* Insert the account and notify the observers */
1612         insert_account (MODEST_TNY_ACCOUNT_STORE (user_data), account, TRUE);
1613 }
1614
1615 static void
1616 on_account_removed (ModestAccountMgr *acc_mgr, 
1617                     const gchar *account,
1618                     gpointer user_data)
1619 {
1620         TnyAccount *store_account = NULL, *transport_account = NULL;
1621         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
1622         
1623         /* Get the server and the transport account */
1624         store_account = 
1625                 modest_tny_account_store_get_server_account (self, account, TNY_ACCOUNT_TYPE_STORE);
1626         transport_account = 
1627                 modest_tny_account_store_get_server_account (self, account, TNY_ACCOUNT_TYPE_TRANSPORT);
1628
1629         /* If there was any problem creating the account, for example,
1630            with the configuration system this could not exist */
1631         if (store_account) {
1632                 /* Clear the cache */
1633                 tny_store_account_delete_cache (TNY_STORE_ACCOUNT (store_account));
1634
1635                 /* Notify the observers */
1636                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_REMOVED_SIGNAL], 0, store_account);
1637                 g_object_unref (store_account);
1638         } else {
1639                 g_warning ("There is no store account for account %s\n", account);
1640         }
1641
1642         /* If there was any problem creating the account, for example,
1643            with the configuration system this could not exist */
1644         if (transport_account) {
1645                 /* Notify the observers */
1646                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_REMOVED_SIGNAL], 0, transport_account);
1647                 g_object_unref (transport_account);
1648         } else {
1649                 g_warning ("There is no transport account for account %s\n", account);
1650         }
1651 }
1652
1653 static void
1654 add_connection_specific_transport_accounts (ModestTnyAccountStore *self,
1655                                             const gchar *account_name)
1656 {
1657         ModestTnyAccountStorePrivate *priv = NULL;
1658         GSList *list_specifics = NULL, *iter = NULL;
1659
1660         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1661
1662         list_specifics = modest_account_mgr_get_list (priv->account_mgr,
1663                                                       account_name, 
1664                                                       MODEST_ACCOUNT_CONNECTION_SPECIFIC_SMTP_LIST,
1665                                                       MODEST_CONF_VALUE_STRING, FALSE);
1666                                 
1667         /* Look at each connection-specific transport account for the 
1668          * modest account: */
1669         iter = list_specifics;
1670         while (iter) {
1671                 /* The list alternates between the connection name and the transport name: */
1672                 iter = g_slist_next (iter);
1673                 if (iter) {
1674                         const gchar* transport_account_name = (const gchar*) (iter->data);
1675                         if (transport_account_name) {
1676                                 TnyAccount * tny_account = NULL;
1677                                 /* Add the account: */
1678                                 tny_account = 
1679                                         modest_tny_account_new_from_server_account_name (priv->account_mgr, 
1680                                                                                          priv->session, 
1681                                                                                          transport_account_name);
1682                                 if (tny_account) {
1683                                         modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account, 
1684                                                                                                               account_name);
1685                                         g_object_set_data (G_OBJECT(tny_account), 
1686                                                            "account_store", 
1687                                                            (gpointer)self);
1688
1689                                         tny_list_append (priv->transport_accounts, G_OBJECT (tny_account));
1690                                 } else
1691                                         g_printerr ("modest: failed to create smtp-specific account for %s\n",
1692                                                     transport_account_name);
1693                         }
1694                 }                               
1695                 iter = g_slist_next (iter);
1696         }
1697 }