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