Bugfix for 80400, introduction of connection policies
[modest] / src / modest-tny-account.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 <modest-platform.h>
31 #include <modest-tny-platform-factory.h>
32 #include <modest-tny-account.h>
33 #include <modest-tny-account-store.h>
34 #include <modest-default-connection-policy.h>
35 #include <modest-tny-local-folders-account.h>
36 #include <modest-runtime.h>
37 #include <tny-simple-list.h>
38 #include <modest-tny-folder.h>
39 #include <modest-tny-outbox-account.h>
40 #include <modest-transport-account-decorator.h>
41 #include <modest-account-mgr-helpers.h>
42 #include <modest-init.h>
43 #include <tny-camel-transport-account.h>
44 #include <tny-camel-imap-store-account.h>
45 #include <tny-camel-pop-store-account.h>
46 #include <tny-folder-stats.h>
47 #include <modest-debug.h>
48 #include <string.h>
49 #ifdef MODEST_PLATFORM_MAEMO
50 #ifdef MODEST_HAVE_HILDON0_WIDGETS
51 #include <hildon-widgets/hildon-file-system-info.h>
52 #else
53 #include <hildon/hildon-file-system-info.h>
54 #endif
55 #endif
56
57 /* we need these dummy functions, or tinymail will complain */
58 static gchar *  get_pass_dummy     (TnyAccount *account, const gchar *prompt, gboolean *cancel);
59 static void     forget_pass_dummy  (TnyAccount *account);
60
61 TnyFolder *
62 modest_tny_account_get_special_folder (TnyAccount *account,
63                                        TnyFolderType special_type)
64 {
65         TnyList *folders = NULL;
66         TnyIterator *iter = NULL;
67         TnyFolder *special_folder = NULL;
68         TnyAccount *local_account  = NULL;
69         GError *error = NULL;
70         
71         g_return_val_if_fail (account, NULL);
72         g_return_val_if_fail (0 <= special_type && special_type < TNY_FOLDER_TYPE_NUM,
73                               NULL);
74         
75         /* The accounts have already been instantiated by 
76          * modest_tny_account_store_get_accounts(), which is the 
77          * TnyAccountStore::get_accounts_func() implementation,
78          * so we just get them here.
79          */
80          
81         /* Per-account outbox folders are each in their own on-disk directory: */
82         if ((special_type == TNY_FOLDER_TYPE_OUTBOX) &&
83             (!modest_tny_account_is_virtual_local_folders (account))) {
84
85                 gchar *account_id;
86                 const gchar *modest_account_name;
87
88                 modest_account_name =
89                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
90                 if (!modest_account_name) {
91                         g_warning ("%s: could not get modest account name", __FUNCTION__);
92                         return NULL;
93                 }
94                 
95                 account_id = g_strdup_printf (
96                         MODEST_PER_ACCOUNT_LOCAL_OUTBOX_FOLDER_ACCOUNT_ID_PREFIX "%s", 
97                         modest_account_name);
98                 
99                 local_account = modest_tny_account_store_get_tny_account_by (modest_runtime_get_account_store(),
100                                                                              MODEST_TNY_ACCOUNT_STORE_QUERY_ID,
101                                                                              account_id);
102                 g_free (account_id);            
103         } else 
104                 /* Other local folders are all in one on-disk directory: */
105                 local_account = modest_tny_account_store_get_tny_account_by (modest_runtime_get_account_store(),
106                                                                              MODEST_TNY_ACCOUNT_STORE_QUERY_ID,
107                                                                              MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
108         if (!local_account) {
109                 g_printerr ("modest: cannot get local account\n");
110                 goto cleanup;
111         }
112
113         folders = TNY_LIST (tny_simple_list_new ());
114         
115         /* There is no need to do this _async, as these are local folders. */
116         /* TODO: However, this seems to fail sometimes when the network is busy, 
117          * returning an empty list. murrayc. */ 
118         tny_folder_store_get_folders (TNY_FOLDER_STORE (local_account), folders, NULL, &error);
119         if (error) {
120                 g_warning ("%s: tny_folder_store_get_folders() failed:%s\n", __FUNCTION__, error->message);
121                 g_error_free (error);
122                 goto cleanup;
123         }
124                                       
125         if (tny_list_get_length (folders) == 0) {
126                 gchar* url_string = tny_account_get_url_string (local_account);
127                 g_printerr ("modest: %s: tny_folder_store_get_folders(%s) returned an empty list\n", 
128                             __FUNCTION__, url_string);
129                 g_free (url_string);
130                 goto cleanup;
131         }
132         
133         iter = tny_list_create_iterator (folders);
134
135         while (!tny_iterator_is_done (iter)) {
136                 TnyFolder *folder = TNY_FOLDER (tny_iterator_get_current (iter));
137                 if (folder) {
138                         if (modest_tny_folder_get_local_or_mmc_folder_type (folder) == special_type) {
139                                 special_folder = folder;
140                                 break; /* Leaving a ref for the special_folder return value. */
141                         }
142                         g_object_unref (folder);
143                 }
144                 tny_iterator_next (iter);
145         }
146         
147 cleanup:
148         if (folders)
149                 g_object_unref (folders);
150         if (iter)
151                 g_object_unref (iter);
152         if (local_account)
153                 g_object_unref (local_account);
154         
155         return special_folder;
156 }
157
158 /**
159  * create_tny_account:
160  * @session: A valid TnySessionCamel instance.
161  * @account_data: the server account for which to create a corresponding tny account
162  * 
163  * get a tnyaccount corresponding to the server_accounts (store or transport) for this account.
164  * NOTE: this function does not set the camel session or the get/forget password functions
165  * 
166  * Returns: a new TnyAccount or NULL in case of error.
167  */
168 static TnyAccount*
169 create_tny_account (TnySessionCamel *session,
170                     ModestServerAccountSettings *server_settings)
171 {
172         TnyAccount *tny_account = NULL;
173         ModestTransportStoreProtocol protocol;
174         const gchar* proto_name;
175         
176         g_return_val_if_fail (session, NULL);
177         g_return_val_if_fail (server_settings, NULL);
178         protocol = modest_server_account_settings_get_protocol (server_settings);
179         g_return_val_if_fail (protocol != MODEST_PROTOCOL_TRANSPORT_STORE_UNKNOWN, NULL);
180         
181         switch (protocol) {
182         case MODEST_PROTOCOL_TRANSPORT_SENDMAIL:
183         case MODEST_PROTOCOL_TRANSPORT_SMTP:
184                 tny_account = TNY_ACCOUNT (modest_transport_account_decorator_new ()); break;
185         case MODEST_PROTOCOL_STORE_POP:
186                 tny_account = TNY_ACCOUNT(tny_camel_pop_store_account_new ()); break;
187         case MODEST_PROTOCOL_STORE_IMAP:
188                 tny_account = TNY_ACCOUNT(tny_camel_imap_store_account_new ()); break;
189         case MODEST_PROTOCOL_STORE_MAILDIR:
190         case MODEST_PROTOCOL_STORE_MBOX:
191                 /* Note that this is not where we create the special local folders account.
192                  * That happens in modest_tny_account_new_for_local_folders() instead.
193                  */
194                 tny_account = TNY_ACCOUNT(tny_camel_store_account_new()); break;
195         default:
196                 g_return_val_if_reached (NULL);
197         }
198
199         if (!tny_account) {
200                 g_printerr ("modest: %s: could not create tny account for '%s'\n",
201                             __FUNCTION__, modest_server_account_settings_get_account_name (server_settings));
202                 return NULL;
203         }
204         tny_account_set_id (tny_account, modest_server_account_settings_get_account_name (server_settings));
205
206         /* This must be set quite early, or other set() functions will fail. */
207         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT (tny_account), session);
208     
209         /* Proto */
210         proto_name =  modest_protocol_info_get_transport_store_protocol_name(protocol);
211         tny_account_set_proto (tny_account, proto_name);
212
213         return tny_account;
214 }
215
216
217
218 /* Camel options: */
219
220 /* These seem to be listed in 
221  * libtinymail-camel/camel-lite/camel/providers/imap/camel-imap-store.c 
222  */
223 #define MODEST_ACCOUNT_OPTION_SSL "use_ssl"
224 #define MODEST_ACCOUNT_OPTION_SSL_NEVER "never"
225 /* This is a tinymail camel-lite specific option, 
226  * roughly equivalent to "always" in regular camel,
227  * which is appropriate for a generic "SSL" connection option: */
228 #define MODEST_ACCOUNT_OPTION_SSL_WRAPPED "wrapped"
229 /* Not used in our UI so far: */
230 #define MODEST_ACCOUNT_OPTION_SSL_WHEN_POSSIBLE "when-possible"
231 /* This is a tinymailcamel-lite specific option that is not in regular camel. */
232 #define MODEST_ACCOUNT_OPTION_SSL_TLS "tls"
233
234 /* These seem to be listed in 
235  * libtinymail-camel/camel-lite/camel/providers/imap/camel-imap-provider.c 
236  */
237 #define MODEST_ACCOUNT_OPTION_USE_LSUB "use_lsub" /* Show only subscribed folders */
238 #define MODEST_ACCOUNT_OPTION_CHECK_ALL "check_all" /* Check for new messages in all folders */
239
240 /* Posssible values for tny_account_set_secure_auth_mech().
241  * These might be camel-specific.
242  * Really, tinymail should use an enum.
243  * camel_sasl_authtype() seems to list some possible values.
244  */
245  
246 /* Note that evolution does not offer these for IMAP: */
247 #define MODEST_ACCOUNT_AUTH_PLAIN "PLAIN"
248 #define MODEST_ACCOUNT_AUTH_ANONYMOUS "ANONYMOUS"
249
250 /* Caeml's IMAP uses NULL instead for "Password".
251  * Also, not that Evolution offers "Password" for IMAP, but "Login" for SMTP.*/
252 #define MODEST_ACCOUNT_AUTH_PASSWORD "LOGIN" 
253 #define MODEST_ACCOUNT_AUTH_CRAMMD5 "CRAM-MD5"
254
255                 
256 /**
257  * update_tny_account:
258  * @account_mgr: a valid account mgr instance
259  * @account_data: the server account for which to create a corresponding tny account
260  * 
261  * get a tnyaccount corresponding to the server_accounts (store or transport) for this account.
262  * NOTE: this function does not set the camel session or the get/forget password functions
263  * 
264  * Returns: a new TnyAccount or NULL in case of error.
265  */
266 static gboolean
267 update_tny_account (TnyAccount *tny_account,
268                     ModestServerAccountSettings *server_settings)
269 {
270         const gchar *account_name;
271         const gchar *uri;
272         g_return_val_if_fail (server_settings, FALSE);
273         account_name = modest_server_account_settings_get_account_name (server_settings);
274         g_return_val_if_fail (account_name, FALSE);
275         g_return_val_if_fail (tny_account, FALSE);
276         
277         tny_account_set_id (tny_account, account_name);
278         
279         /* mbox and maildir accounts use a URI instead of the rest:
280          * Note that this is not where we create the special local folders account.
281          * We do that in modest_tny_account_new_for_local_folders() instead. */
282         uri = modest_server_account_settings_get_uri (server_settings);
283         if (uri)  
284                 tny_account_set_url_string (TNY_ACCOUNT(tny_account), uri);
285         else {
286                 /* Set camel-specific options: */               
287                 /* Enable secure connection settings: */
288                 const gchar* option_security = NULL;
289                 const gchar* auth_mech_name = NULL;
290                 ModestTransportStoreProtocol protocol;
291                 ModestConnectionProtocol security;
292                 ModestAuthProtocol auth_protocol;
293                 const gchar *username;
294                 const gchar *hostname;
295                 guint port;
296
297                 protocol = modest_server_account_settings_get_protocol (server_settings);
298                 security = modest_server_account_settings_get_security (server_settings);
299                 auth_protocol = modest_server_account_settings_get_auth_protocol (server_settings);
300
301                 switch (security) {
302                 case MODEST_PROTOCOL_CONNECTION_NORMAL:
303                         option_security = MODEST_ACCOUNT_OPTION_SSL "=" MODEST_ACCOUNT_OPTION_SSL_NEVER;
304                         break;
305                 case MODEST_PROTOCOL_CONNECTION_SSL:
306                         /* Apparently, use of "IMAPS" (specified in our UI spec), implies 
307                          * use of the "wrapped" option: */
308                         option_security = MODEST_ACCOUNT_OPTION_SSL "=" MODEST_ACCOUNT_OPTION_SSL_WRAPPED;
309                         break;
310                 case MODEST_PROTOCOL_CONNECTION_TLS:
311                         option_security = MODEST_ACCOUNT_OPTION_SSL "=" MODEST_ACCOUNT_OPTION_SSL_TLS;
312                         break;
313                 case MODEST_PROTOCOL_CONNECTION_TLS_OP:
314                         /* This is not actually in our UI: */
315                         option_security = MODEST_ACCOUNT_OPTION_SSL "=" MODEST_ACCOUNT_OPTION_SSL_WHEN_POSSIBLE;
316                         break;
317                 default:
318                         break;
319                 }
320                 
321                 if(option_security)
322                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
323                                                       option_security);
324                 
325                 /* Secure authentication: */
326                 switch (auth_protocol) {
327                 case MODEST_PROTOCOL_AUTH_NONE:
328                         /* IMAP and POP need at least a password,
329                          * which camel uses if we specify NULL.
330                          * This setting should never happen anyway. */
331                         if (protocol == MODEST_PROTOCOL_STORE_IMAP ||
332                             protocol == MODEST_PROTOCOL_STORE_POP)
333                                 auth_mech_name = NULL;
334                         else if (protocol == MODEST_PROTOCOL_TRANSPORT_SMTP)
335                                 auth_mech_name = NULL; 
336                         else
337                                 auth_mech_name = MODEST_ACCOUNT_AUTH_PLAIN;
338                         break;
339                         
340                 case MODEST_PROTOCOL_AUTH_PASSWORD:
341                         /* Camel use a password for IMAP or POP if we specify NULL,
342                          * For IMAP, at least it will report an error if we use "Password", "Login" or "Plain".
343                          * (POP is know to report an error for Login too. Probably Password and Plain too.) */
344                         if (protocol == MODEST_PROTOCOL_STORE_IMAP)
345                                 auth_mech_name = NULL;
346                         else if (protocol == MODEST_PROTOCOL_STORE_POP)
347                                 auth_mech_name = NULL;
348                         else
349                                 auth_mech_name = MODEST_ACCOUNT_AUTH_PASSWORD;
350                         break;
351                         
352                 case MODEST_PROTOCOL_AUTH_CRAMMD5:
353                         auth_mech_name = MODEST_ACCOUNT_AUTH_CRAMMD5;
354                         break;
355                         
356                 default:
357                         g_warning ("%s: Unhandled secure authentication setting %d for "
358                                    "account_name=%s (%s)", __FUNCTION__, auth_protocol,
359                                    account_name, modest_server_account_settings_get_hostname (server_settings));
360                         break;
361                 }
362                 
363                 if(auth_mech_name) 
364                         tny_account_set_secure_auth_mech (tny_account, auth_mech_name);
365                 
366                 if (modest_protocol_info_protocol_is_store(protocol) && 
367                         (protocol == MODEST_PROTOCOL_STORE_IMAP) ) {
368                         /* Other connection options, needed for IMAP. */
369                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
370                                                       MODEST_ACCOUNT_OPTION_USE_LSUB);
371                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
372                                                       MODEST_ACCOUNT_OPTION_CHECK_ALL);
373                 }
374                 
375                 username = modest_server_account_settings_get_username (server_settings);
376                 if (username && strlen (username) > 0) 
377                         tny_account_set_user (tny_account, username);
378                 hostname = modest_server_account_settings_get_hostname (server_settings);
379                 if (hostname)
380                         tny_account_set_hostname (tny_account, hostname);
381                  
382                 /* Set the port: */
383                 port = modest_server_account_settings_get_port (server_settings);
384                 if (port)
385                         tny_account_set_port (tny_account, port);
386         }
387
388         MODEST_DEBUG_BLOCK (
389                 gchar *url = tny_account_get_url_string (TNY_ACCOUNT(tny_account));
390                 g_debug ("%s:\n  account-url: %s\n", __FUNCTION__, url);
391                 g_free (url);
392         );
393         
394         return TRUE;
395 }
396
397 TnyAccount*
398 modest_tny_account_new_from_server_account_name (ModestAccountMgr *account_mgr,
399                                                  TnySessionCamel *session,
400                                                  const gchar *server_account_name,
401                                                  TnyGetPassFunc get_pass_func,
402                                                  TnyForgetPassFunc forget_pass_func)
403 {
404         ModestServerAccountSettings *server_settings;
405         TnyAccount *tny_account;
406         
407         g_return_val_if_fail (session, NULL);
408         g_return_val_if_fail (server_account_name, NULL);
409
410         
411         server_settings =       modest_account_mgr_load_server_settings (account_mgr, server_account_name);
412         if (!server_settings)
413                 return NULL;
414
415         tny_account = TNY_ACCOUNT (tny_camel_transport_account_new ());
416
417         if (tny_account) {
418                 const gchar* proto_name = NULL;
419                 tny_account_set_id (tny_account, server_account_name);
420                 tny_camel_account_set_session (TNY_CAMEL_ACCOUNT (tny_account), session);
421                 proto_name = modest_protocol_info_get_transport_store_protocol_name 
422                                     (modest_server_account_settings_get_protocol (server_settings));
423                 tny_account_set_proto (tny_account, proto_name);
424                 modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account, server_account_name);
425         }
426
427         if (!tny_account)
428                 g_warning ("%s: failed to create tny_account", __FUNCTION__);
429         else if (!update_tny_account (tny_account, server_settings))
430                 g_warning ("%s: failed to initialize tny_account", __FUNCTION__);
431         else {
432                 tny_account_set_forget_pass_func (tny_account,
433                                                   forget_pass_func ? forget_pass_func : forget_pass_dummy);
434                 tny_account_set_pass_func (tny_account,
435                                            get_pass_func ? get_pass_func: get_pass_dummy);
436         }
437
438         tny_account_set_connection_policy (tny_account, modest_default_connection_policy_new ());
439
440         g_object_unref (server_settings);
441         
442         return tny_account;
443 }
444
445
446
447
448 /* we need these dummy functions, or tinymail will complain */
449 static gchar*
450 get_pass_dummy (TnyAccount *account, const gchar *prompt, gboolean *cancel)
451 {
452         return NULL;
453 }
454 static void
455 forget_pass_dummy (TnyAccount *account)
456 {
457         /* intentionally left blank */
458 }
459
460
461 static void
462 set_online_callback (TnyCamelAccount *account, gboolean canceled, GError *err, gpointer user_data)
463 {
464         TnyAccountStore *account_store;
465
466         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
467                                                              "account_store"));
468         if (err && !canceled) {
469                 /* It seems err is forgotten here ... if the disk is full ! */
470                 if (account_store) {
471                         tny_account_store_alert (
472                                 account_store, 
473                                 TNY_ACCOUNT (account), TNY_ALERT_TYPE_ERROR, FALSE, 
474                                 err);
475                 }
476                 g_warning ("err: %s", err->message);
477         }
478 }
479
480 gboolean
481 modest_tny_account_update_from_account (TnyAccount *tny_account,
482                                         TnyGetPassFunc get_pass_func,
483                                         TnyForgetPassFunc forget_pass_func) 
484 {
485         ModestAccountSettings *settings = NULL;
486         ModestServerAccountSettings *server_settings = NULL;
487         ModestAccountMgr *account_mgr;
488         const gchar *account_name;
489         TnyAccountType type;
490         const gchar *display_name;
491         TnyConnectionStatus conn_status;
492
493         g_return_val_if_fail (tny_account, FALSE);
494
495         account_mgr = modest_runtime_get_account_mgr ();
496         account_name = modest_tny_account_get_parent_modest_account_name_for_server_account (tny_account);
497         type = tny_account_get_account_type (tny_account);
498         settings = modest_account_mgr_load_account_settings (account_mgr, account_name);
499         if (!settings) {
500                 g_printerr ("modest: %s: cannot get account data for account %s\n",
501                             __FUNCTION__, account_name);
502                 return FALSE;
503         }
504
505         display_name = modest_account_settings_get_display_name (settings);
506
507         if (type == TNY_ACCOUNT_TYPE_STORE)
508                 server_settings = modest_account_settings_get_store_settings (settings);
509         else if (type == TNY_ACCOUNT_TYPE_TRANSPORT)
510                 server_settings = modest_account_settings_get_transport_settings (settings);
511
512         if (modest_server_account_settings_get_account_name (server_settings) == NULL) {
513                 g_printerr ("modest: no %s account defined for '%s'\n",
514                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
515                             display_name);
516                 g_object_unref (server_settings);
517                 g_object_unref (settings);
518                 return FALSE;
519         }
520         
521         update_tny_account (tny_account, server_settings);
522                 
523         /* This name is what shows up in the folder view -- so for some POP/IMAP/... server
524          * account, we set its name to the account of which it is part. */
525
526         if (display_name)
527                 tny_account_set_name (tny_account, display_name);
528
529         g_object_unref (server_settings);
530         g_object_unref (settings);
531
532         tny_account_set_forget_pass_func (tny_account, NULL);
533         tny_account_set_pass_func (tny_account, NULL);
534         tny_account_set_forget_pass_func (tny_account,
535                                           forget_pass_func ? forget_pass_func : forget_pass_dummy);
536         tny_account_set_pass_func (tny_account,
537                                    get_pass_func ? get_pass_func: get_pass_dummy);
538
539         tny_account_set_connection_policy (tny_account, modest_default_connection_policy_new ());
540         
541         /* The callback will have an error for you if the reconnect
542          * failed. Please handle it (this is TODO). */
543         
544         conn_status = tny_account_get_connection_status (tny_account);
545         if (conn_status != TNY_CONNECTION_STATUS_DISCONNECTED) {
546                 TnyAccountStore *account_store = NULL;
547         
548                 account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(tny_account),
549                                                                      "account_store"));
550         
551                 if (account_store) {
552                         modest_tny_account_store_forget_already_asked (MODEST_TNY_ACCOUNT_STORE (account_store), 
553                                                                        tny_account);
554                 }
555         
556                 tny_camel_account_set_online (TNY_CAMEL_ACCOUNT(tny_account), TRUE, 
557                                               set_online_callback,  "online");
558         }
559         
560         return TRUE;
561 }
562
563
564
565 TnyAccount*
566 modest_tny_account_new_from_account (ModestAccountMgr *account_mgr,
567                                      const gchar *account_name,
568                                      TnyAccountType type,
569                                      TnySessionCamel *session,
570                                      TnyGetPassFunc get_pass_func,
571                                      TnyForgetPassFunc forget_pass_func) 
572 {
573         TnyAccount *tny_account = NULL;
574         ModestAccountSettings *settings = NULL;
575         ModestServerAccountSettings *server_settings = NULL;
576         const gchar *display_name;
577
578         g_return_val_if_fail (account_mgr, NULL);
579         g_return_val_if_fail (account_name, NULL);
580         g_return_val_if_fail (session, NULL);
581         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || type == TNY_ACCOUNT_TYPE_TRANSPORT,
582                               NULL);
583
584         settings = modest_account_mgr_load_account_settings (account_mgr, account_name);
585         if (!settings) {
586                 g_printerr ("modest: %s: cannot get account data for account %s\n",
587                             __FUNCTION__, account_name);
588                 return NULL;
589         }
590         display_name = modest_account_settings_get_display_name (settings);
591
592         if (type == TNY_ACCOUNT_TYPE_STORE)
593                 server_settings = modest_account_settings_get_store_settings (settings);
594         else if (type == TNY_ACCOUNT_TYPE_TRANSPORT)
595                 server_settings = modest_account_settings_get_transport_settings (settings);
596
597         if (modest_server_account_settings_get_account_name (server_settings) == NULL) {
598                 g_printerr ("modest: no %s account defined for '%s'\n",
599                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
600                             display_name);
601                 g_object_unref (server_settings);
602                 g_object_unref (settings);
603                 return NULL;
604         }
605         
606         tny_account = create_tny_account (session, server_settings);
607         if (!tny_account) { 
608                 g_printerr ("modest: failed to create tny account for %s (%s)\n",
609                             account_name, 
610                             modest_server_account_settings_get_account_name (server_settings));
611                 g_object_unref (server_settings);
612                 g_object_unref (settings);
613                 return NULL;
614         } else
615                 update_tny_account (tny_account, server_settings);
616                 
617         /* This name is what shows up in the folder view -- so for some POP/IMAP/... server
618          * account, we set its name to the account of which it is part. */
619  
620         if (display_name)
621                 tny_account_set_name (tny_account, display_name);
622
623         tny_account_set_forget_pass_func (tny_account,
624                                           forget_pass_func ? forget_pass_func : forget_pass_dummy);
625         tny_account_set_pass_func (tny_account,
626                                    get_pass_func ? get_pass_func: get_pass_dummy);
627
628         tny_account_set_connection_policy (tny_account, modest_default_connection_policy_new ());
629
630         modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account,
631                                                                               account_name);
632         g_object_unref (server_settings);
633         g_object_unref (settings);
634
635         return tny_account;
636 }
637
638 typedef struct
639 {
640         TnyStoreAccount *account;
641         
642         ModestTnyAccountGetMmcAccountNameCallback callback;
643         gpointer user_data;
644 } GetMmcAccountNameData;
645
646
647
648 #ifdef MODEST_PLATFORM_MAEMO
649 /* Gets the memory card name: */
650 static void 
651 on_modest_file_system_info (HildonFileSystemInfoHandle *handle,
652                             HildonFileSystemInfo *info,
653                             const GError *error, gpointer data)
654 {
655         GetMmcAccountNameData *callback_data = (GetMmcAccountNameData*)data;
656
657         if (error) {
658                 g_warning ("%s: error=%s", __FUNCTION__, error->message);
659         }
660         
661         TnyAccount *account = TNY_ACCOUNT (callback_data->account);
662         
663         const gchar *previous_display_name = NULL;
664         
665         const gchar *display_name = NULL;
666         if (!error && info) {
667                 display_name = hildon_file_system_info_get_display_name(info);
668                 previous_display_name = tny_account_get_name (account);
669         }
670                  
671         /* printf ("DEBUG: %s: display name=%s\n", __FUNCTION__,  display_name); */
672         if (display_name && previous_display_name && 
673                 (strcmp (display_name, previous_display_name) != 0)) {
674                 tny_account_set_name (account, display_name);
675         }
676                 
677         /* Inform the application that the name is now ready: */
678         if (callback_data->callback)
679                 (*(callback_data->callback)) (callback_data->account, 
680                         callback_data->user_data);
681         
682         g_object_unref (callback_data->account);
683         g_slice_free (GetMmcAccountNameData, callback_data);
684 }
685 #endif
686
687 void modest_tny_account_get_mmc_account_name (TnyStoreAccount* self, ModestTnyAccountGetMmcAccountNameCallback callback, gpointer user_data)
688 {
689 #ifdef MODEST_PLATFORM_MAEMO
690         /* Just use the hard-coded path for the single memory card,
691          * rather than try to figure out the path to the specific card by 
692          * looking at the maildir URI:
693          */
694         const gchar *uri_real = MODEST_MCC1_VOLUMEPATH_URI;
695
696         /*
697         gchar* uri = tny_account_get_url_string (TNY_ACCOUNT (self));
698         if (!uri)
699                 return;
700
701         TODO: This gets the name of the folder, but we want the name of the volume.
702         gchar *uri_real = NULL;
703         const gchar* prefix = "maildir://localhost/";
704         if ((strstr (uri, prefix) == uri) && (strlen(uri) > strlen(prefix)) )
705                 uri_real = g_strconcat ("file:///", uri + strlen (prefix), NULL);
706         */
707
708         if (uri_real) {
709                 //This is freed in the callback:
710                 GetMmcAccountNameData * callback_data = g_slice_new0(GetMmcAccountNameData);
711                 callback_data->account = self;
712                 g_object_ref (callback_data->account); /* Unrefed when we destroy the struct. */
713                 callback_data->callback = callback;
714                 callback_data->user_data = user_data;
715                 
716                 /* TODO: gnome_vfs_volume_get_display_name() does not return 
717                  * the same string. But why not? Why does hildon needs its own 
718                  * function for this?
719                  */
720                 /* printf ("DEBUG: %s Calling hildon_file_system_info_async_new() with URI=%s\n", __FUNCTION__, uri_real); */
721                 hildon_file_system_info_async_new(uri_real, 
722                         on_modest_file_system_info, callback_data /* user_data */);
723
724                 /* g_free (uri_real); */
725         }
726
727         /* g_free (uri); */
728 #endif
729 }
730
731                                 
732
733 TnyAccount*
734 modest_tny_account_new_for_local_folders (ModestAccountMgr *account_mgr, TnySessionCamel *session,
735                                           const gchar* location_filepath)
736 {
737
738         
739         /* Make sure that the directories exist: */
740         modest_init_local_folders (location_filepath);
741
742         TnyStoreAccount *tny_account;
743         CamelURL *url;
744         gchar *maildir, *url_string;
745
746         g_return_val_if_fail (account_mgr, NULL);
747         g_return_val_if_fail (session, NULL);
748
749         
750         if (!location_filepath) {
751                 /* A NULL filepath means that this is the special local-folders maildir 
752                  * account: */
753                 tny_account = TNY_STORE_ACCOUNT (modest_tny_local_folders_account_new ());
754         }
755         else {
756                 /* Else, for instance, a per-account outbox maildir account: */
757                 tny_account = TNY_STORE_ACCOUNT (tny_camel_store_account_new ());
758         }
759                 
760         if (!tny_account) {
761                 g_printerr ("modest: %s: cannot create account for local folders. filepath=%s", 
762                         __FUNCTION__, location_filepath);
763                 return NULL;
764         }
765         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
766         
767         /* This path contains directories for each local folder.
768          * We have created them so that TnyCamelStoreAccount can find them 
769          * and report a folder for each directory: */
770         maildir = modest_local_folder_info_get_maildir_path (location_filepath);
771         url = camel_url_new ("maildir:", NULL);
772         camel_url_set_path (url, maildir);
773         /* Needed by tinymail's DBC assertions */
774         camel_url_set_host (url, "localhost");
775         url_string = camel_url_to_string (url, 0);
776         
777         tny_account_set_url_string (TNY_ACCOUNT(tny_account), url_string);
778 /*      printf("DEBUG: %s:\n  url=%s\n", __FUNCTION__, url_string); */
779
780         /* TODO: Use a more generic way of identifying memory card paths, 
781          * and of marking accounts as memory card accounts, maybe
782          * via a derived TnyCamelStoreAccount ? */
783         const gboolean is_mmc = 
784                 location_filepath && 
785                 (strcmp (location_filepath, MODEST_MCC1_VOLUMEPATH) == 0);
786                 
787         /* The name of memory card locations will be updated asynchronously.
788          * This is just a default: */
789         const gchar *name = is_mmc ? _("Memory Card") : 
790                 MODEST_LOCAL_FOLDERS_DEFAULT_DISPLAY_NAME;
791         tny_account_set_name (TNY_ACCOUNT(tny_account), name); 
792         
793         /* Get the correct display name for memory cards, asynchronously: */
794         if (location_filepath) {
795                 GError *error = NULL;
796                 gchar *uri = g_filename_to_uri(location_filepath, NULL, &error);
797                 if (error) {
798                         g_warning ("%s: g_filename_to_uri(%s) failed: %s", __FUNCTION__, 
799                                 location_filepath, error->message);
800                         g_error_free (error);
801                         error = NULL;   
802                 } else if (uri) {
803                         /* Get the account name asynchronously:
804                          * This might not happen soon enough, so some UI code might 
805                          * need to call this again, specifying a callback.
806                          */
807                         modest_tny_account_get_mmc_account_name (tny_account, NULL, NULL);
808                                 
809                         g_free (uri);
810                         uri = NULL;
811                 }
812         }
813         
814         
815         const gchar* id = is_mmc ? MODEST_MMC_ACCOUNT_ID :
816                 MODEST_LOCAL_FOLDERS_ACCOUNT_ID;
817         tny_account_set_id (TNY_ACCOUNT(tny_account), id);
818         
819         tny_account_set_forget_pass_func (TNY_ACCOUNT(tny_account), forget_pass_dummy);
820         tny_account_set_pass_func (TNY_ACCOUNT(tny_account), get_pass_dummy);
821
822         tny_account_set_connection_policy (TNY_ACCOUNT (tny_account), modest_default_connection_policy_new ()); 
823
824         modest_tny_account_set_parent_modest_account_name_for_server_account (
825                 TNY_ACCOUNT (tny_account), id);
826         
827         camel_url_free (url);
828         g_free (maildir);
829         g_free (url_string);
830
831         return TNY_ACCOUNT(tny_account);
832 }
833
834
835 TnyAccount*
836 modest_tny_account_new_for_per_account_local_outbox_folder (ModestAccountMgr *account_mgr,
837                                                             const gchar* account_name,
838                                                             TnySessionCamel *session)
839 {
840         g_return_val_if_fail (account_mgr, NULL);
841         g_return_val_if_fail (account_name, NULL);
842         g_return_val_if_fail (session, NULL);
843         
844         /* Notice that we create a ModestTnyOutboxAccount here, 
845          * instead of just a TnyCamelStoreAccount,
846          * so that we can later identify this as a special account for internal use only.
847          */
848         TnyStoreAccount *tny_account = TNY_STORE_ACCOUNT (modest_tny_outbox_account_new ());
849         if (!tny_account) {
850                 g_printerr ("modest: cannot create account for per-account local outbox folder.");
851                 return NULL;
852         }
853         
854         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
855         
856         /* Make sure that the paths exists on-disk so that TnyCamelStoreAccount can 
857          * find it to create a TnyFolder for it: */
858         gchar *folder_dir = modest_per_account_local_outbox_folder_info_get_maildir_path_to_outbox_folder (account_name); 
859         modest_init_one_local_folder(folder_dir);
860         g_free (folder_dir);
861         folder_dir = NULL;
862
863         /* This path should contain just one directory - "outbox": */
864         gchar *maildir = 
865                 modest_per_account_local_outbox_folder_info_get_maildir_path (account_name);
866                         
867         CamelURL *url = camel_url_new ("maildir:", NULL);
868         camel_url_set_path (url, maildir);
869         g_free (maildir);
870         
871         /* Needed by tinymail's DBC assertions */
872         camel_url_set_host (url, "localhost");
873         gchar *url_string = camel_url_to_string (url, 0);
874         camel_url_free (url);
875         
876         tny_account_set_url_string (TNY_ACCOUNT(tny_account), url_string);
877 /*      printf("DEBUG: %s:\n  url=%s\n", __FUNCTION__, url_string); */
878         g_free (url_string);
879
880         /* This text should never been seen,
881          * because the per-account outbox accounts are not seen directly by the user.
882          * Their folders are merged and shown as one folder. */ 
883         tny_account_set_name (TNY_ACCOUNT(tny_account), "Per-Account Outbox"); 
884         
885         gchar *account_id = g_strdup_printf (
886                 MODEST_PER_ACCOUNT_LOCAL_OUTBOX_FOLDER_ACCOUNT_ID_PREFIX "%s", 
887                 account_name);
888         tny_account_set_id (TNY_ACCOUNT(tny_account), account_id);
889         g_free (account_id);
890         
891         tny_account_set_forget_pass_func (TNY_ACCOUNT(tny_account), forget_pass_dummy);
892         tny_account_set_pass_func (TNY_ACCOUNT(tny_account), get_pass_dummy);
893
894         tny_account_set_connection_policy (TNY_ACCOUNT (tny_account), modest_default_connection_policy_new ());
895
896         /* Make this think that it belongs to the modest local-folders parent account: */
897         modest_tny_account_set_parent_modest_account_name_for_server_account (
898                 TNY_ACCOUNT (tny_account), MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
899
900         return TNY_ACCOUNT(tny_account);
901 }
902
903
904
905 typedef gint (*TnyStatsFunc) (TnyFolderStats *stats);
906 #define TASK_GET_ALL_COUNT      0
907 #define TASK_GET_LOCAL_SIZE     1
908 #define TASK_GET_FOLDER_COUNT   2
909
910 typedef struct _RecurseFoldersHelper {
911         gint task;
912         guint sum;
913         guint folders;
914 } RecurseFoldersHelper;
915
916 static void
917 recurse_folders (TnyFolderStore *store, 
918                  TnyFolderStoreQuery *query, 
919                  RecurseFoldersHelper *helper)
920 {
921         TnyIterator *iter;
922         TnyList *folders = tny_simple_list_new ();
923
924         tny_folder_store_get_folders (store, folders, query, NULL);
925         iter = tny_list_create_iterator (folders);
926
927         helper->folders += tny_list_get_length (folders);
928
929         while (!tny_iterator_is_done (iter)) {
930                 TnyFolder *folder;
931
932                 folder = TNY_FOLDER (tny_iterator_get_current (iter));
933                 if (folder) {
934                         if (helper->task == TASK_GET_ALL_COUNT)
935                                 helper->sum += tny_folder_get_all_count (folder);
936
937                         if (helper->task == TASK_GET_LOCAL_SIZE)
938                                 helper->sum += tny_folder_get_local_size (folder);
939
940                         if (TNY_IS_FOLDER_STORE (folder))
941                                 recurse_folders (TNY_FOLDER_STORE (folder), query, helper);
942
943                         g_object_unref (folder);
944                 }
945
946                 tny_iterator_next (iter);
947         }
948          g_object_unref (G_OBJECT (iter));
949          g_object_unref (G_OBJECT (folders));
950 }
951
952 gint 
953 modest_tny_folder_store_get_folder_count (TnyFolderStore *self)
954 {
955         RecurseFoldersHelper *helper;
956         gint retval;
957
958         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
959
960         /* Create helper */
961         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
962         helper->task = TASK_GET_FOLDER_COUNT;
963         helper->folders = 0;
964
965         recurse_folders (self, NULL, helper);
966
967         retval = helper->folders;
968
969         g_free (helper);
970
971         return retval;
972 }
973
974 gint
975 modest_tny_folder_store_get_message_count (TnyFolderStore *self)
976 {
977         RecurseFoldersHelper *helper;
978         gint retval;
979
980         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
981         
982         /* Create helper */
983         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
984         helper->task = TASK_GET_ALL_COUNT;
985         if (TNY_IS_FOLDER (self))
986                 helper->sum = tny_folder_get_all_count (TNY_FOLDER (self));
987
988         recurse_folders (self, NULL, helper);
989
990         retval = helper->sum;
991
992         g_free (helper);
993
994         return retval;
995 }
996
997 gint 
998 modest_tny_folder_store_get_local_size (TnyFolderStore *self)
999 {
1000         RecurseFoldersHelper *helper;
1001         gint retval;
1002
1003         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
1004
1005         /* Create helper */
1006         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
1007         helper->task = TASK_GET_LOCAL_SIZE;
1008         if (TNY_IS_FOLDER (self))
1009                 helper->sum = tny_folder_get_local_size (TNY_FOLDER (self));
1010
1011         recurse_folders (self, NULL, helper);
1012
1013         retval = helper->sum;
1014
1015         g_free (helper);
1016
1017         return retval;
1018 }
1019
1020 const gchar* 
1021 modest_tny_account_get_parent_modest_account_name_for_server_account (TnyAccount *self)
1022 {
1023         return (const gchar *)g_object_get_data (G_OBJECT (self), "modest_account");
1024 }
1025
1026 void 
1027 modest_tny_account_set_parent_modest_account_name_for_server_account (TnyAccount *self, 
1028                                                                       const gchar* parent_modest_account_name)
1029 {
1030         g_object_set_data_full (G_OBJECT(self), "modest_account",
1031                                 (gpointer) g_strdup (parent_modest_account_name), g_free);
1032 }
1033
1034 gboolean
1035 modest_tny_account_is_virtual_local_folders (TnyAccount *self)
1036 {
1037         /* We should make this more sophisticated if we ever use ModestTnyLocalFoldersAccount 
1038          * for anything else. */
1039         return MODEST_IS_TNY_LOCAL_FOLDERS_ACCOUNT (self);
1040 }
1041
1042
1043 gboolean
1044 modest_tny_account_is_memory_card_account (TnyAccount *self)
1045 {
1046         const gchar* account_id = NULL;
1047
1048         g_return_val_if_fail (TNY_ACCOUNT (self), FALSE);
1049
1050         if (!self)
1051                 return FALSE;
1052
1053         account_id = tny_account_get_id (self);
1054
1055         if (!account_id)
1056                 return FALSE;
1057         else    
1058                 return (strcmp (account_id, MODEST_MMC_ACCOUNT_ID) == 0);
1059 }
1060
1061 gboolean 
1062 modest_tny_folder_store_is_remote (TnyFolderStore *folder_store)
1063 {
1064         TnyAccount *account = NULL;
1065         gboolean result = TRUE;
1066
1067         g_return_val_if_fail(TNY_IS_FOLDER_STORE(folder_store), FALSE);
1068
1069         if (TNY_IS_FOLDER (folder_store)) {
1070                 /* Get the folder's parent account: */
1071                 account = tny_folder_get_account(TNY_FOLDER(folder_store));
1072         } else if (TNY_IS_ACCOUNT (folder_store)) {
1073                 account = TNY_ACCOUNT(folder_store);
1074                 g_object_ref(account);
1075         }
1076
1077         if (account != NULL) {
1078                 if (tny_account_get_account_type (account) == TNY_ACCOUNT_TYPE_STORE) {
1079                         if (!TNY_IS_CAMEL_POP_STORE_ACCOUNT (account) &&
1080                             !TNY_IS_CAMEL_IMAP_STORE_ACCOUNT (account)) {
1081                                 /* This must be a maildir account, which does
1082                                  * not require a connection: */
1083                                 result = FALSE;
1084                         }
1085                 }
1086                 g_object_unref (account);
1087         } else {
1088                 result = FALSE;
1089         }
1090
1091         return result;
1092 }
1093