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