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