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