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