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