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