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