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