Remove Hildon 0.x conditional code because Hildon 0.x is not available in Diablo...
[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-defs.h>
32 #include <modest-tny-platform-factory.h>
33 #include <modest-tny-account.h>
34 #include <modest-tny-account-store.h>
35 #include <modest-default-connection-policy.h>
36 #include <modest-tny-local-folders-account.h>
37 #include <modest-runtime.h>
38 #include <tny-simple-list.h>
39 #include <modest-tny-folder.h>
40 #include <modest-tny-outbox-account.h>
41 #include <modest-transport-account-decorator.h>
42 #include <modest-account-mgr-helpers.h>
43 #include <modest-init.h>
44 #include <tny-camel-transport-account.h>
45 #include <tny-camel-imap-store-account.h>
46 #include <tny-camel-pop-store-account.h>
47 #include <modest-account-protocol.h>
48 #include <tny-folder-stats.h>
49 #include <tny-merge-folder.h>
50 #include <modest-debug.h>
51 #include <string.h>
52 #ifndef MODEST_TOOLKIT_GTK
53 #include <hildon/hildon-file-system-info.h>
54 #endif
55
56 /* we need these dummy functions, or tinymail will complain */
57 static gchar *  get_pass_dummy     (TnyAccount *account, const gchar *prompt, gboolean *cancel);
58 static void     forget_pass_dummy  (TnyAccount *account);
59
60 TnyFolder *
61 modest_tny_account_get_special_folder (TnyAccount *account,
62                                        TnyFolderType special_type)
63 {
64         TnyList *folders = NULL;
65         TnyIterator *iter = NULL;
66         TnyFolder *special_folder = NULL;
67         TnyAccount *local_account  = NULL;
68         GError *error = NULL;
69         
70         g_return_val_if_fail (account, NULL);
71         g_return_val_if_fail (0 <= special_type && special_type < TNY_FOLDER_TYPE_NUM,
72                               NULL);
73         
74         /* The accounts have already been instantiated by 
75          * modest_tny_account_store_get_accounts(), which is the 
76          * TnyAccountStore::get_accounts_func() implementation,
77          * so we just get them here.
78          */
79          
80         /* Per-account outbox folders are each in their own on-disk directory: */
81         if ((special_type == TNY_FOLDER_TYPE_OUTBOX) &&
82             (!modest_tny_account_is_virtual_local_folders (account))) {
83
84                 gchar *account_id;
85                 const gchar *modest_account_name;
86
87                 modest_account_name =
88                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
89                 if (!modest_account_name) {
90                         g_warning ("%s: could not get modest account name", __FUNCTION__);
91                         return NULL;
92                 }
93                 
94                 account_id = g_strdup_printf (
95                         MODEST_PER_ACCOUNT_LOCAL_OUTBOX_FOLDER_ACCOUNT_ID_PREFIX "%s", 
96                         modest_account_name);
97                 
98                 local_account = modest_tny_account_store_get_tny_account_by (modest_runtime_get_account_store(),
99                                                                              MODEST_TNY_ACCOUNT_STORE_QUERY_ID,
100                                                                              account_id);
101                 g_free (account_id);            
102         } else 
103                 /* Other local folders are all in one on-disk directory: */
104                 local_account = modest_tny_account_store_get_tny_account_by (modest_runtime_get_account_store(),
105                                                                              MODEST_TNY_ACCOUNT_STORE_QUERY_ID,
106                                                                              MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
107         if (!local_account) {
108                 g_printerr ("modest: cannot get local account\n");
109                 goto cleanup;
110         }
111
112         folders = TNY_LIST (tny_simple_list_new ());
113         
114         /* There is no need to do this _async, as these are local folders. */
115         /* TODO: However, this seems to fail sometimes when the network is busy, 
116          * returning an empty list. murrayc. */ 
117         tny_folder_store_get_folders (TNY_FOLDER_STORE (local_account), folders, NULL, FALSE, &error);
118         if (error) {
119                 g_debug ("%s: tny_folder_store_get_folders() failed:%s\n", __FUNCTION__, error->message);
120                 g_error_free (error);
121                 goto cleanup;
122         }
123                                       
124         if (tny_list_get_length (folders) == 0) {
125                 gchar* url_string = tny_account_get_url_string (local_account);
126                 g_printerr ("modest: %s: tny_folder_store_get_folders(%s) returned an empty list\n", 
127                             __FUNCTION__, url_string);
128                 g_free (url_string);
129                 goto cleanup;
130         }
131         
132         iter = tny_list_create_iterator (folders);
133
134         while (!tny_iterator_is_done (iter)) {
135                 TnyFolder *folder = TNY_FOLDER (tny_iterator_get_current (iter));
136                 if (folder) {
137                         if (modest_tny_folder_get_local_or_mmc_folder_type (folder) == special_type) {
138                                 special_folder = folder;
139                                 break; /* Leaving a ref for the special_folder return value. */
140                         }
141                         g_object_unref (folder);
142                 }
143                 tny_iterator_next (iter);
144         }
145         
146 cleanup:
147         if (folders)
148                 g_object_unref (folders);
149         if (iter)
150                 g_object_unref (iter);
151         if (local_account)
152                 g_object_unref (local_account);
153         
154         return special_folder;
155 }
156
157 /**
158  * create_tny_account:
159  * @session: A valid TnySessionCamel instance.
160  * @account_data: the server account for which to create a corresponding tny account
161  * 
162  * get a tnyaccount corresponding to the server_accounts (store or transport) for this account.
163  * NOTE: this function does not set the camel session or the get/forget password functions
164  * 
165  * Returns: a new TnyAccount or NULL in case of error.
166  */
167 static TnyAccount*
168 create_tny_account (TnySessionCamel *session,
169                     ModestServerAccountSettings *server_settings)
170 {
171         TnyAccount *tny_account = NULL;
172         ModestProtocolType protocol_type;
173         ModestProtocolRegistry *protocol_registry;
174         ModestProtocol *protocol;
175         
176         g_return_val_if_fail (session, NULL);
177         g_return_val_if_fail (server_settings, NULL);
178         protocol_type = modest_server_account_settings_get_protocol (server_settings);
179         g_return_val_if_fail (protocol_type != MODEST_PROTOCOL_REGISTRY_TYPE_INVALID, NULL);
180         
181         protocol_registry = modest_runtime_get_protocol_registry ();
182         protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, protocol_type);
183
184         if (MODEST_IS_ACCOUNT_PROTOCOL (protocol)) {
185                 ModestAccountProtocol *acocunt_proto = MODEST_ACCOUNT_PROTOCOL (protocol);
186                 tny_account = modest_account_protocol_create_account (acocunt_proto);
187         }
188
189         if (!tny_account) {
190                 g_printerr ("modest: %s: could not create tny account for '%s'\n",
191                             __FUNCTION__, modest_server_account_settings_get_account_name (server_settings));
192                 return NULL;
193         }
194         tny_account_set_id (tny_account, modest_server_account_settings_get_account_name (server_settings));
195
196         /* This must be set quite early, or other set() functions will fail. */
197         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT (tny_account), session);
198     
199         /* Proto */
200         tny_account_set_proto (tny_account, modest_protocol_get_name (protocol));
201
202         return tny_account;
203 }
204
205
206
207 /* Camel options: */
208
209 #define MODEST_ACCOUNT_OPTION_SSL "use_ssl"
210
211
212                 
213 /**
214  * update_tny_account:
215  * @account_mgr: a valid account mgr instance
216  * @account_data: the server account for which to create a corresponding tny account
217  * 
218  * get a tnyaccount corresponding to the server_accounts (store or transport) for this account.
219  * NOTE: this function does not set the camel session or the get/forget password functions
220  * 
221  * Returns: a new TnyAccount or NULL in case of error.
222  */
223 static gboolean
224 update_tny_account (TnyAccount *tny_account,
225                     ModestServerAccountSettings *server_settings)
226 {
227         const gchar *account_name;
228         const gchar *uri;
229         g_return_val_if_fail (server_settings, FALSE);
230         account_name = modest_server_account_settings_get_account_name (server_settings);
231         g_return_val_if_fail (account_name, FALSE);
232         g_return_val_if_fail (tny_account, FALSE);
233         
234         /* Do not change the id if it's not needed */
235         if (tny_account_get_id (tny_account) && 
236             strcmp (tny_account_get_id (tny_account), account_name))
237                 tny_account_set_id (tny_account, account_name);
238         
239         /* mbox and maildir accounts use a URI instead of the rest:
240          * Note that this is not where we create the special local folders account.
241          * We do that in modest_tny_account_new_for_local_folders() instead. */
242         uri = modest_server_account_settings_get_uri (server_settings);
243         if (uri)  
244                 tny_account_set_url_string (TNY_ACCOUNT(tny_account), uri);
245         else {
246                 /* Set camel-specific options: */               
247                 /* Enable secure connection settings: */
248                 TnyPair *option_security = NULL;
249                 const gchar* auth_mech_name = NULL;
250                 ModestProtocolType protocol_type;
251                 ModestProtocol *protocol;
252                 ModestProtocolType security_type;
253                 ModestProtocol *security;
254                 ModestProtocolType auth_protocol_type;
255                 ModestProtocol *auth_protocol;
256                 ModestProtocolRegistry *protocol_registry;
257                 const gchar *security_option_string;
258                 const gchar *username;
259                 const gchar *hostname;
260                 guint port;
261
262                 /* First of all delete old options */
263                 tny_camel_account_clear_options (TNY_CAMEL_ACCOUNT (tny_account));
264
265                 protocol_type = modest_server_account_settings_get_protocol (server_settings);
266                 security_type = modest_server_account_settings_get_security_protocol (server_settings);
267                 auth_protocol_type = modest_server_account_settings_get_auth_protocol (server_settings);
268                 protocol_registry = modest_runtime_get_protocol_registry ();
269                 protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, protocol_type);
270                 security = modest_protocol_registry_get_protocol_by_type (protocol_registry, security_type);
271                 auth_protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, auth_protocol_type);
272
273                 security_option_string = modest_protocol_get (security, MODEST_PROTOCOL_SECURITY_ACCOUNT_OPTION);
274                 if (security_option_string) {
275                         option_security = tny_pair_new (MODEST_ACCOUNT_OPTION_SSL, security_option_string);
276                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account), option_security);
277                         g_object_unref (option_security);
278                 }
279
280                 /* Secure authentication: */
281                 if (MODEST_IS_ACCOUNT_PROTOCOL (protocol) &&
282                     modest_account_protocol_has_custom_secure_auth_mech (MODEST_ACCOUNT_PROTOCOL (protocol), auth_protocol_type)) {
283                         auth_mech_name = modest_account_protocol_get_custom_secure_auth_mech (MODEST_ACCOUNT_PROTOCOL (protocol), auth_protocol_type);
284                 } else {
285                         auth_mech_name = modest_protocol_get (auth_protocol, MODEST_PROTOCOL_AUTH_ACCOUNT_OPTION);
286                 }
287                 
288                 if (auth_mech_name)
289                         tny_account_set_secure_auth_mech (tny_account, auth_mech_name);
290                 
291                 if (MODEST_IS_ACCOUNT_PROTOCOL (protocol)) {
292                         TnyList *account_options;
293                         TnyIterator *iterator;
294
295                         account_options = modest_account_protocol_get_account_options (MODEST_ACCOUNT_PROTOCOL (protocol));
296                         for (iterator = tny_list_create_iterator (account_options); !tny_iterator_is_done (iterator); tny_iterator_next (iterator)) {
297                                 TnyPair *current;
298
299                                 current = TNY_PAIR (tny_iterator_get_current (iterator));
300                                 tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
301                                                               current);
302                                 g_object_unref (current);
303                         }
304                         g_object_unref (iterator);
305                         g_object_unref (account_options);
306                         
307                 }
308
309                 if (modest_server_account_settings_get_uri (server_settings) == NULL) {
310                         username = modest_server_account_settings_get_username (server_settings);
311                         if (username && strlen (username) > 0) 
312                                 tny_account_set_user (tny_account, username);
313                         hostname = modest_server_account_settings_get_hostname (server_settings);
314                         if (hostname && hostname[0] != '\0')
315                                 tny_account_set_hostname (tny_account, hostname);
316                         
317                         /* Set the port: */
318                         port = modest_server_account_settings_get_port (server_settings);
319                         if (port)
320                                 tny_account_set_port (tny_account, port);
321                 } else {
322                         tny_account_set_url_string (TNY_ACCOUNT (tny_account), modest_server_account_settings_get_uri (server_settings));
323                 }
324         }
325
326         MODEST_DEBUG_BLOCK (
327                 gchar *url = tny_account_get_url_string (TNY_ACCOUNT(tny_account));
328                 g_debug ("%s:\n  account-url: %s\n", __FUNCTION__, url);
329                 g_free (url);
330         );
331         
332         return TRUE;
333 }
334
335 TnyAccount*
336 modest_tny_account_new_from_server_account_name (ModestAccountMgr *account_mgr,
337                                                  TnySessionCamel *session,
338                                                  const gchar *server_account_name,
339                                                  TnyGetPassFunc get_pass_func,
340                                                  TnyForgetPassFunc forget_pass_func)
341 {
342         ModestServerAccountSettings *server_settings;
343         TnyAccount *tny_account;
344         ModestProtocolRegistry *protocol_registry;
345         
346         g_return_val_if_fail (session, NULL);
347         g_return_val_if_fail (server_account_name, NULL);
348
349         protocol_registry = modest_runtime_get_protocol_registry ();
350         
351         server_settings = modest_account_mgr_load_server_settings (account_mgr, server_account_name, TRUE);
352         if (!server_settings)
353                 return NULL;
354
355         tny_account = TNY_ACCOUNT (tny_camel_transport_account_new ());
356
357         if (tny_account) {
358                 ModestProtocol *protocol;
359                 const gchar* proto_name = NULL;
360                 tny_account_set_id (tny_account, server_account_name);
361                 tny_account_set_name (tny_account, server_account_name);
362                 tny_camel_account_set_session (TNY_CAMEL_ACCOUNT (tny_account), session);
363                 protocol = modest_protocol_registry_get_protocol_by_type (protocol_registry, modest_server_account_settings_get_protocol (server_settings));
364                 proto_name = modest_protocol_get_name (protocol);
365                 tny_account_set_proto (tny_account, proto_name);
366                 modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account, server_account_name);
367         }
368
369         if (!tny_account) {
370                 g_warning ("%s: failed to create tny_account", __FUNCTION__);
371         } else {
372                 TnyConnectionPolicy *policy;
373
374                 if (!update_tny_account (tny_account, server_settings)) {
375                         g_warning ("%s: failed to initialize tny_account", __FUNCTION__);
376                 } else {
377                         
378                         tny_account_set_forget_pass_func (tny_account,
379                                                           forget_pass_func ? forget_pass_func : forget_pass_dummy);
380                         tny_account_set_pass_func (tny_account,
381                                                    get_pass_func ? get_pass_func: get_pass_dummy);
382                         
383                 }
384                 policy = modest_default_connection_policy_new ();
385                 tny_account_set_connection_policy (tny_account, policy);
386                 g_object_unref (policy);
387         }
388
389         g_object_unref (server_settings);
390         
391         return tny_account;
392 }
393
394
395
396
397 /* we need these dummy functions, or tinymail will complain */
398 static gchar*
399 get_pass_dummy (TnyAccount *account, const gchar *prompt, gboolean *cancel)
400 {
401         return NULL;
402 }
403 static void
404 forget_pass_dummy (TnyAccount *account)
405 {
406         /* intentionally left blank */
407 }
408
409
410 static void
411 set_online_callback (TnyCamelAccount *account, gboolean canceled, GError *err, gpointer user_data)
412 {
413         TnyAccountStore *account_store;
414
415         account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(account),
416                                                              "account_store"));
417         if (err && !canceled) {
418                 /* It seems err is forgotten here ... if the disk is full ! */
419                 if (account_store) {
420                         tny_account_store_alert (
421                                 account_store, 
422                                 TNY_ACCOUNT (account), TNY_ALERT_TYPE_ERROR, FALSE, 
423                                 err);
424                 }
425                 g_debug ("err: %s", err->message);
426         }
427 }
428
429 gboolean
430 modest_tny_account_update_from_account (TnyAccount *tny_account,
431                                         TnyGetPassFunc get_pass_func,
432                                         TnyForgetPassFunc forget_pass_func) 
433 {
434         ModestAccountSettings *settings = NULL;
435         ModestServerAccountSettings *server_settings = NULL;
436         ModestAccountMgr *account_mgr;
437         const gchar *account_name;
438         TnyAccountType type;
439         const gchar *display_name;
440         TnyConnectionStatus conn_status;
441         TnyConnectionPolicy *policy;
442
443         g_return_val_if_fail (tny_account, FALSE);
444
445         account_mgr = modest_runtime_get_account_mgr ();
446         account_name = modest_tny_account_get_parent_modest_account_name_for_server_account (tny_account);
447         type = tny_account_get_account_type (tny_account);
448         settings = modest_account_mgr_load_account_settings (account_mgr, account_name);
449         if (!settings) {
450                 g_printerr ("modest: %s: cannot get account data for account %s\n",
451                             __FUNCTION__, account_name);
452                 return FALSE;
453         }
454
455         display_name = modest_account_settings_get_display_name (settings);
456
457         if (type == TNY_ACCOUNT_TYPE_STORE)
458                 server_settings = modest_account_settings_get_store_settings (settings);
459         else if (type == TNY_ACCOUNT_TYPE_TRANSPORT)
460                 server_settings = modest_account_settings_get_transport_settings (settings);
461
462         if (modest_server_account_settings_get_account_name (server_settings) == NULL) {
463                 g_printerr ("modest: no %s account defined for '%s'\n",
464                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
465                             display_name);
466                 g_object_unref (server_settings);
467                 g_object_unref (settings);
468                 return FALSE;
469         }
470         
471         update_tny_account (tny_account, server_settings);
472                 
473         /* This name is what shows up in the folder view -- so for some POP/IMAP/... server
474          * account, we set its name to the account of which it is part. */
475
476         if (display_name)
477                 tny_account_set_name (tny_account, display_name);
478
479         g_object_unref (server_settings);
480         g_object_unref (settings);
481
482         policy = modest_default_connection_policy_new ();
483         tny_account_set_connection_policy (tny_account, policy);
484         g_object_unref (policy);
485         
486         /* The callback will have an error for you if the reconnect
487          * failed. Please handle it (this is TODO). */
488         
489         conn_status = tny_account_get_connection_status (tny_account);
490         if (conn_status != TNY_CONNECTION_STATUS_DISCONNECTED) {
491                 TnyAccountStore *account_store = NULL;
492         
493                 account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(tny_account),
494                                                                      "account_store"));
495         
496                 if (account_store) {
497                         modest_tny_account_store_forget_already_asked (MODEST_TNY_ACCOUNT_STORE (account_store), 
498                                                                        tny_account);
499                 }
500         
501                 tny_camel_account_set_online (TNY_CAMEL_ACCOUNT(tny_account), TRUE, 
502                                               set_online_callback,  "online");
503         }
504         
505         return TRUE;
506 }
507
508
509
510 TnyAccount*
511 modest_tny_account_new_from_account (ModestAccountMgr *account_mgr,
512                                      const gchar *account_name,
513                                      TnyAccountType type,
514                                      TnySessionCamel *session,
515                                      TnyGetPassFunc get_pass_func,
516                                      TnyForgetPassFunc forget_pass_func) 
517 {
518         TnyAccount *tny_account = NULL;
519         ModestAccountSettings *settings = NULL;
520         ModestServerAccountSettings *server_settings = NULL;
521         const gchar *display_name;
522         TnyConnectionPolicy *policy;
523
524         g_return_val_if_fail (account_mgr, NULL);
525         g_return_val_if_fail (account_name, NULL);
526         g_return_val_if_fail (session, NULL);
527         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || type == TNY_ACCOUNT_TYPE_TRANSPORT,
528                               NULL);
529
530         settings = modest_account_mgr_load_account_settings (account_mgr, account_name);
531         if (!settings) {
532                 g_printerr ("modest: %s: cannot get account data for account %s\n",
533                             __FUNCTION__, account_name);
534                 return NULL;
535         }
536         display_name = modest_account_settings_get_display_name (settings);
537
538         if (type == TNY_ACCOUNT_TYPE_STORE)
539                 server_settings = modest_account_settings_get_store_settings (settings);
540         else if (type == TNY_ACCOUNT_TYPE_TRANSPORT)
541                 server_settings = modest_account_settings_get_transport_settings (settings);
542
543         if (modest_server_account_settings_get_account_name (server_settings) == NULL) {
544                 g_printerr ("modest: no %s account defined for '%s'\n",
545                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
546                             display_name);
547                 g_object_unref (server_settings);
548                 g_object_unref (settings);
549                 return NULL;
550         }
551         
552         tny_account = create_tny_account (session, server_settings);
553         if (!tny_account) { 
554                 g_printerr ("modest: failed to create tny account for %s (%s)\n",
555                             account_name, 
556                             modest_server_account_settings_get_account_name (server_settings));
557                 g_object_unref (server_settings);
558                 g_object_unref (settings);
559                 return NULL;
560         } else
561                 update_tny_account (tny_account, server_settings);
562                 
563         /* This name is what shows up in the folder view -- so for some POP/IMAP/... server
564          * account, we set its name to the account of which it is part. */
565  
566         if (display_name)
567                 tny_account_set_name (tny_account, display_name);
568
569         tny_account_set_forget_pass_func (tny_account,
570                                           forget_pass_func ? forget_pass_func : forget_pass_dummy);
571         tny_account_set_pass_func (tny_account,
572                                    get_pass_func ? get_pass_func: get_pass_dummy);
573
574         policy = modest_default_connection_policy_new ();
575         tny_account_set_connection_policy (tny_account, policy);
576         g_object_unref (policy);
577
578         modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account,
579                                                                               account_name);
580         g_object_unref (server_settings);
581         g_object_unref (settings);
582
583         return tny_account;
584 }
585
586 typedef struct
587 {
588         TnyStoreAccount *account;
589         
590         ModestTnyAccountGetMmcAccountNameCallback callback;
591         gpointer user_data;
592 } GetMmcAccountNameData;
593
594
595
596 #ifndef MODEST_TOOLKIT_GTK
597 /* Gets the memory card name: */
598 static void 
599 on_modest_file_system_info (HildonFileSystemInfoHandle *handle,
600                             HildonFileSystemInfo *info,
601                             const GError *error, gpointer data)
602 {
603         GetMmcAccountNameData *callback_data = (GetMmcAccountNameData*)data;
604
605         if (error) {
606                 g_debug ("%s: error=%s", __FUNCTION__, error->message);
607         }
608         
609         TnyAccount *account = TNY_ACCOUNT (callback_data->account);
610         
611         const gchar *previous_display_name = NULL;
612         
613         const gchar *display_name = NULL;
614         if (!error && info) {
615                 display_name = hildon_file_system_info_get_display_name(info);
616                 previous_display_name = tny_account_get_name (account);
617         }
618                  
619         /* printf ("DEBUG: %s: display name=%s\n", __FUNCTION__,  display_name); */
620         if (display_name && previous_display_name && 
621                 (strcmp (display_name, previous_display_name) != 0)) {
622                 tny_account_set_name (account, display_name);
623         }
624                 
625         /* Inform the application that the name is now ready: */
626         if (callback_data->callback)
627                 (*(callback_data->callback)) (callback_data->account, 
628                         callback_data->user_data);
629         
630         g_object_unref (callback_data->account);
631         g_slice_free (GetMmcAccountNameData, callback_data);
632 }
633 #endif
634
635 void modest_tny_account_get_mmc_account_name (TnyStoreAccount* self, ModestTnyAccountGetMmcAccountNameCallback callback, gpointer user_data)
636 {
637 #ifndef MODEST_TOOLKIT_GTK
638         /* Just use the path for the single memory card,
639          * rather than try to figure out the path to the specific card by 
640          * looking at the maildir URI:
641          */
642         gchar *uri_real = g_strconcat (MODEST_MMC1_VOLUMEPATH_URI_PREFIX,
643                                        g_getenv (MODEST_MMC1_VOLUMEPATH_ENV),
644                                        NULL);
645
646         /*
647         gchar* uri = tny_account_get_url_string (TNY_ACCOUNT (self));
648         if (!uri)
649                 return;
650
651         TODO: This gets the name of the folder, but we want the name of the volume.
652         gchar *uri_real = NULL;
653         const gchar* prefix = "maildir://localhost/";
654         if ((strstr (uri, prefix) == uri) && (strlen(uri) > strlen(prefix)) )
655                 uri_real = g_strconcat ("file:///", uri + strlen (prefix), NULL);
656         */
657
658         if (uri_real) {
659                 //This is freed in the callback:
660                 GetMmcAccountNameData * callback_data = g_slice_new0(GetMmcAccountNameData);
661                 callback_data->account = self;
662                 g_object_ref (callback_data->account); /* Unrefed when we destroy the struct. */
663                 callback_data->callback = callback;
664                 callback_data->user_data = user_data;
665                 
666                 /* TODO: gnome_vfs_volume_get_display_name() does not return 
667                  * the same string. But why not? Why does hildon needs its own 
668                  * function for this?
669                  */
670                 /* printf ("DEBUG: %s Calling hildon_file_system_info_async_new() with URI=%s\n", __FUNCTION__, uri_real); */
671                 hildon_file_system_info_async_new(uri_real, 
672                         on_modest_file_system_info, callback_data /* user_data */);
673
674                 g_free (uri_real);
675         }
676
677         /* g_free (uri); */
678 #endif
679 }
680
681                                 
682
683 TnyAccount*
684 modest_tny_account_new_for_local_folders (ModestAccountMgr *account_mgr, TnySessionCamel *session,
685                                           const gchar* location_filepath)
686 {
687         TnyStoreAccount *tny_account;
688         CamelURL *url;
689         gchar *maildir, *url_string;
690         TnyConnectionPolicy *policy;
691
692         g_return_val_if_fail (account_mgr, NULL);
693         g_return_val_if_fail (session, NULL);
694         
695         /* Make sure that the directories exist: */
696         modest_init_local_folders (location_filepath);
697         
698         if (!location_filepath) {
699                 /* A NULL filepath means that this is the special local-folders maildir 
700                  * account: */
701                 tny_account = TNY_STORE_ACCOUNT (modest_tny_local_folders_account_new ());
702         }
703         else {
704                 /* Else, for instance, a per-account outbox maildir account: */
705                 tny_account = TNY_STORE_ACCOUNT (tny_camel_store_account_new ());
706         }
707                 
708         if (!tny_account) {
709                 g_printerr ("modest: %s: cannot create account for local folders. filepath=%s", 
710                         __FUNCTION__, location_filepath);
711                 return NULL;
712         }
713         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
714         
715         /* This path contains directories for each local folder.
716          * We have created them so that TnyCamelStoreAccount can find them 
717          * and report a folder for each directory: */
718         maildir = modest_local_folder_info_get_maildir_path (location_filepath);
719         url = camel_url_new ("maildir:", NULL);
720         camel_url_set_path (url, maildir);
721         /* Needed by tinymail's DBC assertions */
722         camel_url_set_host (url, "localhost");
723         url_string = camel_url_to_string (url, 0);
724         
725         tny_account_set_url_string (TNY_ACCOUNT(tny_account), url_string);
726 /*      printf("DEBUG: %s:\n  url=%s\n", __FUNCTION__, url_string); */
727
728         /* TODO: Use a more generic way of identifying memory card paths, 
729          * and of marking accounts as memory card accounts, maybe
730          * via a derived TnyCamelStoreAccount ? */
731         const gboolean is_mmc = 
732                 location_filepath && 
733                 (strcmp (location_filepath, g_getenv (MODEST_MMC1_VOLUMEPATH_ENV)) == 0);
734                 
735         /* The name of memory card locations will be updated asynchronously.
736          * This is just a default: */
737         const gchar *name = is_mmc ? _("Memory Card") : 
738                 MODEST_LOCAL_FOLDERS_DEFAULT_DISPLAY_NAME;
739         tny_account_set_name (TNY_ACCOUNT(tny_account), name); 
740         
741         /* Get the correct display name for memory cards, asynchronously: */
742         if (location_filepath) {
743                 GError *error = NULL;
744                 gchar *uri = g_filename_to_uri(location_filepath, NULL, &error);
745                 if (error) {
746                         g_warning ("%s: g_filename_to_uri(%s) failed: %s", __FUNCTION__, 
747                                 location_filepath, error->message);
748                         g_error_free (error);
749                         error = NULL;   
750                 } else if (uri) {
751                         /* Get the account name asynchronously:
752                          * This might not happen soon enough, so some UI code might 
753                          * need to call this again, specifying a callback.
754                          */
755                         modest_tny_account_get_mmc_account_name (tny_account, NULL, NULL);
756                                 
757                         g_free (uri);
758                         uri = NULL;
759                 }
760         }
761         
762         
763         const gchar* id = is_mmc ? MODEST_MMC_ACCOUNT_ID :
764                 MODEST_LOCAL_FOLDERS_ACCOUNT_ID;
765         tny_account_set_id (TNY_ACCOUNT(tny_account), id);
766         
767         tny_account_set_forget_pass_func (TNY_ACCOUNT(tny_account), forget_pass_dummy);
768         tny_account_set_pass_func (TNY_ACCOUNT(tny_account), get_pass_dummy);
769
770         policy = modest_default_connection_policy_new ();
771         tny_account_set_connection_policy (TNY_ACCOUNT (tny_account), policy);
772         g_object_unref (policy);
773
774         modest_tny_account_set_parent_modest_account_name_for_server_account (
775                 TNY_ACCOUNT (tny_account), id);
776         
777         camel_url_free (url);
778         g_free (maildir);
779         g_free (url_string);
780
781         return TNY_ACCOUNT(tny_account);
782 }
783
784
785 TnyAccount*
786 modest_tny_account_new_for_per_account_local_outbox_folder (ModestAccountMgr *account_mgr,
787                                                             const gchar* account_name,
788                                                             TnySessionCamel *session)
789 {
790         TnyConnectionPolicy *policy;
791         TnyStoreAccount *tny_account;
792        
793         g_return_val_if_fail (account_mgr, NULL);
794         g_return_val_if_fail (account_name, NULL);
795         g_return_val_if_fail (session, NULL);
796
797         /* Notice that we create a ModestTnyOutboxAccount here, 
798          * instead of just a TnyCamelStoreAccount,
799          * so that we can later identify this as a special account for internal use only.
800          */
801         tny_account = TNY_STORE_ACCOUNT (modest_tny_outbox_account_new ());
802
803         if (!tny_account) {
804                 g_printerr ("modest: cannot create account for per-account local outbox folder.");
805                 return NULL;
806         }
807         
808         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
809         
810         /* Make sure that the paths exists on-disk so that TnyCamelStoreAccount can 
811          * find it to create a TnyFolder for it: */
812         gchar *folder_dir = modest_per_account_local_outbox_folder_info_get_maildir_path_to_outbox_folder (account_name); 
813         modest_init_one_local_folder(folder_dir);
814         g_free (folder_dir);
815         folder_dir = NULL;
816
817         /* This path should contain just one directory - "outbox": */
818         gchar *maildir = 
819                 modest_per_account_local_outbox_folder_info_get_maildir_path (account_name);
820                         
821         CamelURL *url = camel_url_new ("maildir:", NULL);
822         camel_url_set_path (url, maildir);
823         g_free (maildir);
824         
825         /* Needed by tinymail's DBC assertions */
826         camel_url_set_host (url, "localhost");
827         gchar *url_string = camel_url_to_string (url, 0);
828         camel_url_free (url);
829         
830         tny_account_set_url_string (TNY_ACCOUNT(tny_account), url_string);
831 /*      printf("DEBUG: %s:\n  url=%s\n", __FUNCTION__, url_string); */
832         g_free (url_string);
833
834         /* This text should never been seen,
835          * because the per-account outbox accounts are not seen directly by the user.
836          * Their folders are merged and shown as one folder. */ 
837         tny_account_set_name (TNY_ACCOUNT(tny_account), "Per-Account Outbox"); 
838         
839         gchar *account_id = g_strdup_printf (
840                 MODEST_PER_ACCOUNT_LOCAL_OUTBOX_FOLDER_ACCOUNT_ID_PREFIX "%s", 
841                 account_name);
842         tny_account_set_id (TNY_ACCOUNT(tny_account), account_id);
843         g_free (account_id);
844         
845         tny_account_set_forget_pass_func (TNY_ACCOUNT(tny_account), forget_pass_dummy);
846         tny_account_set_pass_func (TNY_ACCOUNT(tny_account), get_pass_dummy);
847
848         policy = modest_default_connection_policy_new ();
849         tny_account_set_connection_policy (TNY_ACCOUNT (tny_account), policy);
850         g_object_unref (policy);
851
852         /* Make this think that it belongs to the modest local-folders parent account: */
853         modest_tny_account_set_parent_modest_account_name_for_server_account (
854                 TNY_ACCOUNT (tny_account), MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
855
856         return TNY_ACCOUNT(tny_account);
857 }
858
859
860
861 typedef struct _RecurseFoldersAsyncHelper {
862         ModestFolderStats stats;
863         guint pending_calls;
864         GetFolderStatsCallback callback;
865         GetFolderStatsCallback status_callback;
866         gpointer user_data;
867 } RecurseFoldersAsyncHelper;
868
869 static void 
870 recurse_folders_async_cb (TnyFolderStore *folder_store, 
871                           gboolean canceled,
872                           TnyList *list, 
873                           GError *err, 
874                           gpointer user_data)
875 {
876         RecurseFoldersAsyncHelper *helper;
877         TnyIterator *iter;
878
879         helper = (RecurseFoldersAsyncHelper *) user_data;
880
881         /* A goto just to avoid an indentation level */
882         if (err || canceled)
883                 goto next_folder;
884
885         /* Retrieve children */
886         iter = tny_list_create_iterator (list);
887         while (!tny_iterator_is_done (iter)) {
888                 TnyList *folders = NULL;
889                 TnyFolderStore *folder = NULL;
890
891                 folders = tny_simple_list_new ();
892                 folder = (TnyFolderStore*) tny_iterator_get_current (iter);
893         
894                 /* Add pending call */
895                 helper->pending_calls++;
896                 helper->stats.folders++;
897                 if (TNY_IS_FOLDER (folder)) {
898                         helper->stats.msg_count += tny_folder_get_all_count (TNY_FOLDER (folder));
899                         helper->stats.local_size += tny_folder_get_local_size (TNY_FOLDER (folder));
900                 }
901
902                 /* notify */
903                 if (helper->status_callback)
904                         helper->status_callback (helper->stats, helper->user_data);
905
906                 /* Avoid the outbox */
907                 if (!TNY_IS_MERGE_FOLDER (folder) && 
908                     (TNY_IS_FOLDER (folder) && 
909                      tny_folder_get_folder_type (TNY_FOLDER (folder)) != TNY_FOLDER_TYPE_OUTBOX))
910                         tny_folder_store_get_folders_async (folder, folders, NULL, FALSE,
911                                                             recurse_folders_async_cb, 
912                                                             NULL, helper);
913                 g_object_unref (folders);
914                 g_object_unref (G_OBJECT (folder));
915                 
916                 tny_iterator_next (iter);
917         }
918         g_object_unref (G_OBJECT (iter));
919
920 next_folder:
921         /* Remove my own pending call */
922         helper->pending_calls--;
923
924         /* This means that we have all the folders */
925         if (helper->pending_calls == 0) {
926                 /* notify */
927                 if (helper->callback)
928                         helper->callback (helper->stats, helper->user_data);
929
930                 /* Free resources */
931                 g_slice_free (RecurseFoldersAsyncHelper, helper);
932         }
933 }
934
935 void
936 modest_tny_folder_store_get_folder_stats (TnyFolderStore *self,
937                                           GetFolderStatsCallback callback,
938                                           GetFolderStatsCallback status_callback,
939                                           gpointer user_data)
940 {
941         RecurseFoldersAsyncHelper *helper;
942         TnyList *folders;
943
944         g_return_if_fail (TNY_IS_FOLDER_STORE (self));
945
946         /* Create helper */
947         helper = g_slice_new0 (RecurseFoldersAsyncHelper);
948         helper->pending_calls = 1;
949         helper->callback = callback;
950         helper->status_callback = status_callback;
951         helper->user_data = user_data;
952
953         if (TNY_IS_FOLDER (self)) {
954                 helper->stats.msg_count = tny_folder_get_all_count (TNY_FOLDER (self));
955                 helper->stats.local_size = tny_folder_get_local_size (TNY_FOLDER (self));
956         }
957
958         folders = tny_simple_list_new ();
959         tny_folder_store_get_folders_async (TNY_FOLDER_STORE (self),
960                                             folders, NULL, FALSE,
961                                             recurse_folders_async_cb, 
962                                             NULL, helper);
963         g_object_unref (folders);
964 }
965
966 const gchar* 
967 modest_tny_account_get_parent_modest_account_name_for_server_account (TnyAccount *self)
968 {
969         return (const gchar *)g_object_get_data (G_OBJECT (self), "modest_account");
970 }
971
972 void 
973 modest_tny_account_set_parent_modest_account_name_for_server_account (TnyAccount *self, 
974                                                                       const gchar* parent_modest_account_name)
975 {
976         g_object_set_data_full (G_OBJECT(self), "modest_account",
977                                 (gpointer) g_strdup (parent_modest_account_name), g_free);
978 }
979
980 gboolean
981 modest_tny_account_is_virtual_local_folders (TnyAccount *self)
982 {
983         /* We should make this more sophisticated if we ever use ModestTnyLocalFoldersAccount 
984          * for anything else. */
985         return MODEST_IS_TNY_LOCAL_FOLDERS_ACCOUNT (self);
986 }
987
988
989 gboolean
990 modest_tny_account_is_memory_card_account (TnyAccount *self)
991 {
992         const gchar* account_id = NULL;
993
994         g_return_val_if_fail (TNY_ACCOUNT (self), FALSE);
995
996         if (!self)
997                 return FALSE;
998
999         account_id = tny_account_get_id (self);
1000
1001         if (!account_id)
1002                 return FALSE;
1003         else    
1004                 return (strcmp (account_id, MODEST_MMC_ACCOUNT_ID) == 0);
1005 }
1006
1007 gboolean 
1008 modest_tny_folder_store_is_remote (TnyFolderStore *folder_store)
1009 {
1010         TnyAccount *account = NULL;
1011         gboolean result = TRUE;
1012
1013         g_return_val_if_fail(TNY_IS_FOLDER_STORE(folder_store), FALSE);
1014
1015         if (TNY_IS_FOLDER (folder_store)) {
1016                 /* Get the folder's parent account: */
1017                 account = tny_folder_get_account(TNY_FOLDER(folder_store));
1018         } else if (TNY_IS_ACCOUNT (folder_store)) {
1019                 account = TNY_ACCOUNT(folder_store);
1020                 g_object_ref(account);
1021         }
1022
1023         if (account != NULL) {
1024                 if (tny_account_get_account_type (account) == TNY_ACCOUNT_TYPE_STORE) {
1025                         ModestProtocolType proto_type;
1026                         const gchar *tag;
1027                         ModestProtocolRegistry *registry;
1028
1029                         proto_type = modest_tny_account_get_protocol_type (account);
1030                         registry = modest_runtime_get_protocol_registry ();
1031                         tag = MODEST_PROTOCOL_REGISTRY_REMOTE_STORE_PROTOCOLS;
1032                         if (modest_protocol_registry_protocol_type_has_tag (registry, 
1033                                                                             proto_type,
1034                                                                             tag)) {
1035                                 result = TRUE;
1036                         } else {
1037                                 result = FALSE;
1038                         }
1039                 }
1040                 g_object_unref (account);
1041         } else {
1042                 result = FALSE;
1043         }
1044
1045         return result;
1046 }
1047
1048 ModestProtocolType 
1049 modest_tny_account_get_protocol_type (TnyAccount *self)
1050 {
1051         ModestProtocolRegistry *protocol_registry;
1052         ModestProtocol *protocol;
1053         ModestProtocolType result;
1054
1055         protocol_registry = modest_runtime_get_protocol_registry ();
1056         protocol = modest_protocol_registry_get_protocol_by_name (protocol_registry,
1057                                                                   MODEST_PROTOCOL_REGISTRY_TRANSPORT_STORE_PROTOCOLS,
1058                                                                   tny_account_get_proto (self));
1059         result = protocol?modest_protocol_get_type_id (protocol):MODEST_PROTOCOL_REGISTRY_TYPE_INVALID;
1060
1061         return result;
1062 }