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