b53ff07f1c1f5ae1423a3ee0c10e2aab044d4239
[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         /* Make sure that the account is reviewed from the View menu, etc: */
400         g_signal_emit (G_OBJECT(self), signals[ACCOUNT_UPDATE_SIGNAL], 0,
401                                NULL);
402
403                         /* Notify observers */
404                         g_signal_emit (G_OBJECT (self),
405                                        signals [ACCOUNT_REMOVED_SIGNAL],
406                                        0, mmc_account);
407
408                         g_object_unref (mmc_account);
409                 } else {
410                         g_warning ("%s: there was no store account for the unmounted MMC",
411                                    __FUNCTION__);
412                 }
413         }
414         g_free (uri);
415 }
416
417 /**
418  * modest_tny_account_store_forget_password_in_memory
419  * @self: a TnyAccountStore instance
420  * @account: A server account.
421  * 
422  * Forget any password stored in memory for this account.
423  * For instance, this should be called when the user has changed the password in the account settings.
424  */
425 static void
426 modest_tny_account_store_forget_password_in_memory (ModestTnyAccountStore *self, const gchar * server_account_name)
427 {
428         /* printf ("DEBUG: %s\n", __FUNCTION__); */
429         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
430
431         if (server_account_name && priv->password_hash) {
432                 g_hash_table_remove (priv->password_hash, server_account_name);
433         }
434 }
435
436 static void
437 on_account_changed (ModestAccountMgr *acc_mgr, 
438                     const gchar *account,
439                     const GSList *keys, 
440                     gboolean server_account, 
441                     gpointer user_data)
442 {
443         printf ("DEBUG: modest: %s\n", __FUNCTION__);
444         
445         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
446         
447         /*
448         printf ("DEBUG: %s\n", __FUNCTION__);
449         const GSList *iter = keys;
450         for (iter = keys; iter; iter = g_slist_next (iter)) {
451                 printf ("  DEBUG: %s: key=%s\n", __FUNCTION__, (const gchar*)iter->data);
452         }
453         */
454         
455         
456         /* Ignore the change if it's a change in the last_updated value */
457         if (g_slist_length ((GSList *)keys) == 1 &&
458                 g_str_has_suffix ((const gchar *) keys->data, MODEST_ACCOUNT_LAST_UPDATED)) {
459                 return;
460         }
461
462         /* FIXME: make this more finegrained; changes do not really affect _all_
463          * accounts
464          */
465 /*      recreate_all_accounts (self); */
466         
467         /* TODO: This doesn't actually work, because
468          * a) The account name is not sent correctly per key:
469          * b) We should test the end of the key, not the whole keym
470          * c) We don't seem to be getting all keys here.
471          * Instead, we just forget the password for all accounts when we create them, for now.
472          */
473         #if 0
474         /* If a password has changed, then forget the previously cached password for this account: */
475         if (server_account && keys && g_slist_find_custom ((GSList *)keys, MODEST_ACCOUNT_PASSWORD, (GCompareFunc)strcmp)) {
476                 printf ("DEBUG: %s: Forgetting cached password for account ID=%s\n", __FUNCTION__, account);
477                 modest_tny_account_store_forget_password_in_memory (self,  account);
478         }
479         #endif
480
481         g_signal_emit (G_OBJECT(self), signals[ACCOUNT_CHANGED_SIGNAL], 0, account);
482 }
483
484 static void 
485 on_account_settings_hide (GtkWidget *widget, gpointer user_data)
486 {
487         TnyAccount *account = (TnyAccount*)user_data;
488         
489         /* This is easier than using a struct for the user_data: */
490         ModestTnyAccountStore *self = modest_runtime_get_account_store();
491         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
492         
493         const gchar *modest_account_name = 
494                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
495         if (modest_account_name)
496                 g_hash_table_remove (priv->account_settings_dialog_hash, modest_account_name);
497 }
498
499 static gboolean 
500 on_idle_wrong_password_warning_only (gpointer user_data)
501 {
502         gdk_threads_enter();
503         
504         ModestWindow *main_window = 
505                                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
506                                 
507         /* Show an explanatory temporary banner: */
508         hildon_banner_show_information ( 
509                 GTK_WIDGET(main_window), NULL, _("mcen_ib_username_pw_incorrect"));
510                 
511         gdk_threads_leave();
512         
513         return FALSE; /* Don't show again. */
514 }
515                 
516 static gboolean 
517 on_idle_wrong_password (gpointer user_data)
518
519         TnyAccount *account = (TnyAccount*)user_data;
520         /* This is easier than using a struct for the user_data: */
521         ModestTnyAccountStore *self = modest_runtime_get_account_store();
522         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
523         
524         const gchar *modest_account_name = 
525                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
526         if (!modest_account_name) {
527                 g_warning ("%s: modest_tny_account_get_parent_modest_account_name_for_server_account() failed.\n", 
528                         __FUNCTION__);
529                         
530                 g_object_unref (account);
531                 return FALSE;
532         }
533         
534         
535         /* Check whether this window is already open,
536          * for instance because of a previous get_password() call: 
537          */
538         gpointer dialog_as_gpointer = NULL;
539         gboolean found = FALSE;
540         if (priv->account_settings_dialog_hash) {
541                 found = g_hash_table_lookup_extended (priv->account_settings_dialog_hash,
542                         modest_account_name, NULL, (gpointer*)&dialog_as_gpointer);
543         }
544         ModestAccountSettingsDialog *dialog = dialog_as_gpointer;
545                                         
546         ModestWindow *main_window = 
547                                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
548
549         gdk_threads_enter ();
550         gboolean created_dialog = FALSE;
551         if (!found || !dialog) {
552                 dialog = modest_account_settings_dialog_new ();
553                 modest_account_settings_dialog_set_account_name (dialog, modest_account_name);
554                 modest_account_settings_dialog_switch_to_user_info (dialog);
555                 
556                 g_hash_table_insert (priv->account_settings_dialog_hash, g_strdup (modest_account_name), dialog);
557                 
558                 created_dialog = TRUE;
559         }
560         
561         /* Show an explanatory temporary banner: */
562         hildon_banner_show_information ( 
563                 GTK_WIDGET(dialog), NULL, _("mcen_ib_username_pw_incorrect"));
564                 
565         if (created_dialog) {
566                 /* Forget it when it closes: */
567                 g_signal_connect_object (G_OBJECT (dialog), "hide", G_CALLBACK (on_account_settings_hide), 
568                         account, 0);
569                         
570                 /* Show it and delete it when it closes: */
571                 modest_maemo_show_dialog_and_forget (GTK_WINDOW (main_window), GTK_DIALOG (dialog));
572         }
573         else {
574                 /* Just show it instead of showing it and deleting it when it closes,
575                  * though it is probably open already: */
576                 gtk_window_present (GTK_WINDOW (dialog));
577         }
578         
579         g_object_unref (account);
580         gdk_threads_leave ();
581         
582         return FALSE; /* Dont' call this again. */
583 }
584
585 typedef struct 
586 {
587         GMainLoop *loop;
588         ModestTnyAccountStore* account_store;
589         const gchar* server_account_id;
590         gchar **username;
591         gchar **password;
592         gboolean *cancel;
593         gboolean *remember;
594 } IdlePasswordRequest;
595
596 static gboolean 
597 on_idle_request_password (gpointer user_data)
598 {
599         gdk_threads_enter();
600         
601         IdlePasswordRequest* info = (IdlePasswordRequest*)user_data;
602         g_signal_emit (G_OBJECT(info->account_store), signals[PASSWORD_REQUESTED_SIGNAL], 0,
603                                info->server_account_id, /* server_account_name */
604                                info->username, info->password, info->cancel, info->remember);
605                                
606         if (info->loop)
607                 g_main_loop_quit (info->loop);
608         
609         gdk_threads_leave();
610         
611         return FALSE; /* Don't call again. */
612 }
613
614 static void
615 request_password_in_main_loop_and_wait (ModestTnyAccountStore *account_store, 
616                                          const gchar* server_account_id,
617                                          gchar **username,
618                                          gchar **password,
619                                          gboolean *cancel, 
620                                          gboolean *remember)
621 {
622         IdlePasswordRequest *data = g_slice_new0 (IdlePasswordRequest);
623         data->account_store = account_store;
624         data->server_account_id = server_account_id;
625         data->username = username;
626         data->password = password;
627         data->cancel = cancel;
628         data->remember = remember;
629
630         data->loop = g_main_loop_new (NULL, FALSE /* not running */);
631         
632         /* Cause the function to be run in an idle-handler, which is always 
633          * in the main thread:
634          */
635         g_idle_add (&on_idle_request_password, data);
636         
637         /* This main loop will run until the idle handler has stopped it: */
638         printf ("DEBUG: %s: before g_main_loop_run()\n", __FUNCTION__);
639         GDK_THREADS_LEAVE();
640         g_main_loop_run (data->loop);
641         GDK_THREADS_ENTER();
642         printf ("DEBUG: %s: after g_main_loop_run()\n", __FUNCTION__);
643         printf ("DEBUG: %s: Finished\n", __FUNCTION__);
644         g_main_loop_unref (data->loop);
645
646         g_slice_free (IdlePasswordRequest, data);
647 }
648
649 /* This callback will be called by Tinymail when it needs the password
650  * from the user or the account settings.
651  * It can also call forget_password() before calling this,
652  * so that we clear wrong passwords out of our account settings.
653  * Note that TnyAccount here will be the server account. */
654 static gchar*
655 get_password (TnyAccount *account, const gchar * prompt_not_used, gboolean *cancel)
656 {
657         /* TODO: Settting cancel to FALSE does not actually cancel everything.
658          * We still get multiple requests afterwards, so we end up showing the 
659          * same dialogs repeatedly.
660          */
661          
662         printf ("DEBUG: modest: %s: prompt (not shown) = %s\n", __FUNCTION__, prompt_not_used);
663           
664         g_return_val_if_fail (account, NULL);
665           
666         const TnyAccountStore *account_store = NULL;
667         ModestTnyAccountStore *self = NULL;
668         ModestTnyAccountStorePrivate *priv;
669         gchar *username = NULL;
670         gchar *pwd = NULL;
671         gpointer pwd_ptr = NULL;
672         gboolean already_asked = FALSE;
673
674         /* Initialize the output parameter: */
675         if (cancel)
676                 *cancel = FALSE;
677                 
678         const gchar *server_account_name = tny_account_get_id (account);
679         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
680                                                              "account_store"));
681
682         if (!server_account_name || !account_store) {
683                 g_warning ("modest: %s: could not retrieve account_store for account %s",
684                            __FUNCTION__, server_account_name ? server_account_name : "<NULL>");
685                 if (cancel)
686                         *cancel = TRUE;
687                 
688                 return NULL;
689         }
690
691         self = MODEST_TNY_ACCOUNT_STORE (account_store);
692         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
693         
694         /* This hash map stores passwords, including passwords that are not stored in gconf. */
695         /* Is it in the hash? if it's already there, it must be wrong... */
696         pwd_ptr = (gpointer)&pwd; /* pwd_ptr so the compiler does not complained about
697                                    * type-punned ptrs...*/
698         already_asked = priv->password_hash && 
699                                 g_hash_table_lookup_extended (priv->password_hash,
700                                                       server_account_name,
701                                                       NULL,
702                                                       (gpointer*)&pwd_ptr);
703                                                       
704         printf ("DEBUG: modest: %s: Already asked = %d\n", __FUNCTION__, already_asked);
705
706         /* If the password is not already there, try ModestConf */
707         if (!already_asked) {
708                 pwd  = modest_server_account_get_password (priv->account_mgr,
709                                                       server_account_name);
710                 g_hash_table_insert (priv->password_hash, g_strdup (server_account_name), g_strdup (pwd));
711         }
712
713         /* If it was already asked, it must have been wrong, so ask again */
714         if (already_asked || !pwd || strlen(pwd) == 0) {
715                 /* As per the UI spec, if no password was set in the account settings, 
716                  * ask for it now. But if the password is wrong in the account settings, 
717                  * then show a banner and the account settings dialog so it can be corrected:
718                  */
719                 const gboolean settings_have_password = 
720                         modest_server_account_get_has_password (priv->account_mgr, server_account_name);
721                 printf ("DEBUG: modest: %s: settings_have_password=%d\n", __FUNCTION__, settings_have_password);
722                 if (settings_have_password) {
723         
724                         
725                         /* The password must be wrong, so show the account settings dialog so it can be corrected: */
726                         /* We show it in the main loop, because this function might not be in the main loop. */
727                         g_object_ref (account); /* unrefed in the idle handler. */
728                         g_idle_add (on_idle_wrong_password, account);
729                         
730                         if (cancel)
731                                 *cancel = TRUE;
732                                 
733                         return NULL;
734                 }
735         
736                 /* we don't have it yet. Get the password from the user */
737                 const gchar* account_id = tny_account_get_id (account);
738                 gboolean remember = FALSE;
739                 pwd = NULL;
740                 
741                 if (already_asked) {
742                         /* Show an info banner, before we show the protected password dialog: */
743                         g_idle_add (on_idle_wrong_password_warning_only, NULL);
744                 }
745                 
746                 request_password_in_main_loop_and_wait (self, account_id, 
747                                &username, &pwd, cancel, &remember);
748                 
749                 if (!*cancel) {
750                         /* The password will be returned as the result,
751                          * but we need to tell tinymail about the username too: */
752                         tny_account_set_user (account, username);
753                         
754                         /* Do not save the password in gconf, 
755                          * because the UI spec says "The password will never be saved in the account": */
756                         /*
757                         if (remember) {
758                                 printf ("%s: Storing username=%s, password=%s\n", 
759                                         __FUNCTION__, username, pwd);
760                                 modest_server_account_set_username (priv->account_mgr, server_account_name,
761                                                                username);
762                                 modest_server_account_set_password (priv->account_mgr, server_account_name,
763                                                                pwd);
764                         }
765                         */
766
767                         /* We need to dup the string even knowing that
768                            it's already a dup of the contents of an
769                            entry, because it if it's wrong, then camel
770                            will free it */
771                         g_hash_table_insert (priv->password_hash, g_strdup (server_account_name), g_strdup(pwd));
772                 } else {
773                         g_hash_table_remove (priv->password_hash, server_account_name);
774                         
775                         g_free (pwd);
776                         pwd = NULL;
777                 }
778
779                 g_free (username);
780                 username = NULL;
781         } else
782                 *cancel = FALSE;
783  
784     /* printf("  DEBUG: %s: returning %s\n", __FUNCTION__, pwd); */
785         
786         return pwd;
787 }
788
789 /* tinymail calls this if the connection failed due to an incorrect password.
790  * And it seems to call this for any general connection failure. */
791 static void
792 forget_password (TnyAccount *account)
793 {
794         printf ("DEBUG: %s\n", __FUNCTION__);
795         ModestTnyAccountStore *self;
796         ModestTnyAccountStorePrivate *priv;
797         const TnyAccountStore *account_store;
798         gchar *pwd;
799         const gchar *key;
800         
801         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
802                                                              "account_store"));
803         self = MODEST_TNY_ACCOUNT_STORE (account_store);
804         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
805         key  = tny_account_get_id (account);
806
807         /* Do not remove the key, this will allow us to detect that we
808            have already asked for it at least once */
809         pwd = g_hash_table_lookup (priv->password_hash, key);
810         if (pwd) {
811                 memset (pwd, 0, strlen (pwd));
812                 g_hash_table_insert (priv->password_hash, g_strdup (key), NULL);
813         }
814
815         /* Remove from configuration system */
816         /*
817         modest_account_mgr_unset (priv->account_mgr,
818                                   key, MODEST_ACCOUNT_PASSWORD, TRUE);
819         */
820 }
821
822 static void
823 modest_tny_account_store_finalize (GObject *obj)
824 {
825         GnomeVFSVolumeMonitor *volume_monitor;
826         ModestTnyAccountStore *self        = MODEST_TNY_ACCOUNT_STORE(obj);
827         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
828
829         g_free (priv->cache_dir);
830         priv->cache_dir = NULL;
831         
832         if (priv->password_hash) {
833                 g_hash_table_destroy (priv->password_hash);
834                 priv->password_hash = NULL;
835         }
836
837         /* Disconnect VFS signals */
838         volume_monitor = gnome_vfs_get_volume_monitor ();
839         if (g_signal_handler_is_connected (volume_monitor, 
840                                            priv->volume_mounted_handler))
841                 g_signal_handler_disconnect (volume_monitor, 
842                                              priv->volume_mounted_handler);
843         if (g_signal_handler_is_connected (volume_monitor, 
844                                            priv->volume_unmounted_handler))
845                 g_signal_handler_disconnect (volume_monitor, 
846                                              priv->volume_unmounted_handler);
847
848         if (priv->account_mgr) {
849                 /* Disconnect signals */
850                 if (g_signal_handler_is_connected (priv->account_mgr, 
851                                                    priv->acc_inserted_handler))
852                         g_signal_handler_disconnect (priv->account_mgr, 
853                                                      priv->acc_inserted_handler);
854                 if (g_signal_handler_is_connected (priv->account_mgr, 
855                                                    priv->acc_changed_handler))
856                         g_signal_handler_disconnect (priv->account_mgr, 
857                                                      priv->acc_changed_handler);
858                 if (g_signal_handler_is_connected (priv->account_mgr, 
859                                                    priv->acc_removed_handler))
860                         g_signal_handler_disconnect (priv->account_mgr, 
861                                                      priv->acc_removed_handler);
862
863                 g_object_unref (G_OBJECT(priv->account_mgr));
864                 priv->account_mgr = NULL;
865         }
866
867         if (priv->device) {
868                 g_object_unref (G_OBJECT(priv->device));
869                 priv->device = NULL;
870         }
871
872         /* Destroy all accounts. Disconnect all accounts before they are destroyed */
873         if (priv->store_accounts) {
874                 tny_list_foreach (priv->store_accounts, foreach_account_disconnect, NULL);
875                 g_object_unref (priv->store_accounts);
876                 priv->store_accounts = NULL;
877         }
878
879         if (priv->transport_accounts) {
880                 tny_list_foreach (priv->transport_accounts, foreach_account_disconnect, NULL);
881                 g_object_unref (priv->transport_accounts);
882                 priv->transport_accounts = NULL;
883         }
884
885         if (priv->store_accounts_outboxes) {
886                 g_object_unref (priv->store_accounts_outboxes);
887                 priv->store_accounts_outboxes = NULL;
888         }
889                 
890         if (priv->session) {
891                 camel_object_unref (CAMEL_OBJECT(priv->session));
892                 priv->session = NULL;
893         }
894         
895         G_OBJECT_CLASS(parent_class)->finalize (obj);
896 }
897
898
899 ModestTnyAccountStore*
900 modest_tny_account_store_new (ModestAccountMgr *account_mgr, 
901                               TnyDevice *device) 
902 {
903         GObject *obj;
904         ModestTnyAccountStorePrivate *priv;
905         TnyAccount *local_account = NULL;
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         tny_session_camel_set_ui_locker (priv->session,  tny_gtk_lockable_new ());
924                 
925         /* Connect signals */
926         priv->acc_inserted_handler = g_signal_connect (G_OBJECT(account_mgr), "account_inserted",
927                                                       G_CALLBACK (on_account_inserted), obj);
928         priv->acc_changed_handler = g_signal_connect (G_OBJECT(account_mgr), "account_changed",
929                                                       G_CALLBACK (on_account_changed), obj);
930         priv->acc_removed_handler = g_signal_connect (G_OBJECT(account_mgr), "account_removed",
931                                                       G_CALLBACK (on_account_removed), obj);
932
933         /* Create the lists of accounts */
934         priv->store_accounts = tny_simple_list_new ();
935         priv->transport_accounts = tny_simple_list_new ();
936         priv->store_accounts_outboxes = tny_simple_list_new ();
937
938         /* Create the local folders account */
939         local_account = 
940                 modest_tny_account_new_for_local_folders (priv->account_mgr, priv->session, NULL);
941         tny_list_append (priv->store_accounts, G_OBJECT(local_account));
942         g_object_unref (local_account); 
943
944         /* Add the other remote accounts. Do this before adding the
945            local account, because we need to add our outboxes to the
946            global OUTBOX hosted in the local account */
947         add_existing_accounts (MODEST_TNY_ACCOUNT_STORE (obj));
948
949         return MODEST_TNY_ACCOUNT_STORE(obj);
950 }
951
952 static void
953 modest_tny_account_store_get_accounts  (TnyAccountStore *self, 
954                                         TnyList *list,
955                                         TnyGetAccountsRequestType request_type)
956 {
957         ModestTnyAccountStorePrivate *priv;
958         
959         g_return_if_fail (self);
960         g_return_if_fail (TNY_IS_LIST(list));
961         
962         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
963         
964         switch (request_type) {
965         case TNY_ACCOUNT_STORE_BOTH:
966                 tny_list_foreach (priv->store_accounts, foreach_account_append_to_list, list);
967                 tny_list_foreach (priv->transport_accounts, foreach_account_append_to_list, list);
968                 break;
969         case TNY_ACCOUNT_STORE_STORE_ACCOUNTS:
970                 tny_list_foreach (priv->store_accounts, foreach_account_append_to_list, list);
971                 break;
972         case TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS:
973                 tny_list_foreach (priv->transport_accounts, foreach_account_append_to_list, list);
974                 break;
975         default:
976                 g_return_if_reached ();
977         }
978
979         /* Initialize session. Why do we need this ??? */
980         tny_session_camel_set_initialized (priv->session);
981 }
982
983
984 static const gchar*
985 modest_tny_account_store_get_cache_dir (TnyAccountStore *self)
986 {
987         ModestTnyAccountStorePrivate *priv;
988         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
989         
990         if (!priv->cache_dir)
991                 priv->cache_dir = g_build_filename (g_get_home_dir(), 
992                                                     MODEST_DIR, MODEST_CACHE_DIR, NULL);
993         return priv->cache_dir;
994 }
995
996
997 /*
998  * callers need to unref
999  */
1000 static TnyDevice*
1001 modest_tny_account_store_get_device (TnyAccountStore *self)
1002 {
1003         ModestTnyAccountStorePrivate *priv;
1004
1005         g_return_val_if_fail (self, NULL);
1006         
1007         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1008
1009         if (priv->device)
1010                 return g_object_ref (G_OBJECT(priv->device));
1011         else
1012                 return NULL;
1013 }
1014
1015
1016 static TnyAccount*
1017 modest_tny_account_store_find_account_by_url (TnyAccountStore *self, const gchar* url_string)
1018 {
1019         return modest_tny_account_store_get_tny_account_by (MODEST_TNY_ACCOUNT_STORE (self), 
1020                                                             MODEST_TNY_ACCOUNT_STORE_QUERY_URL,
1021                                                             url_string);
1022 }
1023
1024
1025
1026 static gboolean
1027 modest_tny_account_store_alert (TnyAccountStore *self, TnyAccount *account, TnyAlertType type,
1028                                 gboolean question, const GError *error)
1029 {
1030         g_return_val_if_fail (error, FALSE);
1031
1032         if ((error->domain != TNY_ACCOUNT_ERROR) 
1033                 && (error->domain != TNY_ACCOUNT_STORE_ERROR)) {
1034                 g_warning("modest: %s: Unexpected error domain: != TNY_ACCOUNT_ERROR: %d, message=%s", 
1035                         __FUNCTION__, error->domain, error->message); 
1036                         
1037                 return FALSE;
1038         }
1039         
1040         printf("DEBUG: %s: GError code: %d, message=%s\n", 
1041                                 __FUNCTION__, error->code, error->message);
1042         
1043         /* Get the server name: */
1044         const gchar* server_name = NULL;
1045         if (account && TNY_IS_ACCOUNT (account)) {
1046                 server_name = tny_account_get_hostname (account);
1047                 printf ("modest: %s: account name = %s, server_name=%s\n", __FUNCTION__, 
1048                         tny_account_get_id (account), server_name);
1049         }
1050         
1051         if (!server_name)
1052                 server_name = _("Unknown Server");      
1053                 
1054         ModestTransportStoreProtocol proto = MODEST_PROTOCOL_STORE_POP; /* Arbitrary default. */
1055         if (account) {
1056                 const gchar *proto_name = tny_account_get_proto (account);
1057                 if (proto_name)
1058                         proto = modest_protocol_info_get_transport_store_protocol (proto_name);
1059                 else {
1060                         g_warning("modest: %s: account with id=%s has no proto.\n", __FUNCTION__, 
1061                                 tny_account_get_id (account));
1062                 }
1063         }
1064                 
1065         /* const gchar *prompt = NULL; */
1066         gchar *prompt = NULL;
1067         switch (error->code) {
1068                 case TNY_ACCOUNT_STORE_ERROR_CANCEL_ALERT:
1069                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_USER_CANCEL:
1070                         /* Don't show waste the user's time by showing him a dialog telling 
1071                          * him that he has just cancelled something: */
1072                         g_debug ("%s: Handling GError domain=%d, code=%d (cancelled) without showing a dialog, message=%s", 
1073                                 __FUNCTION__, error->domain, error->code, error->message);
1074                         prompt = NULL;
1075                         break;
1076                         
1077                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_HOST_LOOKUP_FAILED:
1078                         /* TODO: Show the appropriate message, depending on whether it's POP or IMAP: */
1079                         g_debug ("%s: Handling GError domain=%d, code=%d (lookup failed), message=%s", 
1080                                 __FUNCTION__, error->domain, error->code, error->message);
1081                                 
1082                         switch (proto) {
1083                                 case MODEST_PROTOCOL_STORE_POP:
1084                                         prompt = g_strdup_printf (_("emev_ni_ui_pop3_msg_connect_error"), server_name);
1085                                         break;
1086                                 case MODEST_PROTOCOL_STORE_IMAP:
1087                                         prompt = g_strdup_printf (_("emev_ni_ui_imap_connect_server_error"), server_name);
1088                                         break;
1089                                 case MODEST_PROTOCOL_TRANSPORT_SMTP:
1090                                 default: /* Arbitrary default. */
1091                                         prompt = g_strdup_printf (_("emev_ib_ui_smtp_server_invalid"), server_name);
1092                                         break;
1093                         }
1094         
1095                         /*
1096                         prompt = g_strdup_printf(
1097                                 _("Incorrect Account Settings:\n Host lookup failed.%s"), 
1098                                 error->message);
1099                         */
1100                         break;
1101                         
1102                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_AUTHENTICATION_NOT_SUPPORTED:
1103                         g_debug ("%s: Handling GError domain=%d, code=%d (authentication not supported), message=%s", 
1104                                 __FUNCTION__, error->domain, error->code, error->message);
1105                         /* TODO: This needs a logical ID for the string: */
1106                         prompt = g_strdup_printf(
1107                                 _("Incorrect Account Settings:\nThe secure authentication method is not supported.\n%s"), 
1108                                 error->message);
1109                         break;
1110                         
1111                 case TNY_ACCOUNT_ERROR_TRY_CONNECT_CERTIFICATE:
1112                         g_debug ("%s: Handling GError domain=%d, code=%d (certificatae), message=%s", 
1113                                 __FUNCTION__, error->domain, error->code, error->message);
1114                         prompt = g_strdup_printf(
1115                                 _("Certificate Problem:\n%s"), 
1116                                 error->message);
1117                         break;
1118                 
1119                 case TNY_ACCOUNT_ERROR_TRY_CONNECT:
1120                 /* The tinymail camel implementation just sends us this for almost 
1121                  * everything, so we have to guess at the cause.
1122                  * It could be a wrong password, or inability to resolve a hostname, 
1123                  * or lack of network, or incorrect authentication method, or something entirely different: */
1124                 /* TODO: Fix camel to provide specific error codes, and then use the 
1125                  * specific dialog messages from Chapter 12 of the UI spec.
1126                  */
1127                 case TNY_ACCOUNT_STORE_ERROR_UNKNOWN_ALERT: 
1128                         /* This debug output is useful. Please keep it uncommented until 
1129                          * we have fixed the problems in this function: */
1130                         g_debug ("%s: Handling GError domain=%d, code=%d, message=%s", 
1131                                 __FUNCTION__, error->domain, error->code, error->message);
1132                         
1133                         /* TODO: Remove the internal error message for the real release.
1134                          * This is just so the testers can give us more information: */
1135                         /* prompt = _("Modest account not yet fully configured."); */
1136                         prompt = g_strdup_printf(
1137                                 "%s\n (Internal error message, often very misleading):\n%s", 
1138                                 _("Incorrect Account Settings"), 
1139                                 error->message);
1140                                 
1141                         /* Note: If the password was wrong then get_password() would be called again,
1142                          * instead of this vfunc being called. */
1143                          
1144                         break;
1145                 
1146                 default:
1147                         g_warning ("%s: Unhandled GError code: %d, message=%s", 
1148                                 __FUNCTION__, error->code, error->message);
1149                         prompt = NULL;
1150                 break;
1151         }
1152         
1153         if (!prompt)
1154                 return FALSE;
1155
1156         ModestWindow *main_window = 
1157                 modest_window_mgr_get_main_window (modest_runtime_get_window_mgr ());
1158         gboolean retval = TRUE;
1159         if (question) {
1160                 /* The Tinymail documentation says that we should show Yes and No buttons, 
1161                  * when it is a question.
1162                  * Obviously, we need tinymail to use more specific error codes instead,
1163                  * so we know what buttons to show. */
1164          
1165                 /* TODO: Do this in the main context: */
1166                 GtkWidget *dialog = GTK_WIDGET (hildon_note_new_confirmation (GTK_WINDOW (main_window), 
1167                         prompt));
1168                 const int response = gtk_dialog_run (GTK_DIALOG (dialog));
1169                 if (question) {
1170                         retval = (response == GTK_RESPONSE_YES) ||
1171                                          (response == GTK_RESPONSE_OK);
1172                 }
1173         
1174                 gtk_widget_destroy (dialog);
1175         
1176          } else {
1177                 /* Just show the error text and use the default response: */
1178                 modest_maemo_show_information_note_in_main_context_and_forget (GTK_WINDOW (main_window), 
1179                         prompt);
1180          }
1181         
1182         /* TODO: Don't free this when we no longer strdup the message for testers. */
1183         g_free (prompt);
1184
1185
1186         /* printf("DEBUG: %s: returning %d\n", __FUNCTION__, retval); */
1187         return retval;
1188 }
1189
1190
1191 static void
1192 modest_tny_account_store_init (gpointer g, gpointer iface_data)
1193 {
1194         TnyAccountStoreIface *klass;
1195
1196         g_return_if_fail (g);
1197
1198         klass = (TnyAccountStoreIface *)g;
1199
1200         klass->get_accounts_func =
1201                 modest_tny_account_store_get_accounts;
1202         klass->get_cache_dir_func =
1203                 modest_tny_account_store_get_cache_dir;
1204         klass->get_device_func =
1205                 modest_tny_account_store_get_device;
1206         klass->alert_func =
1207                 modest_tny_account_store_alert;
1208         klass->find_account_func =
1209                 modest_tny_account_store_find_account_by_url;
1210 }
1211
1212 void
1213 modest_tny_account_store_set_get_pass_func (ModestTnyAccountStore *self,
1214                                             ModestTnyGetPassFunc func)
1215 {
1216         /* not implemented, we use signals */
1217         g_printerr ("modest: set_get_pass_func not implemented\n");
1218 }
1219
1220 TnySessionCamel*
1221 modest_tny_account_store_get_session  (TnyAccountStore *self)
1222 {
1223         g_return_val_if_fail (self, NULL);
1224         return MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self)->session;
1225 }
1226
1227 static TnyAccount*
1228 get_tny_account_by (TnyList *accounts,
1229                     ModestTnyAccountStoreQueryType type,
1230                     const gchar *str)
1231 {
1232         TnyIterator *iter = NULL;
1233         gboolean found = FALSE;
1234         TnyAccount *retval = NULL;
1235
1236         iter = tny_list_create_iterator (accounts);
1237         while (!tny_iterator_is_done (iter) && !found) {
1238                 TnyAccount *tmp_account = NULL;
1239                 const gchar *val = NULL;
1240
1241                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1242                 switch (type) {
1243                 case MODEST_TNY_ACCOUNT_STORE_QUERY_ID:
1244                         val = tny_account_get_id (tmp_account);
1245                         break;
1246                 case MODEST_TNY_ACCOUNT_STORE_QUERY_URL:
1247                         val = tny_account_get_url_string (tmp_account);
1248                         break;
1249                 }
1250                 
1251                 if (type == MODEST_TNY_ACCOUNT_STORE_QUERY_URL && 
1252                     tny_account_matches_url_string (tmp_account, str)) {
1253                         retval = g_object_ref (tmp_account);
1254                         found = TRUE;
1255                 } else {
1256                         if (strcmp (val, str) == 0) {
1257                                 retval = g_object_ref (tmp_account);
1258                                 found = TRUE;
1259                         }
1260                 }
1261                 g_object_unref (tmp_account);
1262                 tny_iterator_next (iter);
1263         }
1264         g_object_unref (iter);
1265
1266         return retval;
1267 }
1268
1269 TnyAccount*
1270 modest_tny_account_store_get_tny_account_by (ModestTnyAccountStore *self, 
1271                                              ModestTnyAccountStoreQueryType type,
1272                                              const gchar *str)
1273 {
1274         TnyAccount *account = NULL;
1275         ModestTnyAccountStorePrivate *priv;     
1276         
1277         g_return_val_if_fail (self, NULL);
1278         g_return_val_if_fail (str, NULL);
1279         
1280         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1281         
1282         /* Search in store accounts */
1283         account = get_tny_account_by (priv->store_accounts, type, str);
1284
1285         /* If we already found something, no need to search the transport accounts */
1286         if (!account) {
1287                 account = get_tny_account_by (priv->transport_accounts, type, str);
1288
1289                 /* If we already found something, no need to search the
1290                    per-account outbox accounts */
1291                 if (!account)
1292                         account = get_tny_account_by (priv->store_accounts_outboxes, type, str);
1293         }
1294
1295         /* Warn if nothing was found. This is generally unusual. */
1296         if (!account) {
1297                 g_warning("%s: Failed to find account with %s=%s\n", 
1298                           __FUNCTION__, 
1299                           (type == MODEST_TNY_ACCOUNT_STORE_QUERY_ID) ? "ID" : "URL",                     
1300                           str);
1301         }
1302
1303         /* Returns a new reference to the account if found */   
1304         return account;
1305 }
1306
1307 TnyAccount*
1308 modest_tny_account_store_get_server_account (ModestTnyAccountStore *self,
1309                                              const gchar *account_name,
1310                                              TnyAccountType type)
1311 {
1312         ModestTnyAccountStorePrivate *priv = NULL;
1313         TnyAccount *retval = NULL;
1314         TnyList *account_list = NULL;
1315         TnyIterator *iter = NULL;
1316         gboolean found;
1317
1318         g_return_val_if_fail (self, NULL);
1319         g_return_val_if_fail (account_name, NULL);
1320         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || 
1321                               type == TNY_ACCOUNT_TYPE_TRANSPORT,
1322                               NULL);
1323         
1324         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1325
1326         account_list = (type == TNY_ACCOUNT_TYPE_STORE) ? 
1327                 priv->store_accounts : 
1328                 priv->transport_accounts;
1329
1330         if (!account_list) {
1331                 g_printerr ("%s: No server accounts of type %s\n", __FUNCTION__, 
1332                         (type == TNY_ACCOUNT_TYPE_STORE) ? "store" : "transport");
1333                 return NULL;
1334         }
1335         
1336         /* Look for the server account */
1337         found = FALSE;
1338         iter = tny_list_create_iterator (account_list);
1339         while (!tny_iterator_is_done (iter) && !found) {
1340                 const gchar *modest_acc_name;
1341                 TnyAccount *tmp_account;
1342
1343                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1344                 modest_acc_name = 
1345                         modest_tny_account_get_parent_modest_account_name_for_server_account (tmp_account);
1346                 
1347                 if (!strcmp (account_name, modest_acc_name)) {
1348                         found = TRUE;
1349                         retval = g_object_ref (tmp_account);
1350                 }
1351                 /* Free and continue */
1352                 g_object_unref (tmp_account);
1353                 tny_iterator_next (iter);
1354         }
1355
1356         if (!found) {
1357                 g_printerr ("modest: %s: could not get tny %s account for %s\n." \
1358                             "Number of server accounts of this type=%d\n", __FUNCTION__,
1359                             (type == TNY_ACCOUNT_TYPE_STORE) ? "store" : "transport",
1360                             account_name, tny_list_get_length (account_list));
1361         }
1362
1363         /* Returns a new reference */
1364         return retval;
1365 }
1366
1367 static TnyAccount*
1368 get_smtp_specific_transport_account_for_open_connection (ModestTnyAccountStore *self,
1369                                                          const gchar *account_name)
1370 {
1371         /* Get the current connection: */
1372         TnyDevice *device = modest_runtime_get_device ();
1373         
1374         if (!tny_device_is_online (device))
1375                 return NULL;
1376
1377         g_return_val_if_fail (self, NULL);
1378         g_return_val_if_fail (account_name, NULL);
1379         
1380         
1381 #ifdef MODEST_PLATFORM_MAEMO
1382         g_assert (TNY_IS_MAEMO_CONIC_DEVICE (device));
1383         TnyMaemoConicDevice *maemo_device = TNY_MAEMO_CONIC_DEVICE (device);    
1384         const gchar* iap_id = tny_maemo_conic_device_get_current_iap_id (maemo_device);
1385         /* printf ("DEBUG: %s: iap_id=%s\n", __FUNCTION__, iap_id); */
1386         if (!iap_id)
1387                 return NULL;
1388                 
1389         ConIcIap* connection = tny_maemo_conic_device_get_iap (maemo_device, iap_id);
1390         if (!connection)
1391                 return NULL;
1392                 
1393         const gchar *connection_name = con_ic_iap_get_name (connection);
1394         /* printf ("DEBUG: %s: connection_name=%s\n", __FUNCTION__, connection_name); */
1395         if (!connection_name)
1396                 return NULL;
1397         
1398         /*  Get the connection-specific transport acccount, if any: */
1399         ModestAccountMgr *account_manager = modest_runtime_get_account_mgr ();
1400         gchar* server_account_name = modest_account_mgr_get_connection_specific_smtp (account_manager, 
1401                 account_name, connection_name);
1402
1403         /* printf ("DEBUG: %s: server_account_name=%s\n", __FUNCTION__, server_account_name); */
1404         if (!server_account_name) {
1405                 return NULL; /* No connection-specific SMTP server was specified for this connection. */
1406         }
1407                 
1408         TnyAccount* account = modest_tny_account_store_get_tny_account_by (self, 
1409                                                                            MODEST_TNY_ACCOUNT_STORE_QUERY_ID, 
1410                                                                            server_account_name);
1411
1412         /* printf ("DEBUG: %s: account=%p\n", __FUNCTION__, account); */
1413         g_free (server_account_name);   
1414
1415         /* Unref the get()ed object, as required by the tny_maemo_conic_device_get_iap() documentation. */
1416         g_object_unref (connection);
1417         
1418         return account;
1419 #else
1420         return NULL; /* TODO: Implement this for GNOME, instead of just Maemo? */
1421 #endif /* MODEST_PLATFORM_MAEMO */
1422 }
1423
1424                                                                  
1425 TnyAccount*
1426 modest_tny_account_store_get_transport_account_for_open_connection (ModestTnyAccountStore *self,
1427                                                                     const gchar *account_name)
1428 {
1429         g_return_val_if_fail (self, NULL);
1430         g_return_val_if_fail (account_name, NULL);
1431
1432         if (!account_name || !self)
1433                 return NULL;
1434         
1435         /*  Get the connection-specific transport acccount, if any: */
1436         TnyAccount *account =
1437                 get_smtp_specific_transport_account_for_open_connection (self, account_name);
1438                         
1439         /* If there is no connection-specific transport account (the common case), 
1440          * just get the regular transport account: */
1441         if (!account) {
1442                 /* The special local folders don't have transport accounts. */
1443                 if (strcmp (account_name, MODEST_LOCAL_FOLDERS_ACCOUNT_ID) == 0)
1444                         account = NULL;
1445                 else
1446                         account = modest_tny_account_store_get_server_account (self, account_name, 
1447                                                      TNY_ACCOUNT_TYPE_TRANSPORT);
1448         }
1449                              
1450         return account;
1451 }
1452
1453 TnyAccount*
1454 modest_tny_account_store_get_local_folders_account (ModestTnyAccountStore *self)
1455 {
1456         TnyAccount *account = NULL;
1457         ModestTnyAccountStorePrivate *priv;
1458         TnyIterator *iter;
1459         gboolean found;
1460
1461         g_return_val_if_fail (MODEST_IS_TNY_ACCOUNT_STORE (self), NULL);
1462         
1463         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1464
1465         found = FALSE;
1466         iter = tny_list_create_iterator (priv->store_accounts);
1467         while (!tny_iterator_is_done (iter) && !found) {
1468                 TnyAccount *tmp_account;
1469
1470                 tmp_account = TNY_ACCOUNT (tny_iterator_get_current (iter));
1471                 if (modest_tny_account_is_virtual_local_folders (tmp_account)) {
1472                         account = g_object_ref (tmp_account);
1473                         found = TRUE;
1474                 }
1475                 g_object_unref (tmp_account);
1476                 tny_iterator_next (iter);
1477         }
1478         g_object_unref (iter);
1479
1480         /* Returns a new reference to the account */
1481         return account;
1482 }
1483
1484 /*********************************************************************************/
1485 static void
1486 add_existing_accounts (ModestTnyAccountStore *self)
1487 {
1488         GSList *account_names = NULL, *iter = NULL;
1489         ModestTnyAccountStorePrivate *priv = NULL;
1490         
1491         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1492
1493         /* These are account names, not server_account names */
1494         account_names = modest_account_mgr_account_names (priv->account_mgr, FALSE);
1495
1496         for (iter = account_names; iter != NULL; iter = g_slist_next (iter)) {
1497                 const gchar *account_name = (const gchar*) iter->data;
1498                 
1499                 /* Insert all enabled accounts without notifying */
1500                 if (modest_account_mgr_get_enabled (priv->account_mgr, account_name))
1501                         insert_account (self, account_name, FALSE);
1502         }
1503         modest_account_mgr_free_account_names (account_names);
1504 }
1505
1506 static TnyAccount*
1507 create_tny_account (ModestTnyAccountStore *self,
1508                     const gchar *name,
1509                     TnyAccountType type)
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                 modest_tny_account_store_forget_password_in_memory (self, 
1526                                                                     tny_account_get_id (account));
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 /*
1537  * This function will be used for both adding new accounts and for the
1538  * initialization. In the initialization we do not want to emit
1539  * signals so notify will be FALSE, in the case of account additions
1540  * we do want to notify the observers
1541  */
1542 static void
1543 insert_account (ModestTnyAccountStore *self,
1544                 const gchar *account,
1545                 gboolean notify)
1546 {
1547         ModestTnyAccountStorePrivate *priv = NULL;
1548         TnyAccount *store_account = NULL, *transport_account = NULL;
1549         
1550         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1551
1552         /* Get the server and the transport account */
1553         store_account = create_tny_account (self, account, TNY_ACCOUNT_TYPE_STORE);
1554         transport_account = create_tny_account (self, account, TNY_ACCOUNT_TYPE_TRANSPORT);
1555
1556         /* Add to the list, and notify the observers */
1557         if (store_account) {
1558                 tny_list_append (priv->store_accounts, G_OBJECT (store_account));
1559                 if (notify)
1560                         g_signal_emit (G_OBJECT (self), signals [ACCOUNT_INSERTED_SIGNAL], 0, store_account);
1561                 g_object_unref (store_account);
1562         }
1563
1564         /* Add to the list, and notify the observers */
1565         if (transport_account) {
1566                 TnyAccount *account_outbox = NULL, *local_account = NULL;
1567                 TnyFolder *per_account_outbox = NULL;
1568                 TnyList *folders;
1569                 TnyIterator *iter_folders;
1570
1571                 /* Add account to the list */
1572                 tny_list_append (priv->transport_accounts, G_OBJECT (transport_account));
1573
1574                 /* Add connection-specific transport accounts */
1575                 add_connection_specific_transport_accounts (self, account);
1576
1577                 /* Create per account local outbox */
1578                 account_outbox = 
1579                         modest_tny_account_new_for_per_account_local_outbox_folder (priv->account_mgr, 
1580                                                                                     account, 
1581                                                                                     priv->session);
1582                 tny_list_append (priv->store_accounts_outboxes, G_OBJECT (account_outbox));
1583
1584                 /* Get the outbox folder */
1585                 folders = tny_simple_list_new ();
1586                 tny_folder_store_get_folders (TNY_FOLDER_STORE (account_outbox),
1587                                               folders, NULL, NULL);
1588                 g_assert (tny_list_get_length (folders) == 1);
1589                 iter_folders = tny_list_create_iterator (folders);
1590                 per_account_outbox = TNY_FOLDER (tny_iterator_get_current (iter_folders));
1591                 g_object_unref (iter_folders);
1592                 g_object_unref (account_outbox);
1593
1594                 /* Add the outbox of the new per-account-local-outbox
1595                    account to the global local merged OUTBOX of the
1596                    local folders account */
1597                 local_account = modest_tny_account_store_get_local_folders_account (MODEST_TNY_ACCOUNT_STORE (self));
1598                 modest_tny_local_folders_account_add_folder_to_outbox (MODEST_TNY_LOCAL_FOLDERS_ACCOUNT (local_account), 
1599                                                                        per_account_outbox);
1600                 g_object_unref (local_account);
1601                 g_object_unref (per_account_outbox);
1602
1603                 /* Notify the observers */
1604                 if (notify)
1605                         g_signal_emit (G_OBJECT (self), signals [ACCOUNT_INSERTED_SIGNAL], 0, transport_account);
1606                 g_object_unref (transport_account);
1607         }
1608 }
1609
1610 static void
1611 on_account_inserted (ModestAccountMgr *acc_mgr, 
1612                      const gchar *account,
1613                      gpointer user_data)
1614 {
1615         /* Insert the account and notify the observers */
1616         insert_account (MODEST_TNY_ACCOUNT_STORE (user_data), account, TRUE);
1617 }
1618
1619 static void
1620 on_account_removed (ModestAccountMgr *acc_mgr, 
1621                     const gchar *account,
1622                     gpointer user_data)
1623 {
1624         TnyAccount *store_account = NULL, *transport_account = NULL;
1625         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
1626         
1627         /* Get the server and the transport account */
1628         store_account = 
1629                 modest_tny_account_store_get_server_account (self, account, TNY_ACCOUNT_TYPE_STORE);
1630         transport_account = 
1631                 modest_tny_account_store_get_server_account (self, account, TNY_ACCOUNT_TYPE_TRANSPORT);
1632
1633         /* If there was any problem creating the account, for example,
1634            with the configuration system this could not exist */
1635         if (store_account) {
1636                 /* Clear the cache */
1637                 tny_store_account_delete_cache (TNY_STORE_ACCOUNT (store_account));
1638
1639                 /* Notify the observers */
1640                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_REMOVED_SIGNAL], 0, store_account);
1641                 g_object_unref (store_account);
1642         } else {
1643                 g_warning ("There is no store account for account %s\n", account);
1644         }
1645
1646         /* If there was any problem creating the account, for example,
1647            with the configuration system this could not exist */
1648         if (transport_account) {
1649                 /* Notify the observers */
1650                 g_signal_emit (G_OBJECT (self), signals [ACCOUNT_REMOVED_SIGNAL], 0, transport_account);
1651                 g_object_unref (transport_account);
1652         } else {
1653                 g_warning ("There is no transport account for account %s\n", account);
1654         }
1655 }
1656
1657 static void
1658 add_connection_specific_transport_accounts (ModestTnyAccountStore *self,
1659                                             const gchar *account_name)
1660 {
1661         ModestTnyAccountStorePrivate *priv = NULL;
1662         GSList *list_specifics = NULL, *iter = NULL;
1663
1664         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
1665
1666         list_specifics = modest_account_mgr_get_list (priv->account_mgr,
1667                                                       account_name, 
1668                                                       MODEST_ACCOUNT_CONNECTION_SPECIFIC_SMTP_LIST,
1669                                                       MODEST_CONF_VALUE_STRING, FALSE);
1670                                 
1671         /* Look at each connection-specific transport account for the 
1672          * modest account: */
1673         iter = list_specifics;
1674         while (iter) {
1675                 /* The list alternates between the connection name and the transport name: */
1676                 iter = g_slist_next (iter);
1677                 if (iter) {
1678                         const gchar* transport_account_name = (const gchar*) (iter->data);
1679                         if (transport_account_name) {
1680                                 TnyAccount * tny_account = NULL;
1681                                 /* Add the account: */
1682                                 tny_account = 
1683                                         modest_tny_account_new_from_server_account_name (priv->account_mgr, 
1684                                                                                          priv->session, 
1685                                                                                          transport_account_name);
1686                                 if (tny_account) {
1687                                         modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account, 
1688                                                                                                               account_name);
1689                                         g_object_set_data (G_OBJECT(tny_account), 
1690                                                            "account_store", 
1691                                                            (gpointer)self);
1692
1693                                         tny_list_append (priv->transport_accounts, G_OBJECT (tny_account));
1694                                 } else
1695                                         g_printerr ("modest: failed to create smtp-specific account for %s\n",
1696                                                     transport_account_name);
1697                         }
1698                 }                               
1699                 iter = g_slist_next (iter);
1700         }
1701 }