* Fixes NB#85880, show the proper server name if a SMTP send fails
[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         /* Do not change the id if it's not needed */
278         if (tny_account_get_id (tny_account) && 
279             strcmp (tny_account_get_id (tny_account), account_name))
280                 tny_account_set_id (tny_account, account_name);
281         
282         /* mbox and maildir accounts use a URI instead of the rest:
283          * Note that this is not where we create the special local folders account.
284          * We do that in modest_tny_account_new_for_local_folders() instead. */
285         uri = modest_server_account_settings_get_uri (server_settings);
286         if (uri)  
287                 tny_account_set_url_string (TNY_ACCOUNT(tny_account), uri);
288         else {
289                 /* Set camel-specific options: */               
290                 /* Enable secure connection settings: */
291                 TnyPair *option_security = NULL;
292                 const gchar* auth_mech_name = NULL;
293                 ModestTransportStoreProtocol protocol;
294                 ModestConnectionProtocol security;
295                 ModestAuthProtocol auth_protocol;
296                 const gchar *username;
297                 const gchar *hostname;
298                 guint port;
299
300                 /* First of all delete old options */
301                 tny_camel_account_clear_options (TNY_CAMEL_ACCOUNT (tny_account));
302
303                 protocol = modest_server_account_settings_get_protocol (server_settings);
304                 security = modest_server_account_settings_get_security (server_settings);
305                 auth_protocol = modest_server_account_settings_get_auth_protocol (server_settings);
306
307                 switch (security) {
308                 case MODEST_PROTOCOL_CONNECTION_NORMAL:
309                         option_security = tny_pair_new (MODEST_ACCOUNT_OPTION_SSL,MODEST_ACCOUNT_OPTION_SSL_NEVER);
310                         break;
311                 case MODEST_PROTOCOL_CONNECTION_SSL:
312                         /* Apparently, use of "IMAPS" (specified in our UI spec), implies 
313                          * use of the "wrapped" option: */
314                         option_security = tny_pair_new (MODEST_ACCOUNT_OPTION_SSL,MODEST_ACCOUNT_OPTION_SSL_WRAPPED);
315                         break;
316                 case MODEST_PROTOCOL_CONNECTION_TLS:
317                         option_security = tny_pair_new (MODEST_ACCOUNT_OPTION_SSL,MODEST_ACCOUNT_OPTION_SSL_TLS);
318                         break;
319                 case MODEST_PROTOCOL_CONNECTION_TLS_OP:
320                         /* This is not actually in our UI: */
321                         option_security = tny_pair_new (MODEST_ACCOUNT_OPTION_SSL,MODEST_ACCOUNT_OPTION_SSL_WHEN_POSSIBLE);
322                         break;
323                 default:
324                         break;
325                 }
326                 
327                 if(option_security)
328                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account), option_security);
329                 
330                 /* Secure authentication: */
331                 switch (auth_protocol) {
332                 case MODEST_PROTOCOL_AUTH_NONE:
333                         /* IMAP and POP need at least a password,
334                          * which camel uses if we specify NULL.
335                          * This setting should never happen anyway. */
336                         if (protocol == MODEST_PROTOCOL_STORE_IMAP ||
337                             protocol == MODEST_PROTOCOL_STORE_POP)
338                                 auth_mech_name = NULL;
339                         else if (protocol == MODEST_PROTOCOL_TRANSPORT_SMTP)
340                                 auth_mech_name = NULL; 
341                         else
342                                 auth_mech_name = MODEST_ACCOUNT_AUTH_PLAIN;
343                         break;
344                         
345                 case MODEST_PROTOCOL_AUTH_PASSWORD:
346                         /* Camel use a password for IMAP or POP if we specify NULL,
347                          * For IMAP, at least it will report an error if we use "Password", "Login" or "Plain".
348                          * (POP is know to report an error for Login too. Probably Password and Plain too.) */
349                         if (protocol == MODEST_PROTOCOL_STORE_IMAP)
350                                 auth_mech_name = NULL;
351                         else if (protocol == MODEST_PROTOCOL_STORE_POP)
352                                 auth_mech_name = NULL;
353                         else
354                                 auth_mech_name = MODEST_ACCOUNT_AUTH_PASSWORD;
355                         break;
356                         
357                 case MODEST_PROTOCOL_AUTH_CRAMMD5:
358                         auth_mech_name = MODEST_ACCOUNT_AUTH_CRAMMD5;
359                         break;
360                         
361                 default:
362                         g_warning ("%s: Unhandled secure authentication setting %d for "
363                                    "account_name=%s (%s)", __FUNCTION__, auth_protocol,
364                                    account_name, modest_server_account_settings_get_hostname (server_settings));
365                         break;
366                 }
367                 
368                 if(auth_mech_name) 
369                         tny_account_set_secure_auth_mech (tny_account, auth_mech_name);
370                 
371                 if (modest_protocol_info_protocol_is_store(protocol) && 
372                         (protocol == MODEST_PROTOCOL_STORE_IMAP) ) {
373                         /* Other connection options, needed for IMAP. */
374                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
375                                                       tny_pair_new (MODEST_ACCOUNT_OPTION_USE_LSUB, ""));
376                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
377                                                       tny_pair_new (MODEST_ACCOUNT_OPTION_CHECK_ALL, ""));
378                 }
379                 
380                 username = modest_server_account_settings_get_username (server_settings);
381                 if (username && strlen (username) > 0) 
382                         tny_account_set_user (tny_account, username);
383                 hostname = modest_server_account_settings_get_hostname (server_settings);
384                 if (hostname)
385                         tny_account_set_hostname (tny_account, hostname);
386                  
387                 /* Set the port: */
388                 port = modest_server_account_settings_get_port (server_settings);
389                 if (port)
390                         tny_account_set_port (tny_account, port);
391         }
392
393         MODEST_DEBUG_BLOCK (
394                 gchar *url = tny_account_get_url_string (TNY_ACCOUNT(tny_account));
395                 g_debug ("%s:\n  account-url: %s\n", __FUNCTION__, url);
396                 g_free (url);
397         );
398         
399         return TRUE;
400 }
401
402 TnyAccount*
403 modest_tny_account_new_from_server_account_name (ModestAccountMgr *account_mgr,
404                                                  TnySessionCamel *session,
405                                                  const gchar *server_account_name,
406                                                  TnyGetPassFunc get_pass_func,
407                                                  TnyForgetPassFunc forget_pass_func)
408 {
409         ModestServerAccountSettings *server_settings;
410         TnyAccount *tny_account;
411         
412         g_return_val_if_fail (session, NULL);
413         g_return_val_if_fail (server_account_name, NULL);
414
415         
416         server_settings =       modest_account_mgr_load_server_settings (account_mgr, server_account_name);
417         if (!server_settings)
418                 return NULL;
419
420         tny_account = TNY_ACCOUNT (tny_camel_transport_account_new ());
421
422         if (tny_account) {
423                 const gchar* proto_name = NULL;
424                 tny_account_set_id (tny_account, server_account_name);
425                 tny_camel_account_set_session (TNY_CAMEL_ACCOUNT (tny_account), session);
426                 proto_name = modest_protocol_info_get_transport_store_protocol_name 
427                                     (modest_server_account_settings_get_protocol (server_settings));
428                 tny_account_set_proto (tny_account, proto_name);
429                 modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account, server_account_name);
430         }
431
432         if (!tny_account)
433                 g_warning ("%s: failed to create tny_account", __FUNCTION__);
434         else if (!update_tny_account (tny_account, server_settings))
435                 g_warning ("%s: failed to initialize tny_account", __FUNCTION__);
436         else {
437                 tny_account_set_forget_pass_func (tny_account,
438                                                   forget_pass_func ? forget_pass_func : forget_pass_dummy);
439                 tny_account_set_pass_func (tny_account,
440                                            get_pass_func ? get_pass_func: get_pass_dummy);
441         }
442
443         tny_account_set_connection_policy (tny_account, modest_default_connection_policy_new ());
444
445         g_object_unref (server_settings);
446         
447         return tny_account;
448 }
449
450
451
452
453 /* we need these dummy functions, or tinymail will complain */
454 static gchar*
455 get_pass_dummy (TnyAccount *account, const gchar *prompt, gboolean *cancel)
456 {
457         return NULL;
458 }
459 static void
460 forget_pass_dummy (TnyAccount *account)
461 {
462         /* intentionally left blank */
463 }
464
465
466 static void
467 set_online_callback (TnyCamelAccount *account, gboolean canceled, GError *err, gpointer user_data)
468 {
469         TnyAccountStore *account_store;
470
471         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
472                                                              "account_store"));
473         if (err && !canceled) {
474                 /* It seems err is forgotten here ... if the disk is full ! */
475                 if (account_store) {
476                         tny_account_store_alert (
477                                 account_store, 
478                                 TNY_ACCOUNT (account), TNY_ALERT_TYPE_ERROR, FALSE, 
479                                 err);
480                 }
481                 g_warning ("err: %s", err->message);
482         }
483 }
484
485 gboolean
486 modest_tny_account_update_from_account (TnyAccount *tny_account,
487                                         TnyGetPassFunc get_pass_func,
488                                         TnyForgetPassFunc forget_pass_func) 
489 {
490         ModestAccountSettings *settings = NULL;
491         ModestServerAccountSettings *server_settings = NULL;
492         ModestAccountMgr *account_mgr;
493         const gchar *account_name;
494         TnyAccountType type;
495         const gchar *display_name;
496         TnyConnectionStatus conn_status;
497
498         g_return_val_if_fail (tny_account, FALSE);
499
500         account_mgr = modest_runtime_get_account_mgr ();
501         account_name = modest_tny_account_get_parent_modest_account_name_for_server_account (tny_account);
502         type = tny_account_get_account_type (tny_account);
503         settings = modest_account_mgr_load_account_settings (account_mgr, account_name);
504         if (!settings) {
505                 g_printerr ("modest: %s: cannot get account data for account %s\n",
506                             __FUNCTION__, account_name);
507                 return FALSE;
508         }
509
510         display_name = modest_account_settings_get_display_name (settings);
511
512         if (type == TNY_ACCOUNT_TYPE_STORE)
513                 server_settings = modest_account_settings_get_store_settings (settings);
514         else if (type == TNY_ACCOUNT_TYPE_TRANSPORT)
515                 server_settings = modest_account_settings_get_transport_settings (settings);
516
517         if (modest_server_account_settings_get_account_name (server_settings) == NULL) {
518                 g_printerr ("modest: no %s account defined for '%s'\n",
519                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
520                             display_name);
521                 g_object_unref (server_settings);
522                 g_object_unref (settings);
523                 return FALSE;
524         }
525         
526         update_tny_account (tny_account, server_settings);
527                 
528         /* This name is what shows up in the folder view -- so for some POP/IMAP/... server
529          * account, we set its name to the account of which it is part. */
530
531         if (display_name)
532                 tny_account_set_name (tny_account, display_name);
533
534         g_object_unref (server_settings);
535         g_object_unref (settings);
536
537         tny_account_set_forget_pass_func (tny_account, NULL);
538         tny_account_set_pass_func (tny_account, NULL);
539         tny_account_set_forget_pass_func (tny_account,
540                                           forget_pass_func ? forget_pass_func : forget_pass_dummy);
541         tny_account_set_pass_func (tny_account,
542                                    get_pass_func ? get_pass_func: get_pass_dummy);
543
544         tny_account_set_connection_policy (tny_account, modest_default_connection_policy_new ());
545         
546         /* The callback will have an error for you if the reconnect
547          * failed. Please handle it (this is TODO). */
548         
549         conn_status = tny_account_get_connection_status (tny_account);
550         if (conn_status != TNY_CONNECTION_STATUS_DISCONNECTED) {
551                 TnyAccountStore *account_store = NULL;
552         
553                 account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(tny_account),
554                                                                      "account_store"));
555         
556                 if (account_store) {
557                         modest_tny_account_store_forget_already_asked (MODEST_TNY_ACCOUNT_STORE (account_store), 
558                                                                        tny_account);
559                 }
560         
561                 tny_camel_account_set_online (TNY_CAMEL_ACCOUNT(tny_account), TRUE, 
562                                               set_online_callback,  "online");
563         }
564         
565         return TRUE;
566 }
567
568
569
570 TnyAccount*
571 modest_tny_account_new_from_account (ModestAccountMgr *account_mgr,
572                                      const gchar *account_name,
573                                      TnyAccountType type,
574                                      TnySessionCamel *session,
575                                      TnyGetPassFunc get_pass_func,
576                                      TnyForgetPassFunc forget_pass_func) 
577 {
578         TnyAccount *tny_account = NULL;
579         ModestAccountSettings *settings = NULL;
580         ModestServerAccountSettings *server_settings = NULL;
581         const gchar *display_name;
582
583         g_return_val_if_fail (account_mgr, NULL);
584         g_return_val_if_fail (account_name, NULL);
585         g_return_val_if_fail (session, NULL);
586         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || type == TNY_ACCOUNT_TYPE_TRANSPORT,
587                               NULL);
588
589         settings = modest_account_mgr_load_account_settings (account_mgr, account_name);
590         if (!settings) {
591                 g_printerr ("modest: %s: cannot get account data for account %s\n",
592                             __FUNCTION__, account_name);
593                 return NULL;
594         }
595         display_name = modest_account_settings_get_display_name (settings);
596
597         if (type == TNY_ACCOUNT_TYPE_STORE)
598                 server_settings = modest_account_settings_get_store_settings (settings);
599         else if (type == TNY_ACCOUNT_TYPE_TRANSPORT)
600                 server_settings = modest_account_settings_get_transport_settings (settings);
601
602         if (modest_server_account_settings_get_account_name (server_settings) == NULL) {
603                 g_printerr ("modest: no %s account defined for '%s'\n",
604                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
605                             display_name);
606                 g_object_unref (server_settings);
607                 g_object_unref (settings);
608                 return NULL;
609         }
610         
611         tny_account = create_tny_account (session, server_settings);
612         if (!tny_account) { 
613                 g_printerr ("modest: failed to create tny account for %s (%s)\n",
614                             account_name, 
615                             modest_server_account_settings_get_account_name (server_settings));
616                 g_object_unref (server_settings);
617                 g_object_unref (settings);
618                 return NULL;
619         } else
620                 update_tny_account (tny_account, server_settings);
621                 
622         /* This name is what shows up in the folder view -- so for some POP/IMAP/... server
623          * account, we set its name to the account of which it is part. */
624  
625         if (display_name)
626                 tny_account_set_name (tny_account, display_name);
627
628         tny_account_set_forget_pass_func (tny_account,
629                                           forget_pass_func ? forget_pass_func : forget_pass_dummy);
630         tny_account_set_pass_func (tny_account,
631                                    get_pass_func ? get_pass_func: get_pass_dummy);
632
633         tny_account_set_connection_policy (tny_account, modest_default_connection_policy_new ());
634
635         modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account,
636                                                                               account_name);
637         g_object_unref (server_settings);
638         g_object_unref (settings);
639
640         return tny_account;
641 }
642
643 typedef struct
644 {
645         TnyStoreAccount *account;
646         
647         ModestTnyAccountGetMmcAccountNameCallback callback;
648         gpointer user_data;
649 } GetMmcAccountNameData;
650
651
652
653 #ifdef MODEST_PLATFORM_MAEMO
654 /* Gets the memory card name: */
655 static void 
656 on_modest_file_system_info (HildonFileSystemInfoHandle *handle,
657                             HildonFileSystemInfo *info,
658                             const GError *error, gpointer data)
659 {
660         GetMmcAccountNameData *callback_data = (GetMmcAccountNameData*)data;
661
662         if (error) {
663                 g_warning ("%s: error=%s", __FUNCTION__, error->message);
664         }
665         
666         TnyAccount *account = TNY_ACCOUNT (callback_data->account);
667         
668         const gchar *previous_display_name = NULL;
669         
670         const gchar *display_name = NULL;
671         if (!error && info) {
672                 display_name = hildon_file_system_info_get_display_name(info);
673                 previous_display_name = tny_account_get_name (account);
674         }
675                  
676         /* printf ("DEBUG: %s: display name=%s\n", __FUNCTION__,  display_name); */
677         if (display_name && previous_display_name && 
678                 (strcmp (display_name, previous_display_name) != 0)) {
679                 tny_account_set_name (account, display_name);
680         }
681                 
682         /* Inform the application that the name is now ready: */
683         if (callback_data->callback)
684                 (*(callback_data->callback)) (callback_data->account, 
685                         callback_data->user_data);
686         
687         g_object_unref (callback_data->account);
688         g_slice_free (GetMmcAccountNameData, callback_data);
689 }
690 #endif
691
692 void modest_tny_account_get_mmc_account_name (TnyStoreAccount* self, ModestTnyAccountGetMmcAccountNameCallback callback, gpointer user_data)
693 {
694 #ifdef MODEST_PLATFORM_MAEMO
695         /* Just use the hard-coded path for the single memory card,
696          * rather than try to figure out the path to the specific card by 
697          * looking at the maildir URI:
698          */
699         const gchar *uri_real = MODEST_MCC1_VOLUMEPATH_URI;
700
701         /*
702         gchar* uri = tny_account_get_url_string (TNY_ACCOUNT (self));
703         if (!uri)
704                 return;
705
706         TODO: This gets the name of the folder, but we want the name of the volume.
707         gchar *uri_real = NULL;
708         const gchar* prefix = "maildir://localhost/";
709         if ((strstr (uri, prefix) == uri) && (strlen(uri) > strlen(prefix)) )
710                 uri_real = g_strconcat ("file:///", uri + strlen (prefix), NULL);
711         */
712
713         if (uri_real) {
714                 //This is freed in the callback:
715                 GetMmcAccountNameData * callback_data = g_slice_new0(GetMmcAccountNameData);
716                 callback_data->account = self;
717                 g_object_ref (callback_data->account); /* Unrefed when we destroy the struct. */
718                 callback_data->callback = callback;
719                 callback_data->user_data = user_data;
720                 
721                 /* TODO: gnome_vfs_volume_get_display_name() does not return 
722                  * the same string. But why not? Why does hildon needs its own 
723                  * function for this?
724                  */
725                 /* printf ("DEBUG: %s Calling hildon_file_system_info_async_new() with URI=%s\n", __FUNCTION__, uri_real); */
726                 hildon_file_system_info_async_new(uri_real, 
727                         on_modest_file_system_info, callback_data /* user_data */);
728
729                 /* g_free (uri_real); */
730         }
731
732         /* g_free (uri); */
733 #endif
734 }
735
736                                 
737
738 TnyAccount*
739 modest_tny_account_new_for_local_folders (ModestAccountMgr *account_mgr, TnySessionCamel *session,
740                                           const gchar* location_filepath)
741 {
742
743         
744         /* Make sure that the directories exist: */
745         modest_init_local_folders (location_filepath);
746
747         TnyStoreAccount *tny_account;
748         CamelURL *url;
749         gchar *maildir, *url_string;
750
751         g_return_val_if_fail (account_mgr, NULL);
752         g_return_val_if_fail (session, NULL);
753
754         
755         if (!location_filepath) {
756                 /* A NULL filepath means that this is the special local-folders maildir 
757                  * account: */
758                 tny_account = TNY_STORE_ACCOUNT (modest_tny_local_folders_account_new ());
759         }
760         else {
761                 /* Else, for instance, a per-account outbox maildir account: */
762                 tny_account = TNY_STORE_ACCOUNT (tny_camel_store_account_new ());
763         }
764                 
765         if (!tny_account) {
766                 g_printerr ("modest: %s: cannot create account for local folders. filepath=%s", 
767                         __FUNCTION__, location_filepath);
768                 return NULL;
769         }
770         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
771         
772         /* This path contains directories for each local folder.
773          * We have created them so that TnyCamelStoreAccount can find them 
774          * and report a folder for each directory: */
775         maildir = modest_local_folder_info_get_maildir_path (location_filepath);
776         url = camel_url_new ("maildir:", NULL);
777         camel_url_set_path (url, maildir);
778         /* Needed by tinymail's DBC assertions */
779         camel_url_set_host (url, "localhost");
780         url_string = camel_url_to_string (url, 0);
781         
782         tny_account_set_url_string (TNY_ACCOUNT(tny_account), url_string);
783 /*      printf("DEBUG: %s:\n  url=%s\n", __FUNCTION__, url_string); */
784
785         /* TODO: Use a more generic way of identifying memory card paths, 
786          * and of marking accounts as memory card accounts, maybe
787          * via a derived TnyCamelStoreAccount ? */
788         const gboolean is_mmc = 
789                 location_filepath && 
790                 (strcmp (location_filepath, MODEST_MCC1_VOLUMEPATH) == 0);
791                 
792         /* The name of memory card locations will be updated asynchronously.
793          * This is just a default: */
794         const gchar *name = is_mmc ? _("Memory Card") : 
795                 MODEST_LOCAL_FOLDERS_DEFAULT_DISPLAY_NAME;
796         tny_account_set_name (TNY_ACCOUNT(tny_account), name); 
797         
798         /* Get the correct display name for memory cards, asynchronously: */
799         if (location_filepath) {
800                 GError *error = NULL;
801                 gchar *uri = g_filename_to_uri(location_filepath, NULL, &error);
802                 if (error) {
803                         g_warning ("%s: g_filename_to_uri(%s) failed: %s", __FUNCTION__, 
804                                 location_filepath, error->message);
805                         g_error_free (error);
806                         error = NULL;   
807                 } else if (uri) {
808                         /* Get the account name asynchronously:
809                          * This might not happen soon enough, so some UI code might 
810                          * need to call this again, specifying a callback.
811                          */
812                         modest_tny_account_get_mmc_account_name (tny_account, NULL, NULL);
813                                 
814                         g_free (uri);
815                         uri = NULL;
816                 }
817         }
818         
819         
820         const gchar* id = is_mmc ? MODEST_MMC_ACCOUNT_ID :
821                 MODEST_LOCAL_FOLDERS_ACCOUNT_ID;
822         tny_account_set_id (TNY_ACCOUNT(tny_account), id);
823         
824         tny_account_set_forget_pass_func (TNY_ACCOUNT(tny_account), forget_pass_dummy);
825         tny_account_set_pass_func (TNY_ACCOUNT(tny_account), get_pass_dummy);
826
827         tny_account_set_connection_policy (TNY_ACCOUNT (tny_account), modest_default_connection_policy_new ()); 
828
829         modest_tny_account_set_parent_modest_account_name_for_server_account (
830                 TNY_ACCOUNT (tny_account), id);
831         
832         camel_url_free (url);
833         g_free (maildir);
834         g_free (url_string);
835
836         return TNY_ACCOUNT(tny_account);
837 }
838
839
840 TnyAccount*
841 modest_tny_account_new_for_per_account_local_outbox_folder (ModestAccountMgr *account_mgr,
842                                                             const gchar* account_name,
843                                                             TnySessionCamel *session)
844 {
845         g_return_val_if_fail (account_mgr, NULL);
846         g_return_val_if_fail (account_name, NULL);
847         g_return_val_if_fail (session, NULL);
848         
849         /* Notice that we create a ModestTnyOutboxAccount here, 
850          * instead of just a TnyCamelStoreAccount,
851          * so that we can later identify this as a special account for internal use only.
852          */
853         TnyStoreAccount *tny_account = TNY_STORE_ACCOUNT (modest_tny_outbox_account_new ());
854         if (!tny_account) {
855                 g_printerr ("modest: cannot create account for per-account local outbox folder.");
856                 return NULL;
857         }
858         
859         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
860         
861         /* Make sure that the paths exists on-disk so that TnyCamelStoreAccount can 
862          * find it to create a TnyFolder for it: */
863         gchar *folder_dir = modest_per_account_local_outbox_folder_info_get_maildir_path_to_outbox_folder (account_name); 
864         modest_init_one_local_folder(folder_dir);
865         g_free (folder_dir);
866         folder_dir = NULL;
867
868         /* This path should contain just one directory - "outbox": */
869         gchar *maildir = 
870                 modest_per_account_local_outbox_folder_info_get_maildir_path (account_name);
871                         
872         CamelURL *url = camel_url_new ("maildir:", NULL);
873         camel_url_set_path (url, maildir);
874         g_free (maildir);
875         
876         /* Needed by tinymail's DBC assertions */
877         camel_url_set_host (url, "localhost");
878         gchar *url_string = camel_url_to_string (url, 0);
879         camel_url_free (url);
880         
881         tny_account_set_url_string (TNY_ACCOUNT(tny_account), url_string);
882 /*      printf("DEBUG: %s:\n  url=%s\n", __FUNCTION__, url_string); */
883         g_free (url_string);
884
885         /* This text should never been seen,
886          * because the per-account outbox accounts are not seen directly by the user.
887          * Their folders are merged and shown as one folder. */ 
888         tny_account_set_name (TNY_ACCOUNT(tny_account), "Per-Account Outbox"); 
889         
890         gchar *account_id = g_strdup_printf (
891                 MODEST_PER_ACCOUNT_LOCAL_OUTBOX_FOLDER_ACCOUNT_ID_PREFIX "%s", 
892                 account_name);
893         tny_account_set_id (TNY_ACCOUNT(tny_account), account_id);
894         g_free (account_id);
895         
896         tny_account_set_forget_pass_func (TNY_ACCOUNT(tny_account), forget_pass_dummy);
897         tny_account_set_pass_func (TNY_ACCOUNT(tny_account), get_pass_dummy);
898
899         tny_account_set_connection_policy (TNY_ACCOUNT (tny_account), modest_default_connection_policy_new ());
900
901         /* Make this think that it belongs to the modest local-folders parent account: */
902         modest_tny_account_set_parent_modest_account_name_for_server_account (
903                 TNY_ACCOUNT (tny_account), MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
904
905         return TNY_ACCOUNT(tny_account);
906 }
907
908
909
910 typedef gint (*TnyStatsFunc) (TnyFolderStats *stats);
911 #define TASK_GET_ALL_COUNT      0
912 #define TASK_GET_LOCAL_SIZE     1
913 #define TASK_GET_FOLDER_COUNT   2
914
915 typedef struct _RecurseFoldersHelper {
916         gint task;
917         guint sum;
918         guint folders;
919 } RecurseFoldersHelper;
920
921 static void
922 recurse_folders (TnyFolderStore *store, 
923                  TnyFolderStoreQuery *query, 
924                  RecurseFoldersHelper *helper)
925 {
926         TnyIterator *iter;
927         TnyList *folders = tny_simple_list_new ();
928
929         tny_folder_store_get_folders (store, folders, query, NULL);
930         iter = tny_list_create_iterator (folders);
931
932         helper->folders += tny_list_get_length (folders);
933
934         while (!tny_iterator_is_done (iter)) {
935                 TnyFolder *folder;
936
937                 folder = TNY_FOLDER (tny_iterator_get_current (iter));
938                 if (folder) {
939                         if (helper->task == TASK_GET_ALL_COUNT)
940                                 helper->sum += tny_folder_get_all_count (folder);
941
942                         if (helper->task == TASK_GET_LOCAL_SIZE)
943                                 helper->sum += tny_folder_get_local_size (folder);
944
945                         if (TNY_IS_FOLDER_STORE (folder))
946                                 recurse_folders (TNY_FOLDER_STORE (folder), query, helper);
947
948                         g_object_unref (folder);
949                 }
950
951                 tny_iterator_next (iter);
952         }
953          g_object_unref (G_OBJECT (iter));
954          g_object_unref (G_OBJECT (folders));
955 }
956
957 gint 
958 modest_tny_folder_store_get_folder_count (TnyFolderStore *self)
959 {
960         RecurseFoldersHelper *helper;
961         gint retval;
962
963         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
964
965         /* Create helper */
966         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
967         helper->task = TASK_GET_FOLDER_COUNT;
968         helper->folders = 0;
969
970         recurse_folders (self, NULL, helper);
971
972         retval = helper->folders;
973
974         g_free (helper);
975
976         return retval;
977 }
978
979 gint
980 modest_tny_folder_store_get_message_count (TnyFolderStore *self)
981 {
982         RecurseFoldersHelper *helper;
983         gint retval;
984
985         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
986         
987         /* Create helper */
988         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
989         helper->task = TASK_GET_ALL_COUNT;
990         if (TNY_IS_FOLDER (self))
991                 helper->sum = tny_folder_get_all_count (TNY_FOLDER (self));
992
993         recurse_folders (self, NULL, helper);
994
995         retval = helper->sum;
996
997         g_free (helper);
998
999         return retval;
1000 }
1001
1002 gint 
1003 modest_tny_folder_store_get_local_size (TnyFolderStore *self)
1004 {
1005         RecurseFoldersHelper *helper;
1006         gint retval;
1007
1008         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
1009
1010         /* Create helper */
1011         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
1012         helper->task = TASK_GET_LOCAL_SIZE;
1013         if (TNY_IS_FOLDER (self))
1014                 helper->sum = tny_folder_get_local_size (TNY_FOLDER (self));
1015
1016         recurse_folders (self, NULL, helper);
1017
1018         retval = helper->sum;
1019
1020         g_free (helper);
1021
1022         return retval;
1023 }
1024
1025 const gchar* 
1026 modest_tny_account_get_parent_modest_account_name_for_server_account (TnyAccount *self)
1027 {
1028         return (const gchar *)g_object_get_data (G_OBJECT (self), "modest_account");
1029 }
1030
1031 void 
1032 modest_tny_account_set_parent_modest_account_name_for_server_account (TnyAccount *self, 
1033                                                                       const gchar* parent_modest_account_name)
1034 {
1035         g_object_set_data_full (G_OBJECT(self), "modest_account",
1036                                 (gpointer) g_strdup (parent_modest_account_name), g_free);
1037 }
1038
1039 gboolean
1040 modest_tny_account_is_virtual_local_folders (TnyAccount *self)
1041 {
1042         /* We should make this more sophisticated if we ever use ModestTnyLocalFoldersAccount 
1043          * for anything else. */
1044         return MODEST_IS_TNY_LOCAL_FOLDERS_ACCOUNT (self);
1045 }
1046
1047
1048 gboolean
1049 modest_tny_account_is_memory_card_account (TnyAccount *self)
1050 {
1051         const gchar* account_id = NULL;
1052
1053         g_return_val_if_fail (TNY_ACCOUNT (self), FALSE);
1054
1055         if (!self)
1056                 return FALSE;
1057
1058         account_id = tny_account_get_id (self);
1059
1060         if (!account_id)
1061                 return FALSE;
1062         else    
1063                 return (strcmp (account_id, MODEST_MMC_ACCOUNT_ID) == 0);
1064 }
1065
1066 gboolean 
1067 modest_tny_folder_store_is_remote (TnyFolderStore *folder_store)
1068 {
1069         TnyAccount *account = NULL;
1070         gboolean result = TRUE;
1071
1072         g_return_val_if_fail(TNY_IS_FOLDER_STORE(folder_store), FALSE);
1073
1074         if (TNY_IS_FOLDER (folder_store)) {
1075                 /* Get the folder's parent account: */
1076                 account = tny_folder_get_account(TNY_FOLDER(folder_store));
1077         } else if (TNY_IS_ACCOUNT (folder_store)) {
1078                 account = TNY_ACCOUNT(folder_store);
1079                 g_object_ref(account);
1080         }
1081
1082         if (account != NULL) {
1083                 if (tny_account_get_account_type (account) == TNY_ACCOUNT_TYPE_STORE) {
1084                         if (!TNY_IS_CAMEL_POP_STORE_ACCOUNT (account) &&
1085                             !TNY_IS_CAMEL_IMAP_STORE_ACCOUNT (account)) {
1086                                 /* This must be a maildir account, which does
1087                                  * not require a connection: */
1088                                 result = FALSE;
1089                         }
1090                 }
1091                 g_object_unref (account);
1092         } else {
1093                 result = FALSE;
1094         }
1095
1096         return result;
1097 }
1098