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