]> git.0d.be Git - empathy.git/blob - libempathy/empathy-utils.c
include telepathy-glib.h
[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     { NULL, NULL }
506   };
507
508   for (i = 0; names[i].proto != NULL; i++)
509     {
510       if (!tp_strdiff (proto_name, names[i].proto))
511         {
512           if (names[i].translated)
513             return gettext (names[i].display);
514           else
515             return names[i].display;
516         }
517     }
518
519   return proto_name;
520 }
521
522 const char *
523 empathy_service_name_to_display_name (const gchar *service_name)
524 {
525   int i;
526   static struct {
527     const gchar *service;
528     const gchar *display;
529     gboolean translated;
530   } names[] = {
531     { "google-talk", N_("Google Talk"), FALSE },
532     { "facebook", N_("Facebook Chat"), TRUE },
533     { NULL, NULL }
534   };
535
536   for (i = 0; names[i].service != NULL; i++)
537     {
538       if (!tp_strdiff (service_name, names[i].service))
539         {
540           if (names[i].translated)
541             return gettext (names[i].display);
542           else
543             return names[i].display;
544         }
545     }
546
547   return service_name;
548 }
549
550 gboolean
551 empathy_account_manager_get_accounts_connected (gboolean *connecting)
552 {
553   TpAccountManager *manager;
554   GList *accounts, *l;
555   gboolean out_connecting = FALSE;
556   gboolean out_connected = FALSE;
557
558   manager = tp_account_manager_dup ();
559
560   if (G_UNLIKELY (!tp_account_manager_is_prepared (manager,
561           TP_ACCOUNT_MANAGER_FEATURE_CORE)))
562     g_critical (G_STRLOC ": %s called before AccountManager ready", G_STRFUNC);
563
564   accounts = tp_account_manager_dup_valid_accounts (manager);
565
566   for (l = accounts; l != NULL; l = l->next)
567     {
568       TpConnectionStatus s = tp_account_get_connection_status (
569           TP_ACCOUNT (l->data), NULL);
570
571       if (s == TP_CONNECTION_STATUS_CONNECTING)
572         out_connecting = TRUE;
573       else if (s == TP_CONNECTION_STATUS_CONNECTED)
574         out_connected = TRUE;
575
576       if (out_connecting && out_connected)
577         break;
578     }
579
580   g_list_free_full (accounts, g_object_unref);
581   g_object_unref (manager);
582
583   if (connecting != NULL)
584     *connecting = out_connecting;
585
586   return out_connected;
587 }
588
589 /* Change the RequestedPresence of a newly created account to ensure that it
590  * is actually connected. */
591 void
592 empathy_connect_new_account (TpAccount *account,
593     TpAccountManager *account_manager)
594 {
595   TpConnectionPresenceType presence;
596   gchar *status, *message;
597
598   /* only force presence if presence was offline, unknown or unset */
599   presence = tp_account_get_requested_presence (account, NULL, NULL);
600   switch (presence)
601     {
602       case TP_CONNECTION_PRESENCE_TYPE_OFFLINE:
603       case TP_CONNECTION_PRESENCE_TYPE_UNKNOWN:
604       case TP_CONNECTION_PRESENCE_TYPE_UNSET:
605         presence = tp_account_manager_get_most_available_presence (
606             account_manager, &status, &message);
607
608         if (presence == TP_CONNECTION_PRESENCE_TYPE_OFFLINE)
609           /* Global presence is offline; we force it so user doesn't have to
610            * manually change the presence to connect his new account. */
611           presence = TP_CONNECTION_PRESENCE_TYPE_AVAILABLE;
612
613         tp_account_request_presence_async (account, presence,
614             status, NULL, NULL, NULL);
615
616         g_free (status);
617         g_free (message);
618         break;
619
620        case TP_CONNECTION_PRESENCE_TYPE_AVAILABLE:
621        case TP_CONNECTION_PRESENCE_TYPE_AWAY:
622        case TP_CONNECTION_PRESENCE_TYPE_EXTENDED_AWAY:
623        case TP_CONNECTION_PRESENCE_TYPE_HIDDEN:
624        case TP_CONNECTION_PRESENCE_TYPE_BUSY:
625        case TP_CONNECTION_PRESENCE_TYPE_ERROR:
626        default:
627         /* do nothing if the presence is not offline */
628         break;
629     }
630 }
631
632 /* Translate Folks' general presence type to the Tp presence type */
633 TpConnectionPresenceType
634 empathy_folks_presence_type_to_tp (FolksPresenceType type)
635 {
636   return (TpConnectionPresenceType) type;
637 }
638
639 /* Returns TRUE if the given Individual contains a TpContact */
640 gboolean
641 empathy_folks_individual_contains_contact (FolksIndividual *individual)
642 {
643   GeeSet *personas;
644   GeeIterator *iter;
645   gboolean retval = FALSE;
646
647   g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), FALSE);
648
649   personas = folks_individual_get_personas (individual);
650   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
651   while (!retval && gee_iterator_next (iter))
652     {
653       FolksPersona *persona = gee_iterator_get (iter);
654       TpContact *contact = NULL;
655
656       if (empathy_folks_persona_is_interesting (persona))
657         contact = tpf_persona_get_contact (TPF_PERSONA (persona));
658
659       g_clear_object (&persona);
660
661       if (contact != NULL)
662         retval = TRUE;
663     }
664   g_clear_object (&iter);
665
666   return retval;
667 }
668
669 /* TODO: this needs to be eliminated (and replaced in some cases with user
670  * prompts) when we break the assumption that FolksIndividuals are 1:1 with
671  * TpContacts */
672
673 /* Retrieve the EmpathyContact corresponding to the first TpContact contained
674  * within the given Individual. Note that this is a temporary convenience. See
675  * the TODO above. */
676 EmpathyContact *
677 empathy_contact_dup_from_folks_individual (FolksIndividual *individual)
678 {
679   GeeSet *personas;
680   GeeIterator *iter;
681   EmpathyContact *contact = NULL;
682
683   g_return_val_if_fail (FOLKS_IS_INDIVIDUAL (individual), NULL);
684
685   personas = folks_individual_get_personas (individual);
686   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
687   while (gee_iterator_next (iter) && (contact == NULL))
688     {
689       TpfPersona *persona = gee_iterator_get (iter);
690
691       if (empathy_folks_persona_is_interesting (FOLKS_PERSONA (persona)))
692         {
693           TpContact *tp_contact;
694
695           tp_contact = tpf_persona_get_contact (persona);
696           if (tp_contact != NULL)
697             {
698               contact = empathy_contact_dup_from_tp_contact (tp_contact);
699               empathy_contact_set_persona (contact, FOLKS_PERSONA (persona));
700             }
701         }
702       g_clear_object (&persona);
703     }
704   g_clear_object (&iter);
705
706   if (contact == NULL)
707     {
708       DEBUG ("Can't create an EmpathyContact for Individual %s",
709           folks_individual_get_id (individual));
710     }
711
712   return contact;
713 }
714
715 TpChannelGroupChangeReason
716 tp_channel_group_change_reason_from_folks_groups_change_reason (
717     FolksGroupDetailsChangeReason reason)
718 {
719   return (TpChannelGroupChangeReason) reason;
720 }
721
722 TpfPersonaStore *
723 empathy_dup_persona_store_for_connection (TpConnection *connection)
724 {
725   FolksBackendStore *backend_store;
726   FolksBackend *backend;
727   TpfPersonaStore *result = NULL;
728
729   backend_store = folks_backend_store_dup ();
730   backend = folks_backend_store_dup_backend_by_name (backend_store,
731       "telepathy");
732   if (backend != NULL)
733     {
734       GeeMap *stores_map;
735       GeeMapIterator *iter;
736
737       stores_map = folks_backend_get_persona_stores (backend);
738       iter = gee_map_map_iterator (stores_map);
739       while (gee_map_iterator_next (iter))
740         {
741           TpfPersonaStore *persona_store = gee_map_iterator_get_value (iter);
742           TpAccount *account;
743           TpConnection *conn_cur;
744
745           account = tpf_persona_store_get_account (persona_store);
746           conn_cur = tp_account_get_connection (account);
747           if (conn_cur == connection)
748             result = persona_store;
749         }
750       g_clear_object (&iter);
751     }
752
753   g_object_unref (backend);
754   g_object_unref (backend_store);
755
756   return result;
757 }
758
759 gboolean
760 empathy_connection_can_add_personas (TpConnection *connection)
761 {
762   gboolean retval;
763   FolksPersonaStore *persona_store;
764
765   g_return_val_if_fail (TP_IS_CONNECTION (connection), FALSE);
766
767   if (tp_connection_get_status (connection, NULL) !=
768           TP_CONNECTION_STATUS_CONNECTED)
769       return FALSE;
770
771   persona_store = FOLKS_PERSONA_STORE (
772       empathy_dup_persona_store_for_connection (connection));
773
774   retval = (folks_persona_store_get_can_add_personas (persona_store) ==
775       FOLKS_MAYBE_BOOL_TRUE);
776
777   g_clear_object (&persona_store);
778
779   return retval;
780 }
781
782 gboolean
783 empathy_connection_can_alias_personas (TpConnection *connection,
784                                        FolksIndividual *individual)
785 {
786   gboolean retval;
787
788   g_return_val_if_fail (TP_IS_CONNECTION (connection), FALSE);
789
790   if (tp_connection_get_status (connection, NULL) !=
791           TP_CONNECTION_STATUS_CONNECTED)
792       return FALSE;
793
794   retval = check_writeable_property (connection, individual, "alias");
795
796   return retval;
797 }
798
799 gboolean
800 empathy_connection_can_group_personas (TpConnection *connection,
801                                        FolksIndividual *individual)
802 {
803   gboolean retval;
804
805   g_return_val_if_fail (TP_IS_CONNECTION (connection), FALSE);
806
807   if (tp_connection_get_status (connection, NULL) !=
808           TP_CONNECTION_STATUS_CONNECTED)
809       return FALSE;
810
811   retval = check_writeable_property (connection, individual, "groups");
812
813   return retval;
814 }
815
816 gboolean
817 empathy_folks_persona_is_interesting (FolksPersona *persona)
818 {
819   /* We're not interested in non-Telepathy personas */
820   if (!TPF_IS_PERSONA (persona))
821     return FALSE;
822
823   /* We're not interested in user personas which haven't been added to the
824    * contact list (see bgo#637151). */
825   if (folks_persona_get_is_user (persona) &&
826       !tpf_persona_get_is_in_contact_list (TPF_PERSONA (persona)))
827     {
828       return FALSE;
829     }
830
831   return TRUE;
832 }
833
834 gchar *
835 empathy_get_x509_certificate_hostname (gnutls_x509_crt_t cert)
836 {
837   gchar dns_name[256];
838   gsize dns_name_size;
839   gint idx;
840   gint res = 0;
841
842   /* this snippet is taken from GnuTLS.
843    * see gnutls/lib/x509/rfc2818_hostname.c
844    */
845   for (idx = 0; res >= 0; idx++)
846     {
847       dns_name_size = sizeof (dns_name);
848       res = gnutls_x509_crt_get_subject_alt_name (cert, idx,
849           dns_name, &dns_name_size, NULL);
850
851       if (res == GNUTLS_SAN_DNSNAME || res == GNUTLS_SAN_IPADDRESS)
852         return g_strndup (dns_name, dns_name_size);
853     }
854
855   dns_name_size = sizeof (dns_name);
856   res = gnutls_x509_crt_get_dn_by_oid (cert, GNUTLS_OID_X520_COMMON_NAME,
857       0, 0, dns_name, &dns_name_size);
858
859   if (res >= 0)
860     return g_strndup (dns_name, dns_name_size);
861
862   return NULL;
863 }
864
865 gchar *
866 empathy_format_currency (gint amount,
867     guint scale,
868     const gchar *currency)
869 {
870 #define MINUS "\342\210\222"
871 #define EURO "\342\202\254"
872 #define YEN "\302\245"
873 #define POUND "\302\243"
874
875   /* localised representations of currency */
876   /* FIXME: check these, especially negatives and decimals */
877   static const struct {
878     const char *currency;
879     const char *positive;
880     const char *negative;
881     const char *decimal;
882   } currencies[] = {
883     /* sym   positive    negative          decimal */
884     { "EUR", EURO "%s",  MINUS EURO "%s",  "." },
885     { "USD", "$%s",      MINUS "$%s",      "." },
886     { "JPY", YEN "%s"    MINUS YEN "%s",   "." },
887     { "GBP", POUND "%s", MINUS POUND "%s", "." },
888     { "PLN", "%s zl",    MINUS "%s zl",    "." },
889     { "BRL", "R$%s",     MINUS "R$%s",     "." },
890     { "SEK", "%s kr",    MINUS "%s kr",    "." },
891     { "DKK", "kr %s",    "kr " MINUS "%s", "." },
892     { "HKD", "$%s",      MINUS "$%s",      "." },
893     { "CHF", "%s Fr.",   MINUS "%s Fr.",   "." },
894     { "NOK", "kr %s",    "kr" MINUS "%s",  "," },
895     { "CAD", "$%s",      MINUS "$%s",      "." },
896     { "TWD", "$%s",      MINUS "$%s",      "." },
897     { "AUD", "$%s",      MINUS "$%s",      "." },
898   };
899
900   const char *positive = "%s";
901   const char *negative = MINUS "%s";
902   const char *decimal = ".";
903   char *fmt_amount, *money;
904   guint i;
905
906   /* get the localised currency format */
907   for (i = 0; i < G_N_ELEMENTS (currencies); i++)
908     {
909       if (!tp_strdiff (currency, currencies[i].currency))
910         {
911           positive = currencies[i].positive;
912           negative = currencies[i].negative;
913           decimal = currencies[i].decimal;
914           break;
915         }
916     }
917
918   /* format the amount using the scale */
919   if (scale == 0)
920     {
921       /* no decimal point required */
922       fmt_amount = g_strdup_printf ("%d", amount);
923     }
924   else
925     {
926       /* don't use floating point arithmatic, it's noisy;
927        * we take the absolute values, because we want the minus
928        * sign to appear before the $ */
929       int divisor = pow (10, scale);
930       int dollars = abs (amount / divisor);
931       int cents = abs (amount % divisor);
932
933       fmt_amount = g_strdup_printf ("%d%s%0*d",
934         dollars, decimal, scale, cents);
935     }
936
937   money = g_strdup_printf (amount < 0 ? negative : positive, fmt_amount);
938   g_free (fmt_amount);
939
940   return money;
941 }
942
943 gboolean
944 empathy_account_has_uri_scheme_tel (TpAccount *account)
945 {
946   const gchar * const * uri_schemes;
947   guint i;
948
949   uri_schemes = tp_account_get_uri_schemes (account);
950   if (uri_schemes == NULL)
951     return FALSE;
952
953   for (i = 0; uri_schemes[i] != NULL; i++)
954     {
955       if (!tp_strdiff (uri_schemes[i], "tel"))
956         return TRUE;
957     }
958
959   return FALSE;
960 }
961
962 /* Return the TpContact on @conn associated with @individual, if any */
963 TpContact *
964 empathy_get_tp_contact_for_individual (FolksIndividual *individual,
965     TpConnection *conn)
966 {
967   TpContact *contact = NULL;
968   GeeSet *personas;
969   GeeIterator *iter;
970
971   personas = folks_individual_get_personas (individual);
972   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
973   while (contact == NULL && gee_iterator_next (iter))
974     {
975       TpfPersona *persona = gee_iterator_get (iter);
976       TpConnection *contact_conn;
977       TpContact *contact_cur = NULL;
978
979       if (TPF_IS_PERSONA (persona))
980         {
981           contact_cur = tpf_persona_get_contact (persona);
982           if (contact_cur != NULL)
983             {
984               contact_conn = tp_contact_get_connection (contact_cur);
985
986               if (!tp_strdiff (tp_proxy_get_object_path (contact_conn),
987                     tp_proxy_get_object_path (conn)))
988                 contact = contact_cur;
989             }
990         }
991
992       g_clear_object (&persona);
993     }
994   g_clear_object (&iter);
995
996   return contact;
997 }
998
999 static gboolean
1000 properties_contains (gchar **list,
1001                      gint length,
1002                      const gchar *property)
1003 {
1004   gint i;
1005
1006   for (i = 0; i < length; i++)
1007     {
1008       if (!tp_strdiff (list[i], property))
1009         return TRUE;
1010     }
1011
1012   return FALSE;
1013 }
1014
1015 static gboolean
1016 check_writeable_property (TpConnection *connection,
1017                           FolksIndividual *individual,
1018                           gchar *property)
1019 {
1020   gchar **properties;
1021   gint prop_len;
1022   gboolean retval = FALSE;
1023   GeeSet *personas;
1024   GeeIterator *iter;
1025   FolksPersonaStore *persona_store;
1026
1027   persona_store = FOLKS_PERSONA_STORE (
1028       empathy_dup_persona_store_for_connection (connection));
1029
1030   properties =
1031     folks_persona_store_get_always_writeable_properties (persona_store,
1032                                                          &prop_len);
1033   retval = properties_contains (properties, prop_len, property);
1034   if (retval == TRUE)
1035     goto out;
1036
1037   /* Lets see if the Individual contains a Persona with the given property */
1038   personas = folks_individual_get_personas (individual);
1039   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
1040   while (!retval && gee_iterator_next (iter))
1041     {
1042       FolksPersona *persona = gee_iterator_get (iter);
1043
1044       properties =
1045         folks_persona_get_writeable_properties (persona, &prop_len);
1046       retval = properties_contains (properties, prop_len, property);
1047
1048       g_clear_object (&persona);
1049
1050       if (retval == TRUE)
1051         break;
1052     }
1053   g_clear_object (&iter);
1054
1055 out:
1056   g_clear_object (&persona_store);
1057   return retval;
1058 }
1059
1060 /* Calculate whether the Individual can do audio or video calls.
1061  * FIXME: We can remove this once libfolks has grown capabilities support
1062  * again: bgo#626179. */
1063 void
1064 empathy_individual_can_audio_video_call (FolksIndividual *individual,
1065     gboolean *can_audio_call,
1066     gboolean *can_video_call,
1067     EmpathyContact **out_contact)
1068 {
1069   GeeSet *personas;
1070   GeeIterator *iter;
1071   gboolean can_audio = FALSE, can_video = FALSE;
1072
1073   personas = folks_individual_get_personas (individual);
1074   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
1075   while (gee_iterator_next (iter))
1076     {
1077       FolksPersona *persona = gee_iterator_get (iter);
1078       TpContact *tp_contact;
1079
1080       if (!empathy_folks_persona_is_interesting (persona))
1081         goto while_finish;
1082
1083       tp_contact = tpf_persona_get_contact (TPF_PERSONA (persona));
1084       if (tp_contact != NULL)
1085         {
1086           EmpathyContact *contact;
1087
1088           contact = empathy_contact_dup_from_tp_contact (tp_contact);
1089           empathy_contact_set_persona (contact, persona);
1090
1091           can_audio = can_audio || empathy_contact_get_capabilities (contact) &
1092               EMPATHY_CAPABILITIES_AUDIO;
1093           can_video = can_video || empathy_contact_get_capabilities (contact) &
1094               EMPATHY_CAPABILITIES_VIDEO;
1095
1096           if (out_contact != NULL)
1097             *out_contact = g_object_ref (contact);
1098
1099           g_object_unref (contact);
1100         }
1101
1102 while_finish:
1103       g_clear_object (&persona);
1104
1105       if (can_audio && can_video)
1106         break;
1107     }
1108
1109   g_clear_object (&iter);
1110
1111   if (can_audio_call != NULL)
1112     *can_audio_call = can_audio;
1113
1114   if (can_video_call != NULL)
1115     *can_video_call = can_video;
1116 }
1117
1118 static FolksIndividual *
1119 create_individual_from_persona (FolksPersona *persona)
1120 {
1121   GeeSet *personas;
1122   FolksIndividual *individual;
1123
1124   personas = GEE_SET (
1125       gee_hash_set_new (FOLKS_TYPE_PERSONA, g_object_ref, g_object_unref,
1126       g_direct_hash, g_direct_equal));
1127
1128   gee_collection_add (GEE_COLLECTION (personas), persona);
1129
1130   individual = folks_individual_new (personas);
1131
1132   g_clear_object (&personas);
1133
1134   return individual;
1135 }
1136
1137 FolksIndividual *
1138 empathy_create_individual_from_tp_contact (TpContact *contact)
1139 {
1140   TpfPersona *persona;
1141   FolksIndividual *individual;
1142
1143   persona = tpf_persona_dup_for_contact (contact);
1144   if (persona == NULL)
1145     {
1146       DEBUG ("Failed to get a persona for %s",
1147           tp_contact_get_identifier (contact));
1148       return NULL;
1149     }
1150
1151   individual = create_individual_from_persona (FOLKS_PERSONA (persona));
1152
1153   g_object_unref (persona);
1154   return individual;
1155 }
1156
1157 /* Look for a FolksIndividual containing @contact as one of his persona
1158  * and create one if needed */
1159 FolksIndividual *
1160 empathy_ensure_individual_from_tp_contact (TpContact *contact)
1161 {
1162   TpfPersona *persona;
1163   FolksIndividual *individual;
1164
1165   persona = tpf_persona_dup_for_contact (contact);
1166   if (persona == NULL)
1167     {
1168       DEBUG ("Failed to get a persona for %s",
1169           tp_contact_get_identifier (contact));
1170       return NULL;
1171     }
1172
1173   individual = folks_persona_get_individual (FOLKS_PERSONA (persona));
1174
1175   if (individual != NULL)
1176     g_object_ref (individual);
1177   else
1178     individual = create_individual_from_persona (FOLKS_PERSONA (persona));
1179
1180   g_object_unref (persona);
1181   return individual;
1182 }
1183
1184 const gchar * const *
1185 empathy_individual_get_client_types (FolksIndividual *individual)
1186 {
1187   GeeSet *personas;
1188   GeeIterator *iter;
1189   const gchar * const *types = NULL;
1190   FolksPresenceType presence_type = FOLKS_PRESENCE_TYPE_UNSET;
1191
1192   personas = folks_individual_get_personas (individual);
1193   iter = gee_iterable_iterator (GEE_ITERABLE (personas));
1194   while (gee_iterator_next (iter))
1195     {
1196       FolksPresenceDetails *presence;
1197       FolksPersona *persona = gee_iterator_get (iter);
1198
1199       /* We only want personas which have presence and a TpContact */
1200       if (!empathy_folks_persona_is_interesting (persona))
1201         goto while_finish;
1202
1203       presence = FOLKS_PRESENCE_DETAILS (persona);
1204
1205       if (folks_presence_details_typecmp (
1206               folks_presence_details_get_presence_type (presence),
1207               presence_type) > 0)
1208         {
1209           TpContact *tp_contact;
1210
1211           presence_type = folks_presence_details_get_presence_type (presence);
1212
1213           tp_contact = tpf_persona_get_contact (TPF_PERSONA (persona));
1214           if (tp_contact != NULL)
1215             types = tp_contact_get_client_types (tp_contact);
1216         }
1217
1218 while_finish:
1219       g_clear_object (&persona);
1220     }
1221   g_clear_object (&iter);
1222
1223   return types;
1224 }
1225
1226 GVariant *
1227 empathy_asv_to_vardict (const GHashTable *asv)
1228 {
1229   return empathy_boxed_to_variant (TP_HASH_TYPE_STRING_VARIANT_MAP, "a{sv}",
1230       (gpointer) asv);
1231 }
1232
1233 GVariant *
1234 empathy_boxed_to_variant (GType gtype,
1235     const gchar *variant_type,
1236     gpointer boxed)
1237 {
1238   GValue v = G_VALUE_INIT;
1239   GVariant *ret;
1240
1241   g_return_val_if_fail (boxed != NULL, NULL);
1242
1243   g_value_init (&v, gtype);
1244   g_value_set_boxed (&v, boxed);
1245
1246   ret = dbus_g_value_build_g_variant (&v);
1247   g_return_val_if_fail (!tp_strdiff (g_variant_get_type_string (ret),
1248         variant_type), NULL);
1249
1250   g_value_unset (&v);
1251
1252   return g_variant_ref_sink (ret);
1253 }