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