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