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