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