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