Reconnect and forget password when changing account settings
[modest] / src / modest-tny-account.c
1 /* Copyright (c) 2006, Nokia Corporation
2  * All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  * * Redistributions of source code must retain the above copyright
9  *   notice, this list of conditions and the following disclaimer.
10  * * Redistributions in binary form must reproduce the above copyright
11  *   notice, this list of conditions and the following disclaimer in the
12  *   documentation and/or other materials provided with the distribution.
13  * * Neither the name of the Nokia Corporation nor the names of its
14  *   contributors may be used to endorse or promote products derived from
15  *   this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
18  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <modest-platform.h>
31 #include <modest-tny-platform-factory.h>
32 #include <modest-tny-account.h>
33 #include <modest-tny-account-store.h>
34 #include <modest-tny-local-folders-account.h>
35 #include <modest-runtime.h>
36 #include <tny-simple-list.h>
37 #include <modest-tny-folder.h>
38 #include <modest-tny-outbox-account.h>
39 #include <modest-account-mgr-helpers.h>
40 #include <modest-init.h>
41 #include <tny-camel-transport-account.h>
42 #include <tny-camel-imap-store-account.h>
43 #include <tny-camel-pop-store-account.h>
44 #include <tny-folder-stats.h>
45 #include <string.h>
46 #ifdef MODEST_HAVE_HILDON0_WIDGETS
47 #include <hildon-widgets/hildon-file-system-info.h>
48 #else
49 #include <hildon/hildon-file-system-info.h>
50 #endif
51
52 TnyFolder *
53 modest_tny_account_get_special_folder (TnyAccount *account,
54                                        TnyFolderType special_type)
55 {
56         TnyList *folders;
57         TnyIterator *iter;
58         TnyFolder *special_folder = NULL;
59
60         
61         g_return_val_if_fail (account, NULL);
62         g_return_val_if_fail (0 <= special_type && special_type < TNY_FOLDER_TYPE_NUM,
63                               NULL);
64         
65         TnyAccount *local_account  = NULL;
66
67         /* The accounts have already been instantiated by 
68          * modest_tny_account_store_get_accounts(), which is the 
69          * TnyAccountStore::get_accounts_func() implementation,
70          * so we just get them here.
71          */
72          
73         /* Per-account outbox folders are each in their own on-disk directory: */
74         if (special_type == TNY_FOLDER_TYPE_OUTBOX) {
75                 const gchar *modest_account_name = 
76                         modest_tny_account_get_parent_modest_account_name_for_server_account (account);
77                 
78                 if (modest_account_name) {
79                         gchar *account_id = g_strdup_printf (
80                                 MODEST_PER_ACCOUNT_LOCAL_OUTBOX_FOLDER_ACCOUNT_ID_PREFIX "%s", 
81                                 modest_account_name);
82                         
83                         local_account = modest_tny_account_store_get_tny_account_by (modest_runtime_get_account_store(),
84                                                                                      MODEST_TNY_ACCOUNT_STORE_QUERY_ID,
85                                                                                      account_id);
86                         if (!local_account) {
87                                 g_printerr ("modest: %s: modest_tny_account_store_get_tny_account_by(ID) returned NULL for %s\n", __FUNCTION__, account_id);
88                         return NULL;
89                         }
90                 
91                         g_free (account_id);
92                 } else {
93                         g_warning ("%s: modest_account_name was NULL.", __FUNCTION__);
94                 }
95         } else {
96                 /* Other local folders are all in one on-disk directory: */
97                 local_account = modest_tny_account_store_get_tny_account_by (modest_runtime_get_account_store(),
98                                                                              MODEST_TNY_ACCOUNT_STORE_QUERY_ID,
99                                                                              MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
100         }
101         
102         if (!local_account) {
103                 g_printerr ("modest: cannot get local account\n");
104                 return NULL;
105         }
106
107         folders = TNY_LIST (tny_simple_list_new ());
108
109         /* There is no need to do this _async, as these are local folders. */
110         /* TODO: However, this seems to fail sometimes when the network is busy, 
111          * returning an empty list. murrayc. */ 
112         GError *error = NULL;
113         tny_folder_store_get_folders (TNY_FOLDER_STORE (local_account),
114                                       folders, NULL, &error);
115         if (error) {
116                 g_warning ("%s: tny_folder_store_get_folders() failed:\n  error=%s\n", 
117                         __FUNCTION__, error->message);
118         }
119                                       
120         if (tny_list_get_length (folders) == 0) {
121                 gchar* url_string = tny_account_get_url_string (local_account);
122                 g_printerr ("modest: %s: tny_folder_store_get_folders() returned an empty list for account with URL '%s'\n", 
123                         __FUNCTION__, url_string);
124                 g_free (url_string);
125         }
126         
127         iter = tny_list_create_iterator (folders);
128
129         while (!tny_iterator_is_done (iter)) {
130                 TnyFolder *folder =
131                         TNY_FOLDER (tny_iterator_get_current (iter));
132                 if (folder) {
133                         if (modest_tny_folder_get_local_or_mmc_folder_type (folder) == special_type) {
134                                 special_folder = folder;
135                                 break; /* Leaving a ref for the special_folder return value. */
136                         }
137                 
138                         g_object_unref (G_OBJECT(folder));
139                 }
140
141                 tny_iterator_next (iter);
142         }
143         
144         g_object_unref (G_OBJECT (folders));
145         g_object_unref (G_OBJECT (iter));
146         g_object_unref (G_OBJECT (local_account));
147
148         /*
149         if (!special_folder) {
150                 g_warning ("%s: Returning NULL.", __FUNCTION__);        
151         }
152         */
153         
154         return special_folder;
155 }
156
157 static void
158 on_connection_status_changed (TnyAccount *account, TnyConnectionStatus status, gpointer user_data)
159 {
160         printf ("DEBUG: %s: status=%d\n", __FUNCTION__, status);
161         
162         if (status == TNY_CONNECTION_STATUS_DISCONNECTED) {
163                 /* A tinymail network operation failed, and tinymail then noticed that 
164                  * the account is offline, because our TnyDevice is offline,
165                  * because libconic says we are offline.
166                  * So ask the user to go online again.
167                  * 
168                  * Note that this signal will not be emitted if the account was offline 
169                  * when the network operation was first attempted. For those cases, 
170                  * the application must do its own explicit checks.
171                  *
172                  * We make sure that this UI is shown in the main thread, to avoid races,
173                  * because tinymail does not guarantee that this signal handler will be called 
174                  * in the main thread.
175                  */
176                 /* TODO: Commented out, because this causes hangs, probably related to 
177                  * our use of mainloops:
178                  * modest_platform_connect_and_wait (NULL);
179                  */
180         } else if (status == TNY_CONNECTION_STATUS_CONNECTED_BROKEN) {
181                 printf ("DEBUG: %s: Connection broken. Forcing TnyDevice offline.\n", 
182                         __FUNCTION__);
183                         
184                 /* Something went wrong during some network operation.
185                  * Stop trying to use the network now,
186                  * by forcing accounts into offline mode:
187                  * 
188                  * When libconic reconnects, it will set the device back online again,
189                  * regardless of it being forced offline before.
190                  */
191                 /* TODO: Find out when this is falsely being emitted. */
192                 printf ("  DEBUG: %s: Not forcing offline because tinymail is sometimes reporting false connection breaks.\n", 
193                         __FUNCTION__);
194                 /*
195                 TnyDevice *device = modest_runtime_get_device ();
196                 tny_device_force_offline (device);
197                 */
198         }
199 }
200
201
202
203 /**
204  * create_tny_account:
205  * @account_mgr: a valid account mgr instance
206  * @session: A valid TnySessionCamel instance.
207  * @account_data: the server account for which to create a corresponding tny account
208  * 
209  * get a tnyaccount corresponding to the server_accounts (store or transport) for this account.
210  * NOTE: this function does not set the camel session or the get/forget password functions
211  * 
212  * Returns: a new TnyAccount or NULL in case of error.
213  */
214 static TnyAccount*
215 create_tny_account (ModestAccountMgr *account_mgr,
216                     TnySessionCamel *session,
217                     ModestServerAccountData *account_data)
218 {
219         g_return_val_if_fail (account_mgr, NULL);
220         g_return_val_if_fail (session, NULL);
221         g_return_val_if_fail (account_data, NULL);
222
223         /* sanity checks */
224         if (account_data->proto == MODEST_PROTOCOL_TRANSPORT_STORE_UNKNOWN) {
225                 g_printerr ("modest: '%s' does not provide a protocol\n",
226                             account_data->account_name);
227                 return NULL;
228         }
229
230         TnyAccount *tny_account = NULL;
231         
232         switch (account_data->proto) {
233         case MODEST_PROTOCOL_TRANSPORT_SENDMAIL:
234         case MODEST_PROTOCOL_TRANSPORT_SMTP:
235                 tny_account = TNY_ACCOUNT(tny_camel_transport_account_new ()); break;
236         case MODEST_PROTOCOL_STORE_POP:
237                 tny_account = TNY_ACCOUNT(tny_camel_pop_store_account_new ()); break;
238         case MODEST_PROTOCOL_STORE_IMAP:
239                 tny_account = TNY_ACCOUNT(tny_camel_imap_store_account_new ()); break;
240         case MODEST_PROTOCOL_STORE_MAILDIR:
241         case MODEST_PROTOCOL_STORE_MBOX:
242                 /* Note that this is not where we create the special local folders account.
243                  * That happens in modest_tny_account_new_for_local_folders() instead.
244                  */
245                 tny_account = TNY_ACCOUNT(tny_camel_store_account_new()); break;
246         default:
247                 g_return_val_if_reached (NULL);
248         }
249         if (!tny_account) {
250                 g_printerr ("modest: could not create tny account for '%s'\n",
251                             account_data->account_name);
252                 return NULL;
253         }
254         tny_account_set_id (tny_account, account_data->account_name);
255
256         /* This must be set quite early, or other set() functions will fail. */
257         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT (tny_account), session);
258     
259         /* Handle connection requests:
260          * This (badly-named) signal will be called when we try to use an offline account. */
261         g_signal_connect (G_OBJECT (tny_account), "connection-status-changed",
262                         G_CALLBACK (on_connection_status_changed), NULL);
263
264         /* Proto */
265         const gchar* proto_name =
266                 modest_protocol_info_get_transport_store_protocol_name(account_data->proto);
267         tny_account_set_proto (tny_account, proto_name);
268
269         return tny_account;
270 }
271
272
273
274 /* Camel options: */
275
276 /* These seem to be listed in 
277  * libtinymail-camel/camel-lite/camel/providers/imap/camel-imap-store.c 
278  */
279 #define MODEST_ACCOUNT_OPTION_SSL "use_ssl"
280 #define MODEST_ACCOUNT_OPTION_SSL_NEVER "never"
281 /* This is a tinymail camel-lite specific option, 
282  * roughly equivalent to "always" in regular camel,
283  * which is appropriate for a generic "SSL" connection option: */
284 #define MODEST_ACCOUNT_OPTION_SSL_WRAPPED "wrapped"
285 /* Not used in our UI so far: */
286 #define MODEST_ACCOUNT_OPTION_SSL_WHEN_POSSIBLE "when-possible"
287 /* This is a tinymailcamel-lite specific option that is not in regular camel. */
288 #define MODEST_ACCOUNT_OPTION_SSL_TLS "tls"
289
290 /* These seem to be listed in 
291  * libtinymail-camel/camel-lite/camel/providers/imap/camel-imap-provider.c 
292  */
293 #define MODEST_ACCOUNT_OPTION_USE_LSUB "use_lsub" /* Show only subscribed folders */
294 #define MODEST_ACCOUNT_OPTION_CHECK_ALL "check_all" /* Check for new messages in all folders */
295
296 /* Posssible values for tny_account_set_secure_auth_mech().
297  * These might be camel-specific.
298  * Really, tinymail should use an enum.
299  * camel_sasl_authtype() seems to list some possible values.
300  */
301  
302 /* Note that evolution does not offer these for IMAP: */
303 #define MODEST_ACCOUNT_AUTH_PLAIN "PLAIN"
304 #define MODEST_ACCOUNT_AUTH_ANONYMOUS "ANONYMOUS"
305
306 /* Caeml's IMAP uses NULL instead for "Password".
307  * Also, not that Evolution offers "Password" for IMAP, but "Login" for SMTP.*/
308 #define MODEST_ACCOUNT_AUTH_PASSWORD "LOGIN" 
309 #define MODEST_ACCOUNT_AUTH_CRAMMD5 "CRAM-MD5"
310
311                 
312 /**
313  * update_tny_account:
314  * @account_mgr: a valid account mgr instance
315  * @account_data: the server account for which to create a corresponding tny account
316  * 
317  * get a tnyaccount corresponding to the server_accounts (store or transport) for this account.
318  * NOTE: this function does not set the camel session or the get/forget password functions
319  * 
320  * Returns: a new TnyAccount or NULL in case of error.
321  */
322 static gboolean
323 update_tny_account (TnyAccount *tny_account, ModestAccountMgr *account_mgr,
324                     ModestServerAccountData *account_data)
325 {
326         gchar *url = NULL;
327         
328         g_return_val_if_fail (account_mgr, FALSE);
329         g_return_val_if_fail (account_data, FALSE);
330         g_return_val_if_fail (tny_account, FALSE);
331
332         tny_account_set_id (tny_account, account_data->account_name);
333                
334         /* mbox and maildir accounts use a URI instead of the rest:
335          * Note that this is not where we create the special local folders account.
336          * We do that in modest_tny_account_new_for_local_folders() instead. */
337         if (account_data->uri)  
338                 tny_account_set_url_string (TNY_ACCOUNT(tny_account), account_data->uri);
339         else {
340                 /* Set camel-specific options: */
341                 
342                 /* Enable secure connection settings: */
343                 const gchar* option_security = NULL;
344                 switch (account_data->security) {
345                 case MODEST_PROTOCOL_CONNECTION_NORMAL:
346                         option_security = MODEST_ACCOUNT_OPTION_SSL "=" MODEST_ACCOUNT_OPTION_SSL_NEVER;
347                         break;
348                 case MODEST_PROTOCOL_CONNECTION_SSL:
349                         /* Apparently, use of "IMAPS" (specified in our UI spec), implies 
350                          * use of the "wrapped" option: */
351                         option_security = MODEST_ACCOUNT_OPTION_SSL "=" MODEST_ACCOUNT_OPTION_SSL_WRAPPED;
352                         break;
353                 case MODEST_PROTOCOL_CONNECTION_TLS:
354                         option_security = MODEST_ACCOUNT_OPTION_SSL "=" MODEST_ACCOUNT_OPTION_SSL_TLS;
355                         break;
356                 case MODEST_PROTOCOL_CONNECTION_TLS_OP:
357                         /* This is not actually in our UI: */
358                         option_security = MODEST_ACCOUNT_OPTION_SSL "=" MODEST_ACCOUNT_OPTION_SSL_WHEN_POSSIBLE;
359                         break;
360                 default:
361                         break;
362                 }
363                 
364                 if(option_security)
365                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
366                                                       option_security);
367                 
368                 /* Secure authentication: */
369
370                 const gchar* auth_mech_name = NULL;
371                 switch (account_data->secure_auth) {
372                 case MODEST_PROTOCOL_AUTH_NONE:
373                         /* IMAP and POP need at least a password,
374                          * which camel uses if we specify NULL.
375                          * This setting should never happen anyway. */
376                         if (account_data->proto == MODEST_PROTOCOL_STORE_IMAP ||
377                             account_data->proto == MODEST_PROTOCOL_STORE_POP)
378                                 auth_mech_name = NULL;
379                         else if (account_data->proto == MODEST_PROTOCOL_TRANSPORT_SMTP)
380                                 auth_mech_name = MODEST_ACCOUNT_AUTH_ANONYMOUS;
381                         else
382                                 auth_mech_name = MODEST_ACCOUNT_AUTH_PLAIN;
383                         break;
384                         
385                 case MODEST_PROTOCOL_AUTH_PASSWORD:
386                         /* Camel use a password for IMAP or POP if we specify NULL,
387                          * For IMAP, at least it will report an error if we use "Password", "Login" or "Plain".
388                          * (POP is know to report an error for Login too. Probably Password and Plain too.) */
389                         if (account_data->proto == MODEST_PROTOCOL_STORE_IMAP)
390                                 auth_mech_name = NULL;
391                         else if (account_data->proto == MODEST_PROTOCOL_STORE_POP)
392                                 auth_mech_name = NULL;
393                         else
394                                 auth_mech_name = MODEST_ACCOUNT_AUTH_PASSWORD;
395                         break;
396                         
397                 case MODEST_PROTOCOL_AUTH_CRAMMD5:
398                         auth_mech_name = MODEST_ACCOUNT_AUTH_CRAMMD5;
399                         break;
400                         
401                 default:
402                         g_warning ("%s: Unhandled secure authentication setting %d for "
403                                 "account=%s (%s)", __FUNCTION__, account_data->secure_auth,
404                                    account_data->account_name, account_data->hostname);
405                         break;
406                 }
407                 
408                 if(auth_mech_name) 
409                         tny_account_set_secure_auth_mech (tny_account, auth_mech_name);
410                 
411                 if (modest_protocol_info_protocol_is_store(account_data->proto) && 
412                         (account_data->proto == MODEST_PROTOCOL_STORE_IMAP) ) {
413                         /* Other connection options, needed for IMAP. */
414                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
415                                                       MODEST_ACCOUNT_OPTION_USE_LSUB);
416                         tny_camel_account_add_option (TNY_CAMEL_ACCOUNT (tny_account),
417                                                       MODEST_ACCOUNT_OPTION_CHECK_ALL);
418                 }
419                 
420                 if (account_data->username) 
421                         tny_account_set_user (tny_account, account_data->username);
422                 if (account_data->hostname)
423                         tny_account_set_hostname (tny_account, account_data->hostname);
424                  
425                 /* Set the port: */
426                 if (account_data->port)
427                         tny_account_set_port (tny_account, account_data->port);
428         }
429
430         /* FIXME: for debugging. 
431          * Let's keep this because it is very useful for debugging. */
432         url = tny_account_get_url_string (TNY_ACCOUNT(tny_account));
433         g_debug ("%s:\n  account-url: %s\n", __FUNCTION__, url);
434
435         g_free (url);
436         return TRUE;
437 }
438
439 TnyAccount*
440 modest_tny_account_new_from_server_account_name (ModestAccountMgr *account_mgr,
441                                                  TnySessionCamel *session,
442                                                  const gchar *server_account_name)
443 {
444         ModestServerAccountData *account_data;
445         TnyAccount *tny_account;
446         
447         g_return_val_if_fail (session, NULL);
448         g_return_val_if_fail (server_account_name, NULL);
449
450         account_data =  modest_account_mgr_get_server_account_data (account_mgr, 
451                                                                     server_account_name);
452         if (!account_data)
453                 return NULL;
454
455         tny_account = create_tny_account (account_mgr, session, account_data);
456         if (!tny_account)
457                 g_warning ("%s: failed to create tny_account", __FUNCTION__);
458         else if (!update_tny_account (tny_account, account_mgr, account_data))
459                 g_warning ("%s: failed to initialize tny_account", __FUNCTION__);
460         
461         modest_account_mgr_free_server_account_data (account_mgr, account_data);
462         
463         return tny_account;
464 }
465
466
467 #if 0
468 gboolean
469 modest_tny_account_update_from_server_account_name (TnyAccount *tny_account,
470                                                     ModestAccountMgr *account_mgr,
471                                                     const gchar *server_account_name)
472 {
473         ModestServerAccountData *account_data;
474         gboolean valid_account_type;
475         
476         g_return_val_if_fail (tny_account, FALSE);
477         g_return_val_if_fail (server_account_name, FALSE);
478         
479         account_data =  modest_account_mgr_get_server_account_data (account_mgr, 
480                                                                     server_account_name);
481         if (!account_data) {
482                 g_warning ("%s: failed to get server account data for %s",
483                            __FUNCTION__, server_account_name);
484                 return FALSE;
485         }
486
487         valid_account_type = FALSE;
488
489         /* you cannot change the protocol type of an existing account;
490          * so double check we don't even try
491          */
492         switch (account_data->proto) {
493         case MODEST_PROTOCOL_TRANSPORT_SENDMAIL:
494         case MODEST_PROTOCOL_TRANSPORT_SMTP:
495                 if (!TNY_IS_CAMEL_TRANSPORT_ACCOUNT(tny_account))
496                         g_warning ("%s: expecting transport account", __FUNCTION__);
497                 else
498                         valid_account_type = TRUE;
499                 break;
500         case MODEST_PROTOCOL_STORE_POP:
501                 if (!TNY_IS_CAMEL_POP_STORE_ACCOUNT(tny_account))
502                         g_warning ("%s: expecting pop account", __FUNCTION__);
503                 else
504                         valid_account_type = TRUE;
505                 break;
506         case MODEST_PROTOCOL_STORE_IMAP:
507                 if (!TNY_IS_CAMEL_IMAP_STORE_ACCOUNT(tny_account))
508                         g_warning ("%s: expecting imap account", __FUNCTION__);
509                 else
510                         valid_account_type = TRUE;
511                 break;
512         case MODEST_PROTOCOL_STORE_MAILDIR:
513         case MODEST_PROTOCOL_STORE_MBOX:
514                 if (!TNY_IS_CAMEL_STORE_ACCOUNT(tny_account))
515                         g_warning ("%s: expecting store account", __FUNCTION__);
516                 else
517                         valid_account_type = TRUE;
518                 break;
519         default:
520                 g_warning ("invalid account type");
521         }
522
523         if (!valid_account_type) {
524                 g_warning ("%s: protocol type cannot be changed", __FUNCTION__);
525                 modest_account_mgr_free_server_account_data (account_mgr, account_data);
526                 return FALSE;
527         }
528         
529         if (!update_tny_account (tny_account, account_mgr, account_data)) {
530                 g_warning ("%s: failed to update account", __FUNCTION__);
531                 modest_account_mgr_free_server_account_data (account_mgr, account_data);
532                 return FALSE;
533         }
534
535         modest_account_mgr_free_server_account_data (account_mgr, account_data);
536         return TRUE;
537 }
538 #endif
539
540
541
542
543 /* we need these dummy functions, or tinymail will complain */
544 static gchar*
545 get_pass_dummy (TnyAccount *account, const gchar *prompt, gboolean *cancel)
546 {
547         return NULL;
548 }
549 static void
550 forget_pass_dummy (TnyAccount *account)
551 {
552         /* intentionally left blank */
553 }
554
555
556 static void
557 set_online_callback (TnyCamelAccount *account, gboolean canceled, GError *err, gpointer user_data)
558 {
559         /* MODEST TODO: Show a real error message here, this is a significant error!
560          * Perhaps show the account's settings dialog again?! Reconnecting after 
561          * changing the settings of an account failed in this situation. */
562
563        if (err && !canceled)
564                g_warning ("err: %s", err->message);
565 }
566
567 gboolean
568 modest_tny_account_update_from_account (TnyAccount *tny_account, ModestAccountMgr *account_mgr,
569                                         const gchar *account_name, TnyAccountType type) 
570 {
571         ModestAccountData *account_data = NULL;
572         ModestServerAccountData *server_data = NULL;
573         TnyConnectionStatus  conn_status;
574         
575         g_return_val_if_fail (tny_account, FALSE);
576         g_return_val_if_fail (account_mgr, FALSE);
577         g_return_val_if_fail (account_name, FALSE);
578         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || type == TNY_ACCOUNT_TYPE_TRANSPORT,
579                               FALSE);
580
581         account_data = modest_account_mgr_get_account_data (account_mgr, account_name);
582         if (!account_data) {
583                 g_printerr ("modest: %s: cannot get account data for account %s\n",
584                             __FUNCTION__, account_name);
585                 return FALSE;
586         }
587
588         if (type == TNY_ACCOUNT_TYPE_STORE && account_data->store_account)
589                 server_data = account_data->store_account;
590         else if (type == TNY_ACCOUNT_TYPE_TRANSPORT && account_data->transport_account)
591                 server_data = account_data->transport_account;
592         if (!server_data) {
593                 g_printerr ("modest: no %s account defined for '%s'\n",
594                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
595                             account_data->display_name);
596                 modest_account_mgr_free_account_data (account_mgr, account_data);
597                 return FALSE;
598         }
599         
600         update_tny_account (tny_account, account_mgr, server_data);
601                 
602         /* This name is what shows up in the folder view -- so for some POP/IMAP/... server
603          * account, we set its name to the account of which it is part. */
604  
605         if (account_data->display_name)
606                 tny_account_set_name (tny_account, account_data->display_name);
607
608         modest_account_mgr_free_account_data (account_mgr, account_data);
609
610         /* If the account was online, reconnect to apply the changes */
611         conn_status = tny_account_get_connection_status (tny_account);
612         if (conn_status != TNY_CONNECTION_STATUS_DISCONNECTED) {
613                 TnyAccountStore *account_store = NULL;
614
615                 /* The callback will have an error for you if the reconnect
616                  * failed. Please handle it (this is TODO). */
617
618                 account_store = TNY_ACCOUNT_STORE(g_object_get_data (G_OBJECT(tny_account),
619                                                              "account_store"));
620
621                 if (account_store) {
622                         modest_tny_account_store_forget_already_asked (MODEST_TNY_ACCOUNT_STORE (account_store), 
623                                                                 tny_account);
624                 }
625
626                 tny_camel_account_set_online (TNY_CAMEL_ACCOUNT(tny_account), TRUE, 
627                         set_online_callback,  "online");
628         }
629
630         return TRUE;
631 }
632
633
634
635 TnyAccount*
636 modest_tny_account_new_from_account (ModestAccountMgr *account_mgr,
637                                      const gchar *account_name,
638                                      TnyAccountType type,
639                                      TnySessionCamel *session,
640                                      TnyGetPassFunc get_pass_func,
641                                      TnyForgetPassFunc forget_pass_func) 
642 {
643         TnyAccount *tny_account = NULL;
644         ModestAccountData *account_data = NULL;
645         ModestServerAccountData *server_data = NULL;
646
647         g_return_val_if_fail (account_mgr, NULL);
648         g_return_val_if_fail (account_name, NULL);
649         g_return_val_if_fail (session, NULL);
650         g_return_val_if_fail (type == TNY_ACCOUNT_TYPE_STORE || type == TNY_ACCOUNT_TYPE_TRANSPORT,
651                               NULL);
652
653         account_data = modest_account_mgr_get_account_data (account_mgr, account_name);
654         if (!account_data) {
655                 g_printerr ("modest: %s: cannot get account data for account %s\n",
656                             __FUNCTION__, account_name);
657                 return NULL;
658         }
659
660         if (type == TNY_ACCOUNT_TYPE_STORE && account_data->store_account)
661                 server_data = account_data->store_account;
662         else if (type == TNY_ACCOUNT_TYPE_TRANSPORT && account_data->transport_account)
663                 server_data = account_data->transport_account;
664         if (!server_data) {
665                 g_printerr ("modest: no %s account defined for '%s'\n",
666                             type == TNY_ACCOUNT_TYPE_STORE ? "store" : "transport",
667                             account_data->display_name);
668                 modest_account_mgr_free_account_data (account_mgr, account_data);
669                 return NULL;
670         }
671         
672         tny_account = create_tny_account (account_mgr,session, server_data);
673         if (!tny_account) { 
674                 g_printerr ("modest: failed to create tny account for %s (%s)\n",
675                             account_data->account_name, server_data->account_name);
676                 modest_account_mgr_free_account_data (account_mgr, account_data);
677                 return NULL;
678         } else
679                 update_tny_account (tny_account, account_mgr, server_data);
680                 
681         /* This name is what shows up in the folder view -- so for some POP/IMAP/... server
682          * account, we set its name to the account of which it is part. */
683  
684         if (account_data->display_name)
685                 tny_account_set_name (tny_account, account_data->display_name);
686
687         tny_account_set_forget_pass_func (tny_account,
688                                           forget_pass_func ? forget_pass_func : forget_pass_dummy);
689         tny_account_set_pass_func (tny_account,
690                                    get_pass_func ? get_pass_func: get_pass_dummy);
691         
692         modest_tny_account_set_parent_modest_account_name_for_server_account (tny_account,
693                                                                               account_name);
694         modest_account_mgr_free_account_data (account_mgr, account_data);
695
696         return tny_account;
697 }
698
699 typedef struct
700 {
701         TnyStoreAccount *account;
702         
703         ModestTnyAccountGetMmcAccountNameCallback callback;
704         gpointer user_data;
705 } GetMmcAccountNameData;
706
707
708
709
710 /* Gets the memory card name: */
711 static void 
712 on_modest_file_system_info(HildonFileSystemInfoHandle *handle,
713                              HildonFileSystemInfo *info,
714                              const GError *error, gpointer data)
715 {
716         GetMmcAccountNameData *callback_data = (GetMmcAccountNameData*)data;
717
718         if (error) {
719                 g_warning ("%s: error=%s", __FUNCTION__, error->message);
720         }
721         
722         TnyAccount *account = TNY_ACCOUNT (callback_data->account);
723         
724         const gchar *previous_display_name = NULL;
725         
726         const gchar *display_name = NULL;
727         if (!error && info) {
728                 display_name = hildon_file_system_info_get_display_name(info);
729                 previous_display_name = tny_account_get_name (account);
730         }
731                  
732         /* printf ("DEBUG: %s: display name=%s\n", __FUNCTION__,  display_name); */
733         if (display_name && previous_display_name && 
734                 (strcmp (display_name, previous_display_name) != 0)) {
735                 tny_account_set_name (account, display_name);
736         }
737                 
738         /* Inform the application that the name is now ready: */
739         if (callback_data->callback)
740                 (*(callback_data->callback)) (callback_data->account, 
741                         callback_data->user_data);
742         
743         g_object_unref (callback_data->account);
744         g_slice_free (GetMmcAccountNameData, callback_data);
745 }
746
747 void modest_tny_account_get_mmc_account_name (TnyStoreAccount* self, ModestTnyAccountGetMmcAccountNameCallback callback, gpointer user_data)
748 {
749         /* Just use the hard-coded path for the single memory card,
750          * rather than try to figure out the path to the specific card by 
751          * looking at the maildir URI:
752          */
753         const gchar *uri_real = MODEST_MCC1_VOLUMEPATH_URI;
754
755         /*
756         gchar* uri = tny_account_get_url_string (TNY_ACCOUNT (self));
757         if (!uri)
758                 return;
759
760         TODO: This gets the name of the folder, but we want the name of the volume.
761         gchar *uri_real = NULL;
762         const gchar* prefix = "maildir://localhost/";
763         if ((strstr (uri, prefix) == uri) && (strlen(uri) > strlen(prefix)) )
764                 uri_real = g_strconcat ("file:///", uri + strlen (prefix), NULL);
765         */
766
767         if (uri_real) {
768                 //This is freed in the callback:
769                 GetMmcAccountNameData * callback_data = g_slice_new0(GetMmcAccountNameData);
770                 callback_data->account = self;
771                 g_object_ref (callback_data->account); /* Unrefed when we destroy the struct. */
772                 callback_data->callback = callback;
773                 callback_data->user_data = user_data;
774                 
775                 /* TODO: gnome_vfs_volume_get_display_name() does not return 
776                  * the same string. But why not? Why does hildon needs its own 
777                  * function for this?
778                  */
779                 /* printf ("DEBUG: %s Calling hildon_file_system_info_async_new() with URI=%s\n", __FUNCTION__, uri_real); */
780                 hildon_file_system_info_async_new(uri_real, 
781                         on_modest_file_system_info, callback_data /* user_data */);
782
783                 /* g_free (uri_real); */
784         }
785
786         /* g_free (uri); */
787 }
788
789                                 
790
791 TnyAccount*
792 modest_tny_account_new_for_local_folders (ModestAccountMgr *account_mgr, TnySessionCamel *session,
793                                           const gchar* location_filepath)
794 {
795
796         
797         /* Make sure that the directories exist: */
798         modest_init_local_folders (location_filepath);
799
800         TnyStoreAccount *tny_account;
801         CamelURL *url;
802         gchar *maildir, *url_string;
803
804         g_return_val_if_fail (account_mgr, NULL);
805         g_return_val_if_fail (session, NULL);
806
807         
808         if (!location_filepath) {
809                 /* A NULL filepath means that this is the special local-folders maildir 
810                  * account: */
811                 tny_account = TNY_STORE_ACCOUNT (modest_tny_local_folders_account_new ());
812         }
813         else {
814                 /* Else, for instance, a per-account outbox maildir account: */
815                 tny_account = TNY_STORE_ACCOUNT (tny_camel_store_account_new ());
816         }
817                 
818         if (!tny_account) {
819                 g_printerr ("modest: %s: cannot create account for local folders. filepath=%s", 
820                         __FUNCTION__, location_filepath);
821                 return NULL;
822         }
823         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
824         
825         /* This path contains directories for each local folder.
826          * We have created them so that TnyCamelStoreAccount can find them 
827          * and report a folder for each directory: */
828         maildir = modest_local_folder_info_get_maildir_path (location_filepath);
829         url = camel_url_new ("maildir:", NULL);
830         camel_url_set_path (url, maildir);
831         /* Needed by tinymail's DBC assertions */
832         camel_url_set_host (url, "localhost");
833         url_string = camel_url_to_string (url, 0);
834         
835         tny_account_set_url_string (TNY_ACCOUNT(tny_account), url_string);
836 /*      printf("DEBUG: %s:\n  url=%s\n", __FUNCTION__, url_string); */
837
838         /* TODO: Use a more generic way of identifying memory card paths, 
839          * and of marking accounts as memory card accounts, maybe
840          * via a derived TnyCamelStoreAccount ? */
841         const gboolean is_mmc = 
842                 location_filepath && 
843                 (strcmp (location_filepath, MODEST_MCC1_VOLUMEPATH) == 0);
844                 
845         /* The name of memory card locations will be updated asynchronously.
846          * This is just a default: */
847         const gchar *name = is_mmc ? _("Memory Card") : 
848                 MODEST_LOCAL_FOLDERS_DEFAULT_DISPLAY_NAME;
849         tny_account_set_name (TNY_ACCOUNT(tny_account), name); 
850         
851         /* Get the correct display name for memory cards, asynchronously: */
852         if (location_filepath) {
853                 GError *error = NULL;
854                 gchar *uri = g_filename_to_uri(location_filepath, NULL, &error);
855                 if (error) {
856                         g_warning ("%s: g_filename_to_uri(%s) failed: %s", __FUNCTION__, 
857                                 location_filepath, error->message);
858                         g_error_free (error);
859                         error = NULL;   
860                 } else if (uri) {
861                         /* Get the account name asynchronously:
862                          * This might not happen soon enough, so some UI code might 
863                          * need to call this again, specifying a callback.
864                          */
865                         modest_tny_account_get_mmc_account_name (tny_account, NULL, NULL);
866                                 
867                         g_free (uri);
868                         uri = NULL;
869                 }
870         }
871         
872         
873         const gchar* id = is_mmc ? MODEST_MMC_ACCOUNT_ID :
874                 MODEST_LOCAL_FOLDERS_ACCOUNT_ID;
875         tny_account_set_id (TNY_ACCOUNT(tny_account), id);
876         
877         tny_account_set_forget_pass_func (TNY_ACCOUNT(tny_account), forget_pass_dummy);
878         tny_account_set_pass_func (TNY_ACCOUNT(tny_account), get_pass_dummy);
879         
880         modest_tny_account_set_parent_modest_account_name_for_server_account (
881                 TNY_ACCOUNT (tny_account), id);
882         
883         camel_url_free (url);
884         g_free (maildir);
885         g_free (url_string);
886
887         return TNY_ACCOUNT(tny_account);
888 }
889
890
891 TnyAccount*
892 modest_tny_account_new_for_per_account_local_outbox_folder (ModestAccountMgr *account_mgr,
893                                                             const gchar* account_name,
894                                                             TnySessionCamel *session)
895 {
896         g_return_val_if_fail (account_mgr, NULL);
897         g_return_val_if_fail (account_name, NULL);
898         g_return_val_if_fail (session, NULL);
899         
900         /* Notice that we create a ModestTnyOutboxAccount here, 
901          * instead of just a TnyCamelStoreAccount,
902          * so that we can later identify this as a special account for internal use only.
903          */
904         TnyStoreAccount *tny_account = TNY_STORE_ACCOUNT (modest_tny_outbox_account_new ());
905         if (!tny_account) {
906                 g_printerr ("modest: cannot create account for per-account local outbox folder.");
907                 return NULL;
908         }
909         
910         tny_camel_account_set_session (TNY_CAMEL_ACCOUNT(tny_account), session);
911         
912         /* Make sure that the paths exists on-disk so that TnyCamelStoreAccount can 
913          * find it to create a TnyFolder for it: */
914         gchar *folder_dir = modest_per_account_local_outbox_folder_info_get_maildir_path_to_outbox_folder (account_name); 
915         modest_init_one_local_folder(folder_dir);
916         g_free (folder_dir);
917         folder_dir = NULL;
918
919         /* This path should contain just one directory - "outbox": */
920         gchar *maildir = 
921                 modest_per_account_local_outbox_folder_info_get_maildir_path (account_name);
922                         
923         CamelURL *url = camel_url_new ("maildir:", NULL);
924         camel_url_set_path (url, maildir);
925         g_free (maildir);
926         
927         /* Needed by tinymail's DBC assertions */
928         camel_url_set_host (url, "localhost");
929         gchar *url_string = camel_url_to_string (url, 0);
930         camel_url_free (url);
931         
932         tny_account_set_url_string (TNY_ACCOUNT(tny_account), url_string);
933 /*      printf("DEBUG: %s:\n  url=%s\n", __FUNCTION__, url_string); */
934         g_free (url_string);
935
936         /* This text should never been seen,
937          * because the per-account outbox accounts are not seen directly by the user.
938          * Their folders are merged and shown as one folder. */ 
939         tny_account_set_name (TNY_ACCOUNT(tny_account), "Per-Account Outbox"); 
940         
941         gchar *account_id = g_strdup_printf (
942                 MODEST_PER_ACCOUNT_LOCAL_OUTBOX_FOLDER_ACCOUNT_ID_PREFIX "%s", 
943                 account_name);
944         tny_account_set_id (TNY_ACCOUNT(tny_account), account_id);
945         g_free (account_id);
946         
947         tny_account_set_forget_pass_func (TNY_ACCOUNT(tny_account), forget_pass_dummy);
948         tny_account_set_pass_func (TNY_ACCOUNT(tny_account), get_pass_dummy);
949         
950         /* Make this think that it belongs to the modest local-folders parent account: */
951         modest_tny_account_set_parent_modest_account_name_for_server_account (
952                 TNY_ACCOUNT (tny_account), MODEST_LOCAL_FOLDERS_ACCOUNT_ID);
953
954         return TNY_ACCOUNT(tny_account);
955 }
956
957
958
959 typedef gint (*TnyStatsFunc) (TnyFolderStats *stats);
960 #define TASK_GET_ALL_COUNT      0
961 #define TASK_GET_LOCAL_SIZE     1
962 #define TASK_GET_FOLDER_COUNT   2
963
964 typedef struct _RecurseFoldersHelper {
965         gint task;
966         guint sum;
967         guint folders;
968 } RecurseFoldersHelper;
969
970 static void
971 recurse_folders (TnyFolderStore *store, 
972                  TnyFolderStoreQuery *query, 
973                  RecurseFoldersHelper *helper)
974 {
975         TnyIterator *iter;
976         TnyList *folders = tny_simple_list_new ();
977
978         tny_folder_store_get_folders (store, folders, query, NULL);
979         iter = tny_list_create_iterator (folders);
980
981         helper->folders += tny_list_get_length (folders);
982
983         while (!tny_iterator_is_done (iter)) {
984                 TnyFolder *folder;
985
986                 folder = TNY_FOLDER (tny_iterator_get_current (iter));
987                 if (folder) {
988                         if (helper->task == TASK_GET_ALL_COUNT)
989                                 helper->sum += tny_folder_get_all_count (folder);
990
991                         if (helper->task == TASK_GET_LOCAL_SIZE)
992                                 helper->sum += tny_folder_get_local_size (folder);
993
994                         if (TNY_IS_FOLDER_STORE (folder))
995                                 recurse_folders (TNY_FOLDER_STORE (folder), query, helper);
996
997                         g_object_unref (folder);
998                 }
999
1000                 tny_iterator_next (iter);
1001         }
1002          g_object_unref (G_OBJECT (iter));
1003          g_object_unref (G_OBJECT (folders));
1004 }
1005
1006 gint 
1007 modest_tny_folder_store_get_folder_count (TnyFolderStore *self)
1008 {
1009         RecurseFoldersHelper *helper;
1010         gint retval;
1011
1012         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
1013
1014         /* Create helper */
1015         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
1016         helper->task = TASK_GET_FOLDER_COUNT;
1017         helper->folders = 0;
1018
1019         recurse_folders (self, NULL, helper);
1020
1021         retval = helper->folders;
1022
1023         g_free (helper);
1024
1025         return retval;
1026 }
1027
1028 gint
1029 modest_tny_folder_store_get_message_count (TnyFolderStore *self)
1030 {
1031         RecurseFoldersHelper *helper;
1032         gint retval;
1033
1034         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
1035         
1036         /* Create helper */
1037         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
1038         helper->task = TASK_GET_ALL_COUNT;
1039         if (TNY_IS_FOLDER (self))
1040                 helper->sum = tny_folder_get_all_count (TNY_FOLDER (self));
1041
1042         recurse_folders (self, NULL, helper);
1043
1044         retval = helper->sum;
1045
1046         g_free (helper);
1047
1048         return retval;
1049 }
1050
1051 gint 
1052 modest_tny_folder_store_get_local_size (TnyFolderStore *self)
1053 {
1054         RecurseFoldersHelper *helper;
1055         gint retval;
1056
1057         g_return_val_if_fail (TNY_IS_FOLDER_STORE (self), -1);
1058
1059         /* Create helper */
1060         helper = g_malloc0 (sizeof (RecurseFoldersHelper));
1061         helper->task = TASK_GET_LOCAL_SIZE;
1062         if (TNY_IS_FOLDER (self))
1063                 helper->sum = tny_folder_get_local_size (TNY_FOLDER (self));
1064
1065         recurse_folders (self, NULL, helper);
1066
1067         retval = helper->sum;
1068
1069         g_free (helper);
1070
1071         return retval;
1072 }
1073
1074 const gchar* 
1075 modest_tny_account_get_parent_modest_account_name_for_server_account (TnyAccount *self)
1076 {
1077         return (const gchar *)g_object_get_data (G_OBJECT (self), "modest_account");
1078 }
1079
1080 void 
1081 modest_tny_account_set_parent_modest_account_name_for_server_account (TnyAccount *self, 
1082                                                                       const gchar* parent_modest_account_name)
1083 {
1084         g_object_set_data_full (G_OBJECT(self), "modest_account",
1085                                 (gpointer) g_strdup (parent_modest_account_name), g_free);
1086 }
1087
1088 gboolean
1089 modest_tny_account_is_virtual_local_folders (TnyAccount *self)
1090 {
1091         /* We should make this more sophisticated if we ever use ModestTnyLocalFoldersAccount 
1092          * for anything else. */
1093         return MODEST_IS_TNY_LOCAL_FOLDERS_ACCOUNT (self);
1094 }
1095
1096
1097 gboolean
1098 modest_tny_account_is_memory_card_account (TnyAccount *self)
1099 {
1100         const gchar* account_id = NULL;
1101
1102         g_return_val_if_fail (TNY_ACCOUNT (self), FALSE);
1103
1104         if (!self)
1105                 return FALSE;
1106
1107         account_id = tny_account_get_id (self);
1108
1109         if (!account_id)
1110                 return FALSE;
1111         else    
1112                 return (strcmp (account_id, MODEST_MMC_ACCOUNT_ID) == 0);
1113 }