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