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