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