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