]> git.0d.be Git - empathy.git/blob - libempathy/empathy-utils.c
remove unused tp-contact-factory includes
[empathy.git] / libempathy / empathy-utils.c
1 /*
2  * Copyright (C) 2003-2007 Imendio AB
3  * Copyright (C) 2007-2011 Collabora Ltd.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18  * Boston, MA  02110-1301  USA
19  *
20  * Authors: Richard Hult <richard@imendio.com>
21  *          Martyn Russell <martyn@imendio.com>
22  *          Xavier Claessens <xclaesse@gmail.com>
23  *
24  * Some snippets are taken from GnuTLS 2.8.6, which is distributed under the
25  * same GNU Lesser General Public License 2.1 (or later) version. See
26  * empathy_get_x509_certified_hostname ().
27  */
28
29 #include "config.h"
30
31 #include <string.h>
32 #include <math.h>
33 #include <time.h>
34 #include <sys/types.h>
35
36 #include <glib/gi18n-lib.h>
37
38 #include <libxml/uri.h>
39
40 #include <folks/folks.h>
41 #include <folks/folks-telepathy.h>
42
43 #include <dbus/dbus-protocol.h>
44
45 #include <telepathy-glib/account-manager.h>
46 #include <telepathy-glib/connection.h>
47 #include <telepathy-glib/channel.h>
48 #include <telepathy-glib/dbus.h>
49 #include <telepathy-glib/util.h>
50
51 #include "empathy-client-factory.h"
52 #include "empathy-utils.h"
53 #include "empathy-individual-manager.h"
54 #include "empathy-presence-manager.h"
55 #include "empathy-request-util.h"
56
57 #include <extensions/extensions.h>
58
59 #define DEBUG_FLAG EMPATHY_DEBUG_OTHER
60 #include "empathy-debug.h"
61
62 /* Translation between presence types and string */
63 static struct {
64   const gchar *name;
65   TpConnectionPresenceType type;
66 } presence_types[] = {
67   { "available", TP_CONNECTION_PRESENCE_TYPE_AVAILABLE },
68   { "busy",      TP_CONNECTION_PRESENCE_TYPE_BUSY },
69   { "away",      TP_CONNECTION_PRESENCE_TYPE_AWAY },
70   { "ext_away",  TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY },
71   { "hidden",    TP_CONNECTION_PRESENCE_TYPE_HIDDEN },
72   { "offline",   TP_CONNECTION_PRESENCE_TYPE_OFFLINE },
73   { "unset",     TP_CONNECTION_PRESENCE_TYPE_UNSET },
74   { "unknown",   TP_CONNECTION_PRESENCE_TYPE_UNKNOWN },
75   { "error",     TP_CONNECTION_PRESENCE_TYPE_ERROR },
76   /* alternative names */
77   { "dnd",      TP_CONNECTION_PRESENCE_TYPE_BUSY },
78   { "brb",      TP_CONNECTION_PRESENCE_TYPE_AWAY },
79   { "xa",       TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY },
80   { NULL, },
81 };
82
83 static gboolean
84 properties_contains (gchar **list,
85                      gint length,
86                      const gchar *property);
87
88 static gboolean
89 check_writeable_property (TpConnection *connection,
90                           FolksIndividual *individual,
91                           gchar *property);
92
93 void
94 empathy_init (void)
95 {
96   static gboolean initialized = FALSE;
97   TpAccountManager *am;
98   EmpathyClientFactory *factory;
99
100   if (initialized)
101     return;
102
103   g_type_init ();
104
105   /* Setup gettext */
106   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
107   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
108
109   /* Setup debug output for empathy and telepathy-glib */
110   if (g_getenv ("EMPATHY_TIMING") != NULL)
111     g_log_set_default_handler (tp_debug_timestamped_log_handler, NULL);
112
113   empathy_debug_set_flags (g_getenv ("EMPATHY_DEBUG"));
114   tp_debug_divert_messages (g_getenv ("EMPATHY_LOGFILE"));
115
116   emp_cli_init ();
117
118   initialized = TRUE;
119
120   factory = empathy_client_factory_dup ();
121   am = tp_account_manager_new_with_factory (TP_SIMPLE_CLIENT_FACTORY (factory));
122   tp_account_manager_set_default (am);
123
124   g_object_unref (factory);
125   g_object_unref (am);
126 }
127
128 gboolean
129 empathy_xml_validate (xmlDoc      *doc,
130     const gchar *dtd_filename)
131 {
132   gchar *path;
133   xmlChar *escaped;
134   xmlValidCtxt  cvp;
135   xmlDtd *dtd;
136   gboolean ret;
137
138   path = g_build_filename (g_getenv ("EMPATHY_SRCDIR"), "libempathy",
139          dtd_filename, NULL);
140   if (!g_file_test (path, G_FILE_TEST_EXISTS))
141     {
142       g_free (path);
143       path = g_build_filename (DATADIR, "empathy", dtd_filename, NULL);
144     }
145
146   DEBUG ("Loading dtd file %s", path);
147
148   /* The list of valid chars is taken from libxml. */
149   escaped = xmlURIEscapeStr ((const xmlChar *) path,
150     (const xmlChar *)":@&=+$,/?;");
151   g_free (path);
152
153   memset (&cvp, 0, sizeof (cvp));
154   dtd = xmlParseDTD (NULL, escaped);
155   ret = xmlValidateDtd (&cvp, doc, dtd);
156
157   xmlFree (escaped);
158   xmlFreeDtd (dtd);
159
160   return ret;
161 }
162
163 xmlNodePtr
164 empathy_xml_node_get_child (xmlNodePtr   node,
165     const gchar *child_name)
166 {
167   xmlNodePtr l;
168
169   g_return_val_if_fail (node != NULL, NULL);
170   g_return_val_if_fail (child_name != NULL, NULL);
171
172   for (l = node->children; l; l = l->next)
173     {
174       if (l->name && strcmp ((const gchar *) l->name, child_name) == 0)
175         return l;
176     }
177
178   return NULL;
179 }
180
181 xmlChar *
182 empathy_xml_node_get_child_content (xmlNodePtr   node,
183     const gchar *child_name)
184 {
185   xmlNodePtr l;
186
187   g_return_val_if_fail (node != NULL, NULL);
188   g_return_val_if_fail (child_name != NULL, NULL);
189
190   l = empathy_xml_node_get_child (node, child_name);
191   if (l != NULL)
192     return xmlNodeGetContent (l);
193
194   return NULL;
195 }
196
197 xmlNodePtr
198 empathy_xml_node_find_child_prop_value (xmlNodePtr   node,
199     const gchar *prop_name,
200     const gchar *prop_value)
201 {
202   xmlNodePtr l;
203   xmlNodePtr found = NULL;
204
205   g_return_val_if_fail (node != NULL, NULL);
206   g_return_val_if_fail (prop_name != NULL, NULL);
207   g_return_val_if_fail (prop_value != NULL, NULL);
208
209   for (l = node->children; l && !found; l = l->next)
210     {
211       xmlChar *prop;
212
213       if (!xmlHasProp (l, (const xmlChar *) prop_name))
214         continue;
215
216       prop = xmlGetProp (l, (const xmlChar *) prop_name);
217       if (prop && strcmp ((const gchar *) prop, prop_value) == 0)
218         found = l;
219
220       xmlFree (prop);
221     }
222
223   return found;
224 }
225
226 const gchar *
227 empathy_presence_get_default_message (TpConnectionPresenceType presence)
228 {
229   switch (presence)
230     {
231       case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
232         return _("Available");
233       case TP_CONNECTION_PRESENCE_TYPE_BUSY:
234         return _("Busy");
235       case TP_CONNECTION_PRESENCE_TYPE_AWAY:
236       case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
237         return _("Away");
238       case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
239         return _("Invisible");
240       case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
241         return _("Offline");
242       case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
243         /* translators: presence type is unknown */
244         return C_("presence", "Unknown");
245       case TP_CONNECTION_PRESENCE_TYPE_UNSET:
246       case TP_CONNECTION_PRESENCE_TYPE_ERROR:
247       default:
248         return NULL;
249     }
250
251   return NULL;
252 }
253
254 const gchar *
255 empathy_presence_to_str (TpConnectionPresenceType presence)
256 {
257   int i;
258
259   for (i = 0 ; presence_types[i].name != NULL; i++)
260     if (presence == presence_types[i].type)
261       return presence_types[i].name;
262
263   return NULL;
264 }
265
266 TpConnectionPresenceType
267 empathy_presence_from_str (const gchar *str)
268 {
269   int i;
270
271   for (i = 0 ; presence_types[i].name != NULL; i++)
272     if (!tp_strdiff (str, presence_types[i].name))
273       return presence_types[i].type;
274
275   return TP_CONNECTION_PRESENCE_TYPE_UNSET;
276 }
277
278 static const gchar *
279 empathy_status_reason_get_default_message (TpConnectionStatusReason reason)
280 {
281   switch (reason)
282     {
283       case TP_CONNECTION_STATUS_REASON_NONE_SPECIFIED:
284         return _("No reason specified");
285       case TP_CONNECTION_STATUS_REASON_REQUESTED:
286         return _("Status is set to offline");
287       case TP_CONNECTION_STATUS_REASON_NETWORK_ERROR:
288         return _("Network error");
289       case TP_CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED:
290         return _("Authentication failed");
291       case TP_CONNECTION_STATUS_REASON_ENCRYPTION_ERROR:
292         return _("Encryption error");
293       case TP_CONNECTION_STATUS_REASON_NAME_IN_USE:
294         return _("Name in use");
295       case TP_CONNECTION_STATUS_REASON_CERT_NOT_PROVIDED:
296         return _("Certificate not provided");
297       case TP_CONNECTION_STATUS_REASON_CERT_UNTRUSTED:
298         return _("Certificate untrusted");
299       case TP_CONNECTION_STATUS_REASON_CERT_EXPIRED:
300         return _("Certificate expired");
301       case TP_CONNECTION_STATUS_REASON_CERT_NOT_ACTIVATED:
302         return _("Certificate not activated");
303       case TP_CONNECTION_STATUS_REASON_CERT_HOSTNAME_MISMATCH:
304         return _("Certificate hostname mismatch");
305       case TP_CONNECTION_STATUS_REASON_CERT_FINGERPRINT_MISMATCH:
306         return _("Certificate fingerprint mismatch");
307       case TP_CONNECTION_STATUS_REASON_CERT_SELF_SIGNED:
308         return _("Certificate self-signed");
309       case TP_CONNECTION_STATUS_REASON_CERT_OTHER_ERROR:
310         return _("Certificate error");
311       default:
312         return _("Unknown reason");
313     }
314 }
315
316 static GHashTable *
317 create_errors_to_message_hash (void)
318 {
319   GHashTable *errors;
320
321   errors = g_hash_table_new (g_str_hash, g_str_equal);
322   g_hash_table_insert (errors, TP_ERROR_STR_NETWORK_ERROR, _("Network error"));
323   g_hash_table_insert (errors, TP_ERROR_STR_AUTHENTICATION_FAILED,
324     _("Authentication failed"));
325   g_hash_table_insert (errors, TP_ERROR_STR_ENCRYPTION_ERROR,
326     _("Encryption error"));
327   g_hash_table_insert (errors, TP_ERROR_STR_CERT_NOT_PROVIDED,
328     _("Certificate not provided"));
329   g_hash_table_insert (errors, TP_ERROR_STR_CERT_UNTRUSTED,
330     _("Certificate untrusted"));
331   g_hash_table_insert (errors, TP_ERROR_STR_CERT_EXPIRED,
332     _("Certificate expired"));
333   g_hash_table_insert (errors, TP_ERROR_STR_CERT_NOT_ACTIVATED,
334     _("Certificate not activated"));
335   g_hash_table_insert (errors, TP_ERROR_STR_CERT_HOSTNAME_MISMATCH,
336     _("Certificate hostname mismatch"));
337   g_hash_table_insert (errors, TP_ERROR_STR_CERT_FINGERPRINT_MISMATCH,
338     _("Certificate fingerprint mismatch"));
339   g_hash_table_insert (errors, TP_ERROR_STR_CERT_SELF_SIGNED,
340     _("Certificate self-signed"));
341   g_hash_table_insert (errors, TP_ERROR_STR_CANCELLED,
342     _("Status is set to offline"));
343   g_hash_table_insert (errors, TP_ERROR_STR_ENCRYPTION_NOT_AVAILABLE,
344     _("Encryption is not available"));
345   g_hash_table_insert (errors, TP_ERROR_STR_CERT_INVALID,
346     _("Certificate is invalid"));
347   g_hash_table_insert (errors, TP_ERROR_STR_CONNECTION_REFUSED,
348     _("Connection has been refused"));
349   g_hash_table_insert (errors, TP_ERROR_STR_CONNECTION_FAILED,
350     _("Connection can't be established"));
351   g_hash_table_insert (errors, TP_ERROR_STR_CONNECTION_LOST,
352     _("Connection has been lost"));
353   g_hash_table_insert (errors, TP_ERROR_STR_ALREADY_CONNECTED,
354     _("This account is already connected to the server"));
355   g_hash_table_insert (errors, TP_ERROR_STR_CONNECTION_REPLACED,
356     _("Connection has been replaced by a new connection using the "
357     "same resource"));
358   g_hash_table_insert (errors, TP_ERROR_STR_REGISTRATION_EXISTS,
359     _("The account already exists on the server"));
360   g_hash_table_insert (errors, TP_ERROR_STR_SERVICE_BUSY,
361     _("Server is currently too busy to handle the connection"));
362   g_hash_table_insert (errors, TP_ERROR_STR_CERT_REVOKED,
363     _("Certificate has been revoked"));
364   g_hash_table_insert (errors, TP_ERROR_STR_CERT_INSECURE,
365     _("Certificate uses an insecure cipher algorithm or is "
366     "cryptographically weak"));
367   g_hash_table_insert (errors, TP_ERROR_STR_CERT_LIMIT_EXCEEDED,
368     _("The length of the server certificate, or the depth of the "
369     "server certificate chain, exceed the limits imposed by the "
370     "cryptography library"));
371   g_hash_table_insert (errors, TP_ERROR_STR_SOFTWARE_UPGRADE_REQUIRED,
372     _("Your software is too old"));
373   g_hash_table_insert (errors, DBUS_ERROR_NO_REPLY,
374     _("Internal error"));
375
376   return errors;
377 }
378
379 static const gchar *
380 empathy_dbus_error_name_get_default_message  (const gchar *error)
381 {
382   static GHashTable *errors_to_message = NULL;
383
384   if (error == NULL)
385     return NULL;
386
387   if (G_UNLIKELY (errors_to_message == NULL))
388     errors_to_message = create_errors_to_message_hash ();
389
390   return g_hash_table_lookup (errors_to_message, error);
391 }
392
393 const gchar *
394 empathy_account_get_error_message (TpAccount *account,
395     gboolean *user_requested)
396 {
397   const gchar *dbus_error;
398   const gchar *message;
399   const GHashTable *details = NULL;
400   TpConnectionStatusReason reason;
401
402   dbus_error = tp_account_get_detailed_error (account, &details);
403
404   if (user_requested != NULL)
405     {
406       if (tp_asv_get_boolean (details, "user-requested", NULL))
407         *user_requested = TRUE;
408       else
409         *user_requested = FALSE;
410     }
411
412   message = empathy_dbus_error_name_get_default_message (dbus_error);
413   if (message != NULL)
414     return message;
415
416   tp_account_get_connection_status (account, &reason);
417
418   DEBUG ("Don't understand error '%s'; fallback to the status reason (%u)",
419     dbus_error, reason);
420
421   return empathy_status_reason_get_default_message (reason);
422 }
423
424 gchar *
425 empathy_file_lookup (const gchar *filename, const gchar *subdir)
426 {
427   gchar *path;
428
429   if (subdir == NULL)
430     subdir = ".";
431
432   path = g_build_filename (g_getenv ("EMPATHY_SRCDIR"), subdir, filename, NULL);
433   if (!g_file_test (path, G_FILE_TEST_EXISTS))
434     {
435       g_free (path);
436       path = g_build_filename (DATADIR, "empathy", filename, NULL);
437     }
438
439   return path;
440 }
441
442 guint
443 empathy_proxy_hash (gconstpointer key)
444 {
445   TpProxy *proxy = TP_PROXY (key);
446   TpProxyClass *proxy_class = TP_PROXY_GET_CLASS (key);
447
448   g_return_val_if_fail (TP_IS_PROXY (proxy), 0);
449   g_return_val_if_fail (proxy_class->must_have_unique_name, 0);
450
451   return g_str_hash (proxy->object_path) ^ g_str_hash (proxy->bus_name);
452 }
453
454 gboolean
455 empathy_proxy_equal (gconstpointer a,
456     gconstpointer b)
457 {
458   TpProxy *proxy_a = TP_PROXY (a);
459   TpProxy *proxy_b = TP_PROXY (b);
460   TpProxyClass *proxy_a_class = TP_PROXY_GET_CLASS (a);
461   TpProxyClass *proxy_b_class = TP_PROXY_GET_CLASS (b);
462
463   g_return_val_if_fail (TP_IS_PROXY (proxy_a), FALSE);
464   g_return_val_if_fail (TP_IS_PROXY (proxy_b), FALSE);
465   g_return_val_if_fail (proxy_a_class->must_have_unique_name, 0);
466   g_return_val_if_fail (proxy_b_class->must_have_unique_name, 0);
467
468   return g_str_equal (proxy_a->object_path, proxy_b->object_path) &&
469          g_str_equal (proxy_a->bus_name, proxy_b->bus_name);
470 }
471
472 gboolean
473 empathy_check_available_state (void)
474 {
475   TpConnectionPresenceType presence;
476   EmpathyPresenceManager *presence_mgr;
477
478   presence_mgr = empathy_presence_manager_dup_singleton ();
479   presence = empathy_presence_manager_get_state (presence_mgr);
480   g_object_unref (presence_mgr);
481
482   if (presence != TP_CONNECTION_PRESENCE_TYPE_AVAILABLE &&
483     presence != TP_CONNECTION_PRESENCE_TYPE_UNSET)
484     return FALSE;
485
486   return TRUE;
487 }
488
489 gint
490 empathy_uint_compare (gconstpointer a,
491     gconstpointer b)
492 {
493   return *(guint *) a - *(guint *) b;
494 }
495
496 gchar *
497 empathy_protocol_icon_name (const gchar *protocol)
498 {
499   if (!tp_strdiff (protocol, "yahoojp"))
500     /* Yahoo Japan uses the same icon as Yahoo */
501     protocol = "yahoo";
502   else if (!tp_strdiff (protocol, "simple"))
503     /* SIMPLE uses the same icon as SIP */
504     protocol = "sip";
505   else if (!tp_strdiff (protocol, "sms"))
506     return g_strdup ("phone");
507
508   return g_strdup_printf ("im-%s", protocol);
509 }
510
511 GType
512 empathy_type_dbus_ao (void)
513 {
514   static GType t = 0;
515
516   if (G_UNLIKELY (t == 0))
517      t = dbus_g_type_get_collection ("GPtrArray", DBUS_TYPE_G_OBJECT_PATH);
518
519   return t;
520 }
521
522 const char *
523 empathy_protocol_name_to_display_name (const gchar *proto_name)
524 {
525   int i;
526   static struct {
527     const gchar *proto;
528     const gchar *display;
529     gboolean translated;
530   } names[] = {
531     { "jabber", "Jabber", FALSE },
532     { "msn", "Windows Live (MSN)", FALSE, },
533     { "local-xmpp", N_("People Nearby"), TRUE },
534     { "irc", "IRC", FALSE },
535     { "icq", "ICQ", FALSE },
536     { "aim", "AIM", FALSE },
537     { "yahoo", "Yahoo!", FALSE },
538     { "yahoojp", N_("Yahoo! Japan"), TRUE },
539     { "groupwise", "GroupWise", FALSE },
540     { "sip", "SIP", FALSE },
541     { NULL, NULL }
542   };
543
544   for (i = 0; names[i].proto != NULL; i++)
545     {
546       if (!tp_strdiff (proto_name, names[i].proto))
547         {
548           if (names[i].translated)
549             return gettext (names[i].display);
550           else
551             return names[i].display;
552         }
553     }
554
555   return proto_name;
556 }
557
558 const char *
559 empathy_service_name_to_display_name (const gchar *service_name)
560 {
561   int i;
562   static struct {
563     const gchar *service;
564     const gchar *display;
565     gboolean translated;
566   } names[] = {
567     { "google-talk", N_("Google Talk"), FALSE },
568     { "facebook", N_("Facebook Chat"), TRUE },
569     { NULL, NULL }
570   };
571
572   for (i = 0; names[i].service != NULL; i++)
573     {
574       if (!tp_strdiff (service_name, names[i].service))
575         {
576           if (names[i].translated)
577             return gettext (names[i].display);
578           else
579             return names[i].display;
580         }
581     }
582
583   return service_name;
584 }
585
586 gboolean
587 empathy_account_manager_get_accounts_connected (gboolean *connecting)
588 {
589   TpAccountManager *manager;
590   GList *accounts, *l;
591   gboolean out_connecting = FALSE;
592   gboolean out_connected = FALSE;
593
594   manager = tp_account_manager_dup ();
595
596   if (G_UNLIKELY (!tp_account_manager_is_prepared (manager,
597           TP_ACCOUNT_MANAGER_FEATURE_CORE)))
598     g_critical (G_STRLOC ": %s called before AccountManager ready", G_STRFUNC);
599
600   accounts = tp_account_manager_get_valid_accounts (manager);
601
602   for (l = accounts; l != NULL; l = l->next)
603     {
604       TpConnectionStatus s = tp_account_get_connection_status (
605           TP_ACCOUNT (l->data), NULL);
606
607       if (s == TP_CONNECTION_STATUS_CONNECTING)
608         out_connecting = TRUE;
609       else if (s == TP_CONNECTION_STATUS_CONNECTED)
610         out_connected = TRUE;
611
612       if (out_connecting && out_connected)
613         break;
614     }
615
616   g_list_free (accounts);
617   g_object_unref (manager);
618
619   if (connecting != NULL)
620     *connecting = out_connecting;
621
622   return out_connected;
623 }
624
625 /* Change the RequestedPresence of a newly created account to ensure that it
626  * is actually connected. */
627 void
628 empathy_connect_new_account (TpAccount *account,
629     TpAccountManager *account_manager)
630 {
631   TpConnectionPresenceType presence;
632   gchar *status, *message;
633
634   /* only force presence if presence was offline, unknown or unset */
635   presence = tp_account_get_requested_presence (account, NULL, NULL);
636   switch (presence)
637     {
638       case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
639       case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
640       case TP_CONNECTION_PRESENCE_TYPE_UNSET:
641         presence = tp_account_manager_get_most_available_presence (
642             account_manager, &status, &message);
643
644         if (presence == TP_CONNECTION_PRESENCE_TYPE_OFFLINE)
645           /* Global presence is offline; we force it so user doesn't have to
646            * manually change the presence to connect his new account. */
647           presence = TP_CONNECTION_PRESENCE_TYPE_AVAILABLE;
648
649         tp_account_request_presence_async (account, presence,
650             status, NULL, NULL, NULL);
651
652         g_free (status);
653         g_free (message);
654         break;
655
656        case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
657        case TP_CONNECTION_PRESENCE_TYPE_AWAY:
658        case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
659        case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
660        case TP_CONNECTION_PRESENCE_TYPE_BUSY:
661        case TP_CONNECTION_PRESENCE_TYPE_ERROR:
662        default:
663         /* do nothing if the presence is not offline */
664         break;
665     }
666 }
667
668 /* Translate Folks' general presence type to the Tp presence type */
669 TpConnectionPresenceType
670 empathy_folks_presence_type_to_tp (FolksPresenceType type)
671 {
672   return (TpConnectionPresenceType) type;
673 }
674
675 /* Returns TRUE if the given Individual contains a TpContact */
676 gboolean
677 empathy_folks_individual_contains_contact (FolksIndividual *individual)
678 {
679   GeeSet *personas;
680   GeeIterator *iter;
681   gboolean retval = FALSE;
682
683   g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), FALSE);
684
685   personas = folks_individual_get_personas (individual);
686   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
687   while (!retval && gee_iterator_next (iter))
688     {
689       FolksPersona *persona = gee_iterator_get (iter);
690       TpContact *contact = NULL;
691
692       if (empathy_folks_persona_is_interesting (persona))
693         contact = tpf_persona_get_contact (TPF_PERSONA (persona));
694
695       g_clear_object (&persona);
696
697       if (contact != NULL)
698         retval = TRUE;
699     }
700   g_clear_object (&iter);
701
702   return retval;
703 }
704
705 /* TODO: this needs to be eliminated (and replaced in some cases with user
706  * prompts) when we break the assumption that FolksIndividuals are 1:1 with
707  * TpContacts */
708
709 /* Retrieve the EmpathyContact corresponding to the first TpContact contained
710  * within the given Individual. Note that this is a temporary convenience. See
711  * the TODO above. */
712 EmpathyContact *
713 empathy_contact_dup_from_folks_individual (FolksIndividual *individual)
714 {
715   GeeSet *personas;
716   GeeIterator *iter;
717   EmpathyContact *contact = NULL;
718
719   g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
720
721   personas = folks_individual_get_personas (individual);
722   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
723   while (gee_iterator_next (iter) && (contact == NULL))
724     {
725       TpfPersona *persona = gee_iterator_get (iter);
726
727       if (empathy_folks_persona_is_interesting (FOLKS_PERSONA (persona)))
728         {
729           TpContact *tp_contact;
730
731           tp_contact = tpf_persona_get_contact (persona);
732           if (tp_contact != NULL)
733             {
734               contact = empathy_contact_dup_from_tp_contact (tp_contact);
735               empathy_contact_set_persona (contact, FOLKS_PERSONA (persona));
736             }
737         }
738       g_clear_object (&persona);
739     }
740   g_clear_object (&iter);
741
742   if (contact == NULL)
743     {
744       DEBUG ("Can't create an EmpathyContact for Individual %s",
745           folks_individual_get_id (individual));
746     }
747
748   return contact;
749 }
750
751 TpChannelGroupChangeReason
752 tp_channel_group_change_reason_from_folks_groups_change_reason (
753     FolksGroupDetailsChangeReason reason)
754 {
755   return (TpChannelGroupChangeReason) reason;
756 }
757
758 TpfPersonaStore *
759 empathy_dup_persona_store_for_connection (TpConnection *connection)
760 {
761   FolksBackendStore *backend_store;
762   FolksBackend *backend;
763   TpfPersonaStore *result = NULL;
764
765   backend_store = folks_backend_store_dup ();
766   backend = folks_backend_store_dup_backend_by_name (backend_store,
767       "telepathy");
768   if (backend != NULL)
769     {
770       GeeMap *stores_map;
771       GeeMapIterator *iter;
772
773       stores_map = folks_backend_get_persona_stores (backend);
774       iter = gee_map_map_iterator (stores_map);
775       while (gee_map_iterator_next (iter))
776         {
777           TpfPersonaStore *persona_store = gee_map_iterator_get_value (iter);
778           TpAccount *account;
779           TpConnection *conn_cur;
780
781           account = tpf_persona_store_get_account (persona_store);
782           conn_cur = tp_account_get_connection (account);
783           if (conn_cur == connection)
784             result = persona_store;
785         }
786       g_clear_object (&iter);
787     }
788
789   g_object_unref (backend);
790   g_object_unref (backend_store);
791
792   return result;
793 }
794
795 gboolean
796 empathy_connection_can_add_personas (TpConnection *connection)
797 {
798   gboolean retval;
799   FolksPersonaStore *persona_store;
800
801   g_return_val_if_fail (TP_IS_CONNECTION (connection), FALSE);
802
803   if (tp_connection_get_status (connection, NULL) !=
804           TP_CONNECTION_STATUS_CONNECTED)
805       return FALSE;
806
807   persona_store = FOLKS_PERSONA_STORE (
808       empathy_dup_persona_store_for_connection (connection));
809
810   retval = (folks_persona_store_get_can_add_personas (persona_store) ==
811       FOLKS_MAYBE_BOOL_TRUE);
812
813   g_clear_object (&persona_store);
814
815   return retval;
816 }
817
818 gboolean
819 empathy_connection_can_alias_personas (TpConnection *connection,
820                                        FolksIndividual *individual)
821 {
822   gboolean retval;
823
824   g_return_val_if_fail (TP_IS_CONNECTION (connection), FALSE);
825
826   if (tp_connection_get_status (connection, NULL) !=
827           TP_CONNECTION_STATUS_CONNECTED)
828       return FALSE;
829
830   retval = check_writeable_property (connection, individual, "alias");
831
832   return retval;
833 }
834
835 gboolean
836 empathy_connection_can_group_personas (TpConnection *connection,
837                                        FolksIndividual *individual)
838 {
839   gboolean retval;
840
841   g_return_val_if_fail (TP_IS_CONNECTION (connection), FALSE);
842
843   if (tp_connection_get_status (connection, NULL) !=
844           TP_CONNECTION_STATUS_CONNECTED)
845       return FALSE;
846
847   retval = check_writeable_property (connection, individual, "groups");
848
849   return retval;
850 }
851
852 gboolean
853 empathy_folks_persona_is_interesting (FolksPersona *persona)
854 {
855   /* We're not interested in non-Telepathy personas */
856   if (!TPF_IS_PERSONA (persona))
857     return FALSE;
858
859   /* We're not interested in user personas which haven't been added to the
860    * contact list (see bgo#637151). */
861   if (folks_persona_get_is_user (persona) &&
862       !tpf_persona_get_is_in_contact_list (TPF_PERSONA (persona)))
863     {
864       return FALSE;
865     }
866
867   return TRUE;
868 }
869
870 gchar *
871 empathy_get_x509_certificate_hostname (gnutls_x509_crt_t cert)
872 {
873   gchar dns_name[256];
874   gsize dns_name_size;
875   gint idx;
876   gint res = 0;
877
878   /* this snippet is taken from GnuTLS.
879    * see gnutls/lib/x509/rfc2818_hostname.c
880    */
881   for (idx = 0; res >= 0; idx++)
882     {
883       dns_name_size = sizeof (dns_name);
884       res = gnutls_x509_crt_get_subject_alt_name (cert, idx,
885           dns_name, &dns_name_size, NULL);
886
887       if (res == GNUTLS_SAN_DNSNAME || res == GNUTLS_SAN_IPADDRESS)
888         return g_strndup (dns_name, dns_name_size);
889     }
890
891   dns_name_size = sizeof (dns_name);
892   res = gnutls_x509_crt_get_dn_by_oid (cert, GNUTLS_OID_X520_COMMON_NAME,
893       0, 0, dns_name, &dns_name_size);
894
895   if (res >= 0)
896     return g_strndup (dns_name, dns_name_size);
897
898   return NULL;
899 }
900
901 gchar *
902 empathy_format_currency (gint amount,
903     guint scale,
904     const gchar *currency)
905 {
906 #define MINUS "\342\210\222"
907 #define EURO "\342\202\254"
908 #define YEN "\302\245"
909 #define POUND "\302\243"
910
911   /* localised representations of currency */
912   /* FIXME: check these, especially negatives and decimals */
913   static const struct {
914     const char *currency;
915     const char *positive;
916     const char *negative;
917     const char *decimal;
918   } currencies[] = {
919     /* sym   positive    negative          decimal */
920     { "EUR", EURO "%s",  MINUS EURO "%s",  "." },
921     { "USD", "$%s",      MINUS "$%s",      "." },
922     { "JPY", YEN "%s"    MINUS YEN "%s",   "." },
923     { "GBP", POUND "%s", MINUS POUND "%s", "." },
924     { "PLN", "%s zl",    MINUS "%s zl",    "." },
925     { "BRL", "R$%s",     MINUS "R$%s",     "." },
926     { "SEK", "%s kr",    MINUS "%s kr",    "." },
927     { "DKK", "kr %s",    "kr " MINUS "%s", "." },
928     { "HKD", "$%s",      MINUS "$%s",      "." },
929     { "CHF", "%s Fr.",   MINUS "%s Fr.",   "." },
930     { "NOK", "kr %s",    "kr" MINUS "%s",  "," },
931     { "CAD", "$%s",      MINUS "$%s",      "." },
932     { "TWD", "$%s",      MINUS "$%s",      "." },
933     { "AUD", "$%s",      MINUS "$%s",      "." },
934   };
935
936   const char *positive = "%s";
937   const char *negative = MINUS "%s";
938   const char *decimal = ".";
939   char *fmt_amount, *money;
940   guint i;
941
942   /* get the localised currency format */
943   for (i = 0; i < G_N_ELEMENTS (currencies); i++)
944     {
945       if (!tp_strdiff (currency, currencies[i].currency))
946         {
947           positive = currencies[i].positive;
948           negative = currencies[i].negative;
949           decimal = currencies[i].decimal;
950           break;
951         }
952     }
953
954   /* format the amount using the scale */
955   if (scale == 0)
956     {
957       /* no decimal point required */
958       fmt_amount = g_strdup_printf ("%d", amount);
959     }
960   else
961     {
962       /* don't use floating point arithmatic, it's noisy;
963        * we take the absolute values, because we want the minus
964        * sign to appear before the $ */
965       int divisor = pow (10, scale);
966       int dollars = abs (amount / divisor);
967       int cents = abs (amount % divisor);
968
969       fmt_amount = g_strdup_printf ("%d%s%0*d",
970         dollars, decimal, scale, cents);
971     }
972
973   money = g_strdup_printf (amount < 0 ? negative : positive, fmt_amount);
974   g_free (fmt_amount);
975
976   return money;
977 }
978
979 gboolean
980 empathy_account_has_uri_scheme_tel (TpAccount *account)
981 {
982   const gchar * const * uri_schemes;
983   guint i;
984
985   uri_schemes = tp_account_get_uri_schemes (account);
986   if (uri_schemes == NULL)
987     return FALSE;
988
989   for (i = 0; uri_schemes[i] != NULL; i++)
990     {
991       if (!tp_strdiff (uri_schemes[i], "tel"))
992         return TRUE;
993     }
994
995   return FALSE;
996 }
997
998 /* Return the TpContact on @conn associated with @individual, if any */
999 TpContact *
1000 empathy_get_tp_contact_for_individual (FolksIndividual *individual,
1001     TpConnection *conn)
1002 {
1003   TpContact *contact = NULL;
1004   GeeSet *personas;
1005   GeeIterator *iter;
1006
1007   personas = folks_individual_get_personas (individual);
1008   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
1009   while (contact == NULL && gee_iterator_next (iter))
1010     {
1011       TpfPersona *persona = gee_iterator_get (iter);
1012       TpConnection *contact_conn;
1013       TpContact *contact_cur = NULL;
1014
1015       if (TPF_IS_PERSONA (persona))
1016         {
1017           contact_cur = tpf_persona_get_contact (persona);
1018           if (contact_cur != NULL)
1019             {
1020               contact_conn = tp_contact_get_connection (contact_cur);
1021
1022               if (!tp_strdiff (tp_proxy_get_object_path (contact_conn),
1023                     tp_proxy_get_object_path (conn)))
1024                 contact = contact_cur;
1025             }
1026         }
1027
1028       g_clear_object (&persona);
1029     }
1030   g_clear_object (&iter);
1031
1032   return contact;
1033 }
1034
1035 static gboolean
1036 properties_contains (gchar **list,
1037                      gint length,
1038                      const gchar *property)
1039 {
1040   gint i;
1041
1042   for (i = 0; i < length; i++)
1043     {
1044       if (!tp_strdiff (list[i], property))
1045         return TRUE;
1046     }
1047
1048   return FALSE;
1049 }
1050
1051 static gboolean
1052 check_writeable_property (TpConnection *connection,
1053                           FolksIndividual *individual,
1054                           gchar *property)
1055 {
1056   gchar **properties;
1057   gint prop_len;
1058   gboolean retval = FALSE;
1059   GeeSet *personas;
1060   GeeIterator *iter;
1061   FolksPersonaStore *persona_store;
1062
1063   persona_store = FOLKS_PERSONA_STORE (
1064       empathy_dup_persona_store_for_connection (connection));
1065
1066   properties =
1067     folks_persona_store_get_always_writeable_properties (persona_store,
1068                                                          &prop_len);
1069   retval = properties_contains (properties, prop_len, property);
1070   if (retval == TRUE)
1071     goto out;
1072
1073   /* Lets see if the Individual contains a Persona with the given property */
1074   personas = folks_individual_get_personas (individual);
1075   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
1076   while (!retval && gee_iterator_next (iter))
1077     {
1078       FolksPersona *persona = gee_iterator_get (iter);
1079
1080       properties =
1081         folks_persona_get_writeable_properties (persona, &prop_len);
1082       retval = properties_contains (properties, prop_len, property);
1083
1084       g_clear_object (&persona);
1085
1086       if (retval == TRUE)
1087         break;
1088     }
1089   g_clear_object (&iter);
1090
1091 out:
1092   g_clear_object (&persona_store);
1093   return retval;
1094 }
1095
1096 /* Calculate whether the Individual can do audio or video calls.
1097  * FIXME: We can remove this once libfolks has grown capabilities support
1098  * again: bgo#626179. */
1099 void
1100 empathy_individual_can_audio_video_call (FolksIndividual *individual,
1101     gboolean *can_audio_call,
1102     gboolean *can_video_call,
1103     EmpathyContact **out_contact)
1104 {
1105   GeeSet *personas;
1106   GeeIterator *iter;
1107   gboolean can_audio = FALSE, can_video = FALSE;
1108
1109   personas = folks_individual_get_personas (individual);
1110   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
1111   while (gee_iterator_next (iter))
1112     {
1113       FolksPersona *persona = gee_iterator_get (iter);
1114       TpContact *tp_contact;
1115
1116       if (!empathy_folks_persona_is_interesting (persona))
1117         goto while_finish;
1118
1119       tp_contact = tpf_persona_get_contact (TPF_PERSONA (persona));
1120       if (tp_contact != NULL)
1121         {
1122           EmpathyContact *contact;
1123
1124           contact = empathy_contact_dup_from_tp_contact (tp_contact);
1125           empathy_contact_set_persona (contact, persona);
1126
1127           can_audio = can_audio || empathy_contact_get_capabilities (contact) &
1128               EMPATHY_CAPABILITIES_AUDIO;
1129           can_video = can_video || empathy_contact_get_capabilities (contact) &
1130               EMPATHY_CAPABILITIES_VIDEO;
1131
1132           if (out_contact != NULL)
1133             *out_contact = g_object_ref (contact);
1134
1135           g_object_unref (contact);
1136         }
1137
1138 while_finish:
1139       g_clear_object (&persona);
1140
1141       if (can_audio && can_video)
1142         break;
1143     }
1144
1145   g_clear_object (&iter);
1146
1147   if (can_audio_call != NULL)
1148     *can_audio_call = can_audio;
1149
1150   if (can_video_call != NULL)
1151     *can_video_call = can_video;
1152 }
1153
1154 gboolean
1155 empathy_sasl_channel_supports_mechanism (TpChannel *channel,
1156     const gchar *mechanism)
1157 {
1158   GHashTable *props;
1159   const gchar * const *available_mechanisms;
1160
1161   props = tp_channel_borrow_immutable_properties (channel);
1162   available_mechanisms = tp_asv_get_boxed (props,
1163       TP_PROP_CHANNEL_INTERFACE_SASL_AUTHENTICATION_AVAILABLE_MECHANISMS,
1164       G_TYPE_STRV);
1165
1166   return tp_strv_contains (available_mechanisms, mechanism);
1167 }
1168
1169 static FolksIndividual *
1170 create_individual_from_persona (FolksPersona *persona)
1171 {
1172   GeeSet *personas;
1173   FolksIndividual *individual;
1174
1175   personas = GEE_SET (
1176       gee_hash_set_new (FOLKS_TYPE_PERSONA, g_object_ref, g_object_unref,
1177       g_direct_hash, g_direct_equal));
1178
1179   gee_collection_add (GEE_COLLECTION (personas), persona);
1180
1181   individual = folks_individual_new (personas);
1182
1183   g_clear_object (&personas);
1184
1185   return individual;
1186 }
1187
1188 FolksIndividual *
1189 empathy_create_individual_from_tp_contact (TpContact *contact)
1190 {
1191   TpfPersona *persona;
1192   FolksIndividual *individual;
1193
1194   persona = tpf_persona_dup_for_contact (contact);
1195   if (persona == NULL)
1196     {
1197       DEBUG ("Failed to get a persona for %s",
1198           tp_contact_get_identifier (contact));
1199       return NULL;
1200     }
1201
1202   individual = create_individual_from_persona (FOLKS_PERSONA (persona));
1203
1204   g_object_unref (persona);
1205   return individual;
1206 }
1207
1208 /* Look for a FolksIndividual containing @contact as one of his persona
1209  * and create one if needed */
1210 FolksIndividual *
1211 empathy_ensure_individual_from_tp_contact (TpContact *contact)
1212 {
1213   TpfPersona *persona;
1214   FolksIndividual *individual;
1215
1216   persona = tpf_persona_dup_for_contact (contact);
1217   if (persona == NULL)
1218     {
1219       DEBUG ("Failed to get a persona for %s",
1220           tp_contact_get_identifier (contact));
1221       return NULL;
1222     }
1223
1224   individual = folks_persona_get_individual (FOLKS_PERSONA (persona));
1225
1226   if (individual != NULL)
1227     g_object_ref (individual);
1228   else
1229     individual = create_individual_from_persona (FOLKS_PERSONA (persona));
1230
1231   g_object_unref (persona);
1232   return individual;
1233 }