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