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