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