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