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