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