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