2007-05-28 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-account-mgr.h>
50 #include <modest-account-mgr-helpers.h>
51
52 #include "modest-tny-account-store.h"
53 #include "modest-tny-platform-factory.h"
54 #include <tny-gtk-lockable.h>
55 #include <camel/camel.h>
56
57 #ifdef MODEST_PLATFORM_MAEMO
58 #include <tny-maemo-conic-device.h>
59 #ifdef MODEST_HILDON_VERSION_0
60 #include <hildon-widgets/hildon-note.h>
61 #else
62 #include <hildon/hildon-note.h>
63 #endif
64 #endif
65
66 /* 'private'/'protected' functions */
67 static void modest_tny_account_store_class_init   (ModestTnyAccountStoreClass *klass);
68 //static void modest_tny_account_store_init         (ModestTnyAccountStore *obj);
69 static void modest_tny_account_store_finalize     (GObject *obj);
70
71 /* implementations for tny-account-store-iface */
72 static void    modest_tny_account_store_instance_init (ModestTnyAccountStore *obj);
73 static void    modest_tny_account_store_init          (gpointer g, gpointer iface_data);
74
75
76 static void
77 get_server_accounts  (TnyAccountStore *self, TnyList *list, TnyAccountType type);
78
79
80 /* list my signals */
81 enum {
82         ACCOUNT_UPDATE_SIGNAL,
83         PASSWORD_REQUESTED_SIGNAL,
84         LAST_SIGNAL
85 };
86
87 typedef struct _ModestTnyAccountStorePrivate ModestTnyAccountStorePrivate;
88 struct _ModestTnyAccountStorePrivate {
89         gchar              *cache_dir;  
90         GHashTable         *password_hash;
91         ModestAccountMgr   *account_mgr;
92         TnySessionCamel    *session;
93         TnyDevice          *device;
94         
95         /* We cache the lists of accounts here.
96          * They are created in our get_accounts_func() implementation. */
97         GSList             *store_accounts;
98         GSList             *transport_accounts;
99         
100         /* This is also contained in store_accounts,
101          * but we cached it temporarily separately, 
102          * because we create this while creating the transport accounts, 
103          * but return it when requesting the store accounts: 
104          */
105         GSList             *store_accounts_outboxes;
106 };
107
108 #define MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(o)      (G_TYPE_INSTANCE_GET_PRIVATE((o), \
109                                                       MODEST_TYPE_TNY_ACCOUNT_STORE, \
110                                                       ModestTnyAccountStorePrivate))
111
112 /* globals */
113 static GObjectClass *parent_class = NULL;
114
115 static guint signals[LAST_SIGNAL] = {0};
116
117 GType
118 modest_tny_account_store_get_type (void)
119 {
120         static GType my_type = 0;
121
122         if (!my_type) {
123                 static const GTypeInfo my_info = {
124                         sizeof(ModestTnyAccountStoreClass),
125                         NULL,           /* base init */
126                         NULL,           /* base finalize */
127                         (GClassInitFunc) modest_tny_account_store_class_init,
128                         NULL,           /* class finalize */
129                         NULL,           /* class data */
130                         sizeof(ModestTnyAccountStore),
131                         0,              /* n_preallocs */
132                         (GInstanceInitFunc) modest_tny_account_store_instance_init,
133                         NULL
134                 };
135
136                 static const GInterfaceInfo iface_info = {
137                         (GInterfaceInitFunc) modest_tny_account_store_init,
138                         NULL,         /* interface_finalize */
139                         NULL          /* interface_data */
140                 };
141                 /* hack hack */
142                 my_type = g_type_register_static (G_TYPE_OBJECT,
143                                                   "ModestTnyAccountStore",
144                                                   &my_info, 0);
145                 g_type_add_interface_static (my_type, TNY_TYPE_ACCOUNT_STORE,
146                                              &iface_info);
147         }
148         return my_type;
149 }
150
151 static void
152 modest_tny_account_store_class_init (ModestTnyAccountStoreClass *klass)
153 {
154         GObjectClass *gobject_class;
155         gobject_class = (GObjectClass*) klass;
156
157         parent_class            = g_type_class_peek_parent (klass);
158         gobject_class->finalize = modest_tny_account_store_finalize;
159
160         g_type_class_add_private (gobject_class,
161                                   sizeof(ModestTnyAccountStorePrivate));
162
163          signals[ACCOUNT_UPDATE_SIGNAL] =
164                 g_signal_new ("account_update",
165                               G_TYPE_FROM_CLASS (gobject_class),
166                               G_SIGNAL_RUN_FIRST,
167                               G_STRUCT_OFFSET(ModestTnyAccountStoreClass, account_update),
168                               NULL, NULL,
169                               g_cclosure_marshal_VOID__STRING,
170                               G_TYPE_NONE, 1, G_TYPE_STRING);
171          
172          signals[PASSWORD_REQUESTED_SIGNAL] =
173                  g_signal_new ("password_requested",
174                                G_TYPE_FROM_CLASS (gobject_class),
175                                G_SIGNAL_RUN_FIRST,
176                                G_STRUCT_OFFSET(ModestTnyAccountStoreClass, password_requested),
177                                NULL, NULL,
178                                modest_marshal_VOID__STRING_POINTER_POINTER_POINTER_POINTER,
179                                G_TYPE_NONE, 5, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_POINTER, G_TYPE_POINTER,
180                                G_TYPE_POINTER);
181 }
182
183
184 static void
185 modest_tny_account_store_instance_init (ModestTnyAccountStore *obj)
186 {
187         ModestTnyAccountStorePrivate *priv =
188                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
189
190         priv->cache_dir              = NULL;
191         priv->account_mgr            = NULL;
192         priv->session                = NULL;
193         priv->device                 = NULL;
194         
195         /* An in-memory store of passwords, 
196          * for passwords that are not remembered in the configuration,
197          * so they need to be asked for from the user once in each session:
198          */
199         priv->password_hash          = g_hash_table_new_full (g_str_hash, g_str_equal,
200                                                               g_free, g_free);
201 }
202
203
204
205 static void
206 account_list_free (GSList *accounts)
207 {
208         GSList *cursor = accounts;
209
210         while (cursor) {
211                 if (G_IS_OBJECT(cursor->data)) { /* check twice... */
212                         const gchar *id = tny_account_get_id(TNY_ACCOUNT(cursor->data));
213                         modest_runtime_verify_object_last_ref(cursor->data,id);
214                 }                       
215                 g_object_unref (G_OBJECT(cursor->data));
216                 cursor = cursor->next;
217         }
218         g_slist_free (accounts);
219 }
220
221
222 static void
223 on_account_removed (ModestAccountMgr *acc_mgr, const gchar *account, gboolean server_account,
224                     gpointer user_data)
225 {
226         ModestTnyAccountStore *self        = MODEST_TNY_ACCOUNT_STORE(user_data);
227         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
228
229         /* FIXME: make this more finegrained; changes do not really affect _all_
230          * accounts, and some do not affect tny accounts at all (such as 'last_update')
231          */
232         
233         account_list_free (priv->store_accounts);
234         get_server_accounts (TNY_ACCOUNT_STORE(self), NULL, TNY_ACCOUNT_TYPE_STORE);
235         
236         account_list_free (priv->transport_accounts);
237         get_server_accounts (TNY_ACCOUNT_STORE(self), NULL,
238                                                         TNY_ACCOUNT_TYPE_TRANSPORT);
239                 
240         /* TODO: Ref these when we add them? */
241         g_slist_free (priv->store_accounts_outboxes);
242         priv->store_accounts_outboxes = NULL;
243         
244         g_signal_emit (G_OBJECT(self), signals[ACCOUNT_UPDATE_SIGNAL], 0,
245                        account);
246 }
247
248
249 static void
250 on_account_changed (ModestAccountMgr *acc_mgr, const gchar *account,
251                     const gchar *key, gboolean server_account, gpointer user_data)
252
253 {
254         ModestTnyAccountStore *self = MODEST_TNY_ACCOUNT_STORE(user_data);
255         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
256         
257         /* FIXME: make this more finegrained; changes do not really affect _all_
258          * accounts, and some do not affect tny accounts at all (such as 'last_update')
259          */
260         if (server_account) {
261                 if (priv->store_accounts) {
262                         account_list_free (priv->store_accounts);
263                         priv->store_accounts = NULL;
264                         get_server_accounts (TNY_ACCOUNT_STORE(self),
265                                                      NULL, TNY_ACCOUNT_TYPE_STORE);
266                 }
267                 
268                 if (priv->transport_accounts) {
269                         account_list_free (priv->transport_accounts);
270                         priv->transport_accounts = NULL;
271                         get_server_accounts (TNY_ACCOUNT_STORE(self), NULL,
272                                                      TNY_ACCOUNT_TYPE_TRANSPORT);
273                 }
274         }
275
276         g_signal_emit (G_OBJECT(self), signals[ACCOUNT_UPDATE_SIGNAL], 0,
277                        account);
278 }
279
280
281 static ModestTnyAccountStore*
282 get_account_store_for_account (TnyAccount *account)
283 {
284         return MODEST_TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
285                                                            "account_store"));
286 }
287
288 /* This callback will be called by Tinymail when it needs the password
289  * from the user, for instance if the password was not remembered.
290  * Note that TnyAccount here will be the server account. */
291 static gchar*
292 get_password (TnyAccount *account, const gchar *prompt, gboolean *cancel)
293 {
294         /* Initialize the output parameter: */
295         if (cancel)
296           *cancel = FALSE;
297           
298         const gchar *key;
299         const TnyAccountStore *account_store;
300         ModestTnyAccountStore *self;
301         ModestTnyAccountStorePrivate *priv;
302         gchar *username = NULL;
303         gchar *pwd = NULL;
304         gpointer pwd_ptr;
305         gboolean already_asked;
306         
307         key           = tny_account_get_id (account);
308         account_store = TNY_ACCOUNT_STORE(get_account_store_for_account (account));
309         
310         self = MODEST_TNY_ACCOUNT_STORE (account_store);
311         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
312         
313         /* This hash map stores passwords, including passwords that are not stored in gconf. */
314         /* is it in the hash? if it's already there, it must be wrong... */
315         pwd_ptr = (gpointer)&pwd; /* pwd_ptr so the compiler does not complained about
316                                    * type-punned ptrs...*/
317         already_asked = g_hash_table_lookup_extended (priv->password_hash,
318                                                       key,
319                                                       NULL,
320                                                       (gpointer*)&pwd_ptr);
321
322         /* if the password is not already there, try ModestConf */
323         if (!already_asked) {
324                 pwd  = modest_account_mgr_get_string (priv->account_mgr,
325                                                       key, MODEST_ACCOUNT_PASSWORD, TRUE);
326                 g_hash_table_insert (priv->password_hash, g_strdup (key), g_strdup (pwd));
327         }
328
329         /* if it was already asked, it must have been wrong, so ask again */
330         if (already_asked || !pwd || strlen(pwd) == 0) {
331                 /* we don't have it yet. Get the password from the user */
332                 const gchar* account_id = tny_account_get_id (account);
333                 gboolean remember = FALSE;
334                 pwd = NULL;
335                 
336                 /* Note that we ignore the returned username here,
337                  * because it is enough that it will be stored in gconf 
338                  * by the signal handler. */
339                 g_signal_emit (G_OBJECT(self), signals[PASSWORD_REQUESTED_SIGNAL], 0,
340                                account_id, /* server_account_name */
341                                &username, &pwd, cancel, &remember);
342                 
343                 if (!*cancel) {
344                         if (remember)
345                                 modest_account_mgr_set_string (priv->account_mgr,key,
346                                                                MODEST_ACCOUNT_PASSWORD,
347                                                                pwd, TRUE);
348                         /* We need to dup the string even knowing that
349                            it's already a dup of the contents of an
350                            entry, because it if it's wrong, then camel
351                            will free it */
352                         g_hash_table_insert (priv->password_hash, g_strdup (key), g_strdup(pwd));
353                 } else {
354                         g_hash_table_remove (priv->password_hash, key);
355                         
356                         g_free (pwd);
357                         pwd = NULL;
358                 }
359
360                 g_free (username);
361                 username = NULL;
362         } else
363                 *cancel = FALSE;
364  
365     /* printf("  DEBUG: %s: returning %s\n", __FUNCTION__, pwd); */
366         
367         return pwd;
368 }
369
370 /* tinymail calls this if the connection failed due to an incorrect password.
371  * And it seems to call this for any general connection failure. */
372 static void
373 forget_password (TnyAccount *account)
374 {
375         printf ("DEBUG: %s\n", __FUNCTION__);
376         ModestTnyAccountStore *self;
377         ModestTnyAccountStorePrivate *priv;
378         const TnyAccountStore *account_store;
379         gchar *pwd;
380         const gchar *key;
381         
382         account_store = TNY_ACCOUNT_STORE(get_account_store_for_account (account));
383         self = MODEST_TNY_ACCOUNT_STORE (account_store);
384         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
385         key  = tny_account_get_id (account);
386
387         /* Do not remove the key, this will allow us to detect that we
388            have already asked for it at least once */
389         pwd = g_hash_table_lookup (priv->password_hash, key);
390         if (pwd) {
391                 memset (pwd, 0, strlen (pwd));
392                 g_hash_table_insert (priv->password_hash, g_strdup (key), NULL);
393         }
394
395         /* Remove from configuration system */
396         modest_account_mgr_unset (priv->account_mgr,
397                                   key, MODEST_ACCOUNT_PASSWORD, TRUE);
398 }
399
400
401 static void
402 modest_tny_account_store_finalize (GObject *obj)
403 {
404         ModestTnyAccountStore *self        = MODEST_TNY_ACCOUNT_STORE(obj);
405         ModestTnyAccountStorePrivate *priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
406         
407         //gboolean debug = modest_runtime_get_debug_flags() & MODEST_RUNTIME_DEBUG_DEBUG_OBJECTS;
408
409         g_free (priv->cache_dir);
410         priv->cache_dir = NULL;
411         
412         if (priv->password_hash) {
413                 g_hash_table_destroy (priv->password_hash);
414                 priv->password_hash = NULL;
415         }
416
417         if (priv->account_mgr) {
418                 g_object_unref (G_OBJECT(priv->account_mgr));
419                 priv->account_mgr = NULL;
420         }
421
422         if (priv->device) {
423                 g_object_unref (G_OBJECT(priv->device));
424                 priv->device = NULL;
425         }
426
427         /* this includes the local folder */
428         account_list_free (priv->store_accounts);
429         priv->store_accounts = NULL;
430         
431         account_list_free (priv->transport_accounts);
432         priv->transport_accounts = NULL;
433
434         if (priv->session) {
435                 camel_object_unref (CAMEL_OBJECT(priv->session));
436                 priv->session = NULL;
437         }
438         
439         G_OBJECT_CLASS(parent_class)->finalize (obj);
440 }
441
442
443 ModestTnyAccountStore*
444 modest_tny_account_store_new (ModestAccountMgr *account_mgr, TnyDevice *device) {
445
446         GObject *obj;
447         ModestTnyAccountStorePrivate *priv;
448         TnyList *list; 
449         
450         g_return_val_if_fail (account_mgr, NULL);
451         g_return_val_if_fail (device, NULL);
452
453         obj  = G_OBJECT(g_object_new(MODEST_TYPE_TNY_ACCOUNT_STORE, NULL));
454         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(obj);
455
456         priv->account_mgr = g_object_ref (G_OBJECT(account_mgr));
457         priv->device = g_object_ref (device);
458         
459         priv->session = tny_session_camel_new (TNY_ACCOUNT_STORE(obj));
460         
461         tny_session_camel_set_ui_locker (priv->session,  tny_gtk_lockable_new ());
462         /* FIXME: unref this in the end? */
463         tny_session_camel_set_async_connecting (priv->session, TRUE);
464         
465         /* force a cache fill... ugly */
466         list = TNY_LIST(tny_simple_list_new());
467         tny_account_store_get_accounts (TNY_ACCOUNT_STORE(obj), list,
468                                         TNY_ACCOUNT_STORE_BOTH);
469         g_object_unref(list);
470         
471         /* Connect signals */
472         g_signal_connect (G_OBJECT(account_mgr), "account_changed",
473                                        G_CALLBACK (on_account_changed), obj);
474         g_signal_connect (G_OBJECT(account_mgr), "account_removed",
475                                        G_CALLBACK (on_account_removed), obj);
476
477         return MODEST_TNY_ACCOUNT_STORE(obj);
478 }
479
480 /** Fill the TnyList from the appropriate cached GSList of accounts. */
481 static void
482 get_cached_accounts (TnyAccountStore *self, TnyList *list, TnyAccountType type)
483 {
484         ModestTnyAccountStorePrivate *priv;
485         GSList                       *accounts, *cursor;
486         
487         priv     = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
488         accounts = (type == TNY_ACCOUNT_TYPE_STORE ? priv->store_accounts : priv->transport_accounts);
489
490         cursor = accounts;
491         while (cursor) {
492                 tny_list_prepend (list, G_OBJECT(cursor->data));
493                 cursor = cursor->next;
494         }
495 }
496
497 static void
498 create_per_account_local_outbox_folders (TnyAccountStore *self)
499 {
500         g_return_if_fail (self);
501         
502         ModestTnyAccountStorePrivate *priv = 
503                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
504         
505         /* printf("DEBUG: %s: priv->store_accounts_outboxes = %p\n", __FUNCTION__, priv->store_accounts_outboxes); */
506         
507         GSList *accounts = NULL;
508         
509         GSList *account_names  = modest_account_mgr_account_names (priv->account_mgr, 
510                 TRUE /* including disabled accounts */);
511         
512         GSList *iter = NULL;
513         for (iter = account_names; iter; iter = g_slist_next (iter)) {
514                 
515                 const gchar* account_name = (const gchar*)iter->data;
516                 
517                 /* Create a per-account local outbox folder (a _store_ account) 
518                  * for each _transport_ account: */
519                 TnyAccount *tny_account_outbox =
520                         modest_tny_account_new_for_per_account_local_outbox_folder (
521                                 priv->account_mgr, account_name, priv->session);
522                                 
523                 accounts = g_slist_append (accounts, tny_account_outbox); /* cache it */
524         };
525         
526         g_slist_free (account_names);
527         
528         priv->store_accounts_outboxes = accounts;
529 }
530
531 /* This function fills the TnyList, and also stores a GSList of the accounts,
532  * for caching purposes. It creates the TnyAccount objects if necessary.
533  * The @list parameter may be NULL, if you just want to fill the cache.
534  */
535 static void
536 get_server_accounts  (TnyAccountStore *self, TnyList *list, TnyAccountType type)
537 {
538         g_return_if_fail (self);
539         
540         /* printf ("DEBUG: %s: list=%p, type=%d\n", __FUNCTION__, list, type); */
541                 
542         ModestTnyAccountStorePrivate *priv = 
543                 MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
544                 
545         /* Do nothing if the accounts are already cached: */
546         if (type == TNY_ACCOUNT_TYPE_STORE) {
547                         if (priv->store_accounts)
548                                 return;
549         } else if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
550                         if (priv->transport_accounts)
551                                 return;
552         }
553         
554         GSList                       *account_names = NULL, *cursor = NULL;
555         GSList                       *accounts = NULL;
556
557         /* these account names, not server_account names */
558         account_names = modest_account_mgr_account_names (priv->account_mgr,FALSE);
559                 
560         for (cursor = account_names; cursor; cursor = cursor->next) {
561                 
562                 gchar *account_name = (gchar*)cursor->data;
563                 
564                 /* we get the server_accounts for enabled accounts */
565                 if (modest_account_mgr_get_enabled(priv->account_mgr, account_name)) {
566                                 
567                         /* Add the account: */
568                         TnyAccount *tny_account = 
569                                 modest_tny_account_new_from_account (priv->account_mgr,
570                                                                      account_name,
571                                                                      type, priv->session,
572                                                                      get_password,
573                                                                      forget_password);
574                         if (tny_account) {
575                                 g_object_set_data (G_OBJECT(tny_account), "account_store",
576                                                    (gpointer)self);
577                                 if (list)
578                                         tny_list_prepend (list, G_OBJECT(tny_account));
579                                 
580                                 accounts = g_slist_append (accounts, tny_account); /* cache it */               
581                         } else
582                                 g_printerr ("modest: failed to create account for %s\n",
583                                             account_name);
584                         }
585                 g_free (account_name);
586         }
587         g_slist_free (account_names);
588         
589         if (type == TNY_ACCOUNT_TYPE_STORE) {
590                 /* Also add the local folder pseudo-account: */
591                 TnyAccount *tny_account =
592                         modest_tny_account_new_for_local_folders (priv->account_mgr, priv->session);
593                 if (list)
594                         tny_list_prepend (list, G_OBJECT(tny_account));
595                 accounts = g_slist_append (accounts, tny_account); /* cache it */
596         }
597         
598         /* Do this here, because create_per_account_local_outbox_folders() needs it. */
599         if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
600                         /* Store the cache: */
601                         priv->transport_accounts = accounts;
602         }
603         
604         /* We also create a per-account local outbox folder (a _store_ account) 
605          * for each _transport_ account. */
606         if (type == TNY_ACCOUNT_TYPE_TRANSPORT) {
607                 /* Now would be a good time to create the per-account local outbox folder 
608                  * _store_ accounts corresponding to each transport account: */
609                 if (!priv->store_accounts_outboxes) {
610                         create_per_account_local_outbox_folders (self);
611                 }
612         }
613         
614         /* But we only return the per-account local outbox folder when 
615          * _store_ accounts are requested. */
616         if (type == TNY_ACCOUNT_TYPE_STORE) {
617                 /* Create them if necessary, 
618                  * (which also requires creating the transport accounts, 
619                  * if necessary.) */
620                 if (!priv->store_accounts_outboxes) {
621                         create_per_account_local_outbox_folders (self);
622                 }
623         
624                 /* Add them to the TnyList: */
625                 if (priv->store_accounts_outboxes) {
626                         GSList *iter = NULL;
627                         for (iter = priv->store_accounts_outboxes; iter; iter = g_slist_next (iter)) {
628                                 TnyAccount *outbox_account = (TnyAccount*)iter->data;
629                                 if (list && outbox_account)
630                                         tny_list_prepend (list,  G_OBJECT(outbox_account));
631                                         
632                                 accounts = g_slist_append (accounts, outbox_account);
633                         }
634                 }
635         }
636                 
637         if (type == TNY_ACCOUNT_TYPE_STORE) {
638                         /* Store the cache: */
639                         priv->store_accounts = accounts;
640         }
641 }       
642
643
644 static void
645 modest_tny_account_store_get_accounts  (TnyAccountStore *self, TnyList *list,
646                                         TnyGetAccountsRequestType request_type)
647 {
648         ModestTnyAccountStorePrivate *priv;
649         
650         g_return_if_fail (self);
651         g_return_if_fail (TNY_IS_LIST(list));
652         
653         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
654         
655         if (request_type == TNY_ACCOUNT_STORE_BOTH) {
656                 modest_tny_account_store_get_accounts (self, list,
657                                                        TNY_ACCOUNT_STORE_STORE_ACCOUNTS);
658                 modest_tny_account_store_get_accounts (self, list,
659                                                        TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS);
660                 return;
661         }
662         
663         if (request_type == TNY_ACCOUNT_STORE_STORE_ACCOUNTS)  {
664                 if (!priv->store_accounts)
665                         get_server_accounts (self, list, TNY_ACCOUNT_TYPE_STORE);
666                 else
667                         get_cached_accounts (self, list, TNY_ACCOUNT_TYPE_STORE);
668                 
669         } else if (request_type == TNY_ACCOUNT_STORE_TRANSPORT_ACCOUNTS) {
670                 if (!priv->transport_accounts)
671                         get_server_accounts (self, list, TNY_ACCOUNT_TYPE_TRANSPORT);
672                 else
673                         get_cached_accounts (self, list, TNY_ACCOUNT_TYPE_TRANSPORT);
674         } else
675                 g_return_if_reached (); /* incorrect req type */
676 }
677
678
679 static const gchar*
680 modest_tny_account_store_get_cache_dir (TnyAccountStore *self)
681 {
682         ModestTnyAccountStorePrivate *priv;
683         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
684         
685         if (!priv->cache_dir)
686                 priv->cache_dir = g_build_filename (g_get_home_dir(), 
687                                                     MODEST_DIR, MODEST_CACHE_DIR, NULL);
688         return priv->cache_dir;
689 }
690
691
692 /*
693  * callers need to unref
694  */
695 static TnyDevice*
696 modest_tny_account_store_get_device (TnyAccountStore *self)
697 {
698         ModestTnyAccountStorePrivate *priv;
699
700         g_return_val_if_fail (self, NULL);
701         
702         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
703
704         if (priv->device)
705                 return g_object_ref (G_OBJECT(priv->device));
706         else
707                 return NULL;
708 }
709
710
711 static TnyAccount*
712 modest_tny_account_store_find_account_by_url (TnyAccountStore *self, const gchar* url_string)
713 {
714         TnyAccount *account = NULL;
715         ModestTnyAccountStorePrivate *priv;     
716         GSList *cursor;
717         
718         g_return_val_if_fail (self, NULL);
719         g_return_val_if_fail (url_string, NULL);
720         
721         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
722
723         for (cursor = priv->store_accounts; cursor ; cursor = cursor->next) {
724                 if (tny_account_matches_url_string (TNY_ACCOUNT(cursor->data), url_string)) {
725                         account = TNY_ACCOUNT(cursor->data);
726                         break;
727                 }
728         }
729
730         if (!account) {
731                 for (cursor = priv->transport_accounts; !account && cursor ; cursor = cursor->next) {
732                         if (tny_account_matches_url_string (TNY_ACCOUNT(cursor->data), url_string)) {
733                                 account = TNY_ACCOUNT(cursor->data);
734                                 break;
735                         }
736                 }
737         }
738
739         if (account)
740                 g_object_ref (G_OBJECT(account));
741
742         return account;
743 }
744
745
746
747 static gboolean
748 modest_tny_account_store_alert (TnyAccountStore *self, TnyAlertType type,
749                                 gboolean question, const GError *error)
750 {
751         g_return_val_if_fail (error, FALSE);
752
753         if ((error->domain != TNY_ACCOUNT_ERROR) 
754                 && (error->domain != TNY_ACCOUNT_STORE_ERROR)) {
755                 g_warning("%s: Unexpected error domain: != TNY_ACCOUNT_ERROR: %d, message=%s", 
756                         __FUNCTION__, error->domain, error->message); 
757                 return FALSE;
758         }
759         
760         /* printf("DEBUG: %s: error->message=%s\n", __FUNCTION__, error->message); */
761         
762
763         /* const gchar *prompt = NULL; */
764         gchar *prompt = NULL;
765         switch (error->code) {
766                 case TNY_ACCOUNT_ERROR_TRY_CONNECT:
767                 /* The tinymail camel implementation just sends us this for almost 
768                  * everything, so we have to guess at the cause.
769                  * It could be a wrong password, or inability to resolve a hostname, 
770                  * or lack of network, or something entirely different: */
771                 case TNY_ACCOUNT_STORE_ERROR_UNKNOWN_ALERT: 
772                     g_debug ("%s: Handling GError domain=%d, code=%d, message=%s", 
773                                 __FUNCTION__, error->domain, error->code, error->message);
774                         
775                         /* TODO: Remove the internal error message for the real release.
776                          * This is just so the testers can give us more information: */
777                         /* prompt = _("Modest account not yet fully configured."); */
778                         prompt = g_strdup_printf(_("Modest account not yet fully configured. Error=%s"), 
779                                 error->message);
780                         break;
781                 default:
782                         g_warning ("%s: Unhandled GError code: %d, message=%s", 
783                                 __FUNCTION__, error->code, error->message);
784                         prompt = NULL;
785                 break;
786         }
787         
788         if (!prompt)
789                 return FALSE;
790
791 #ifdef MODEST_PLATFORM_MAEMO
792         /* The Tinymail documentation says that we should show Yes and No buttons, 
793          * when it is a question.
794          * Obviously, we need tinymail to use more specific error codes instead,
795          * so we know what buttons to show. */
796          GtkWidget *dialog = NULL;
797          if (question) {
798                 dialog = GTK_WIDGET (hildon_note_new_confirmation (NULL, 
799                         prompt));
800          } else {
801                 dialog = GTK_WIDGET (hildon_note_new_information (NULL, 
802                         prompt));
803          }
804 #else
805
806         GtkMessageType gtktype = GTK_MESSAGE_ERROR;
807         switch (type)
808         {
809                 case TNY_ALERT_TYPE_INFO:
810                 gtktype = GTK_MESSAGE_INFO;
811                 break;
812                 case TNY_ALERT_TYPE_WARNING:
813                 gtktype = GTK_MESSAGE_WARNING;
814                 break;
815                 case TNY_ALERT_TYPE_ERROR:
816                 default:
817                 gtktype = GTK_MESSAGE_ERROR;
818                 break;
819         }
820         
821         GtkWidget *dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL,
822                 gtktype, GTK_BUTTONS_YES_NO, prompt);
823 #endif /* #ifdef MODEST_PLATFORM_MAEMO */
824
825         gboolean retval = TRUE;
826         const int response = gtk_dialog_run (GTK_DIALOG (dialog));
827         if (question) {
828                 retval = (response == GTK_RESPONSE_YES) ||
829                                  (response == GTK_RESPONSE_OK); 
830         }
831
832         gtk_widget_destroy (dialog);
833         
834         /* TODO: Don't free this when we no longer strdup the message for testers. */
835         g_free (prompt);
836
837
838         /* printf("DEBUG: %s: returning %d\n", __FUNCTION__, retval); */
839         return retval;
840 }
841
842
843 static void
844 modest_tny_account_store_init (gpointer g, gpointer iface_data)
845 {
846         TnyAccountStoreIface *klass;
847
848         g_return_if_fail (g);
849
850         klass = (TnyAccountStoreIface *)g;
851
852         klass->get_accounts_func =
853                 modest_tny_account_store_get_accounts;
854         klass->get_cache_dir_func =
855                 modest_tny_account_store_get_cache_dir;
856         klass->get_device_func =
857                 modest_tny_account_store_get_device;
858         klass->alert_func =
859                 modest_tny_account_store_alert;
860         klass->find_account_func =
861                 modest_tny_account_store_find_account_by_url;
862 }
863
864 void
865 modest_tny_account_store_set_get_pass_func (ModestTnyAccountStore *self,
866                                             ModestTnyGetPassFunc func)
867 {
868         /* not implemented, we use signals */
869         g_printerr ("modest: set_get_pass_func not implemented\n");
870 }
871
872 TnySessionCamel*
873 modest_tny_account_store_get_session  (TnyAccountStore *self)
874 {
875         g_return_val_if_fail (self, NULL);
876         return MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE (self)->session;
877 }
878
879
880 TnyAccount*
881 modest_tny_account_store_get_tny_account_by_id  (ModestTnyAccountStore *self, const gchar *id)
882 {
883         TnyAccount *account = NULL;
884         ModestTnyAccountStorePrivate *priv;     
885         GSList *cursor;
886
887         g_return_val_if_fail (self, NULL);
888         g_return_val_if_fail (id, NULL);
889         
890         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
891
892
893         for (cursor = priv->store_accounts; cursor ; cursor = cursor->next) {
894                 const gchar *acc_id = tny_account_get_id (TNY_ACCOUNT(cursor->data));
895                 if (acc_id && strcmp (acc_id, id) == 0) {
896                         account = TNY_ACCOUNT(cursor->data);
897                         break;
898                 }
899         }
900                 
901         /* if we already found something, no need to search the transport accounts */
902         for (cursor = priv->transport_accounts; !account && cursor ; cursor = cursor->next) {
903                 const gchar *acc_id = tny_account_get_id (TNY_ACCOUNT(cursor->data));
904                 if (acc_id && strcmp (acc_id, id) == 0) {
905                         account = TNY_ACCOUNT(cursor->data);
906                         break;
907                 }
908         }
909
910         if (account)
911                 g_object_ref (G_OBJECT(account));
912         
913         return account;
914 }
915
916 TnyAccount*
917 modest_tny_account_store_get_tny_account_by_account (ModestTnyAccountStore *self,
918                                                      const gchar *account_name,
919                                                      TnyAccountType type)
920 {
921         TnyAccount *account = NULL;
922         gchar *id = NULL;
923         ModestTnyAccountStorePrivate *priv;     
924
925         g_return_val_if_fail (self, NULL);
926         g_return_val_if_fail (account_name, NULL);
927         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || type == TNY_ACCOUNT_TYPE_TRANSPORT,
928                               NULL);
929         
930         priv = MODEST_TNY_ACCOUNT_STORE_GET_PRIVATE(self);
931
932         /* Special case for the local account */
933         if (!strcmp (account_name, MODEST_ACTUAL_LOCAL_FOLDERS_ACCOUNT_ID) && 
934             type == TNY_ACCOUNT_TYPE_STORE) {
935                 id = g_strdup (MODEST_ACTUAL_LOCAL_FOLDERS_ACCOUNT_ID);
936         } else {
937                 ModestAccountData *account_data;
938
939                 account_data = modest_account_mgr_get_account_data (priv->account_mgr, account_name);
940                 if (!account_data) {
941                         g_printerr ("modest: cannot get account data for account '%s'\n", account_name);
942                         return NULL;
943                 }
944
945                 if (type == TNY_ACCOUNT_TYPE_STORE && account_data->store_account)
946                         id = g_strdup (account_data->store_account->account_name);
947                 else if (account_data->transport_account)
948                         id = g_strdup (account_data->transport_account->account_name);
949
950                 modest_account_mgr_free_account_data (priv->account_mgr, account_data);
951         }
952
953         if (!id)
954                 g_printerr ("modest: could not get an id for account %s\n",
955                             account_name);
956         else    
957                 account = modest_tny_account_store_get_tny_account_by_id (self, id);
958
959         if (!account)
960                 g_printerr ("modest: could not get tny %s account for %s (id=%s)\n",
961                             type == TNY_ACCOUNT_TYPE_STORE? "store" : "transport",
962                             account_name, id ? id : "<none>");
963
964         return account; 
965 }
966
967 static TnyAccount*
968 get_smtp_specific_transport_account_for_open_connection (ModestTnyAccountStore *self,
969                                                          const gchar *account_name)
970 {
971         /* Get the current connection: */
972         TnyDevice *device = modest_runtime_get_device ();
973         
974         if (!tny_device_is_online (device))
975                 return NULL;
976
977 #ifdef MODEST_PLATFORM_MAEMO
978         g_assert (TNY_IS_MAEMO_CONIC_DEVICE (device));
979         TnyMaemoConicDevice *maemo_device = TNY_MAEMO_CONIC_DEVICE (device);    
980         const gchar* iap_id = tny_maemo_conic_device_get_current_iap_id (maemo_device);
981         if (!iap_id)
982                 return NULL;
983                 
984         ConIcIap* connection = tny_maemo_conic_device_get_iap (maemo_device, iap_id);
985         if (!connection)
986                 return NULL;
987                 
988         const gchar *connection_name = con_ic_iap_get_name (connection);
989         if (!connection_name)
990                 return NULL;
991         
992         /*  Get the connection-specific transport acccount, if any: */
993         ModestAccountMgr *account_manager = modest_runtime_get_account_mgr ();
994         gchar* server_account_name = modest_account_mgr_get_connection_specific_smtp (account_manager, 
995                 account_name, connection_name);
996                 
997         if (!server_account_name)
998                 return NULL; /* No connection-specific SMTP server was specified for this connection. */
999                 
1000         TnyAccount* account = modest_tny_account_store_get_tny_account_by_id (self, server_account_name);
1001         g_free (server_account_name);   
1002
1003         /* Unref the get()ed object, as required by the tny_maemo_conic_device_get_iap() documentation. */
1004         g_object_unref (connection);
1005         
1006         return account;
1007 #else
1008         return NULL; /* TODO: Implement this for GNOME, instead of just Maemo? */
1009 #endif /* MODEST_PLATFORM_MAEMO */
1010 }
1011
1012                                                                  
1013 TnyAccount*
1014 modest_tny_account_store_get_transport_account_for_open_connection (ModestTnyAccountStore *self,
1015                                                                     const gchar *account_name)
1016 {
1017         /*  Get the connection-specific transport acccount, if any: */
1018         TnyAccount *account = get_smtp_specific_transport_account_for_open_connection (self, account_name);
1019                         
1020         /* If there is no connection-specific transport account (the common case), 
1021          * just get the regular transport account: */
1022         if (!account) {         
1023                 account = modest_tny_account_store_get_tny_account_by_account (self, account_name, 
1024                                                      TNY_ACCOUNT_TYPE_TRANSPORT);
1025         }
1026                              
1027         return account;
1028 }
1029
1030 gboolean modest_tny_folder_store_is_virtual_local_folders (TnyFolderStore *self)
1031 {
1032         /* We should make this more sophisticated if we ever use ModestTnySimpleFolderStore 
1033          * for anything else. */
1034         return MODEST_IS_TNY_SIMPLE_FOLDER_STORE (self);
1035 }