]> git.0d.be Git - empathy.git/blob - libempathy/empathy-utils.c
Merge commit 'sjoerd/master'
[empathy.git] / libempathy / empathy-utils.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2003-2007 Imendio AB
4  * Copyright (C) 2007 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  *
21  * Authors: Richard Hult <richard@imendio.com>
22  *          Martyn Russell <martyn@imendio.com>
23  *          Xavier Claessens <xclaesse@gmail.com>
24  */
25
26 #include "config.h"
27
28 #include <string.h>
29 #include <time.h>
30 #include <sys/types.h>
31 #include <regex.h>
32
33 #include <glib/gi18n.h>
34
35 #include <libxml/uri.h>
36 #include <libtelepathy/tp-helpers.h>
37
38 #include "empathy-debug.h"
39 #include "empathy-utils.h"
40 #include "empathy-contact-factory.h"
41 #include "empathy-contact-manager.h"
42 #include "empathy-tp-group.h"
43
44 #define DEBUG_DOMAIN "Utils"
45
46 static void regex_init (void);
47
48 gchar *
49 empathy_substring (const gchar *str,
50                   gint         start,
51                   gint         end)
52 {
53         return g_strndup (str + start, end - start);
54 }
55
56 /*
57  * Regular Expression code to match urls.
58  */
59 #define USERCHARS "-A-Za-z0-9"
60 #define PASSCHARS "-A-Za-z0-9,?;.:/!%$^*&~\"#'"
61 #define HOSTCHARS "-A-Za-z0-9"
62 #define PATHCHARS "-A-Za-z0-9_$.+!*(),;:@&=?/~#%"
63 #define SCHEME    "(news:|telnet:|nntp:|file:/|https?:|ftps?:|webcal:)"
64 #define USER      "[" USERCHARS "]+(:["PASSCHARS "]+)?"
65 #define URLPATH   "/[" PATHCHARS "]*[^]'.}>) \t\r\n,\\\"]"
66
67 static regex_t dingus[EMPATHY_REGEX_ALL];
68
69 static void
70 regex_init (void)
71 {
72         static gboolean  inited = FALSE;
73         const gchar     *expression;
74         gint             i;
75
76         if (inited) {
77                 return;
78         }
79
80         for (i = 0; i < EMPATHY_REGEX_ALL; i++) {
81                 switch (i) {
82                 case EMPATHY_REGEX_AS_IS:
83                         expression =
84                                 SCHEME "//(" USER "@)?[" HOSTCHARS ".]+"
85                                 "(:[0-9]+)?(" URLPATH ")?";
86                         break;
87                 case EMPATHY_REGEX_BROWSER:
88                         expression =
89                                 "(www|ftp)[" HOSTCHARS "]*\\.[" HOSTCHARS ".]+"
90                                 "(:[0-9]+)?(" URLPATH ")?";
91                         break;
92                 case EMPATHY_REGEX_EMAIL:
93                         expression =
94                                 "(mailto:)?[a-z0-9][a-z0-9.-]*@[a-z0-9]"
95                                 "[a-z0-9-]*(\\.[a-z0-9][a-z0-9-]*)+";
96                         break;
97                 case EMPATHY_REGEX_OTHER:
98                         expression =
99                                 "news:[-A-Z\\^_a-z{|}~!\"#$%&'()*+,./0-9;:=?`]+"
100                                 "@[" HOSTCHARS ".]+(:[0-9]+)?";
101                         break;
102                 default:
103                         /* Silence the compiler. */
104                         expression = NULL;
105                         continue;
106                 }
107
108                 memset (&dingus[i], 0, sizeof (regex_t));
109                 regcomp (&dingus[i], expression, REG_EXTENDED | REG_ICASE);
110         }
111
112         inited = TRUE;
113 }
114
115 gint
116 empathy_regex_match (EmpathyRegExType  type,
117                     const gchar     *msg,
118                     GArray          *start,
119                     GArray          *end)
120 {
121         regmatch_t matches[1];
122         gint       ret = 0;
123         gint       num_matches = 0;
124         gint       offset = 0;
125         gint       i;
126
127         g_return_val_if_fail (type >= 0 || type <= EMPATHY_REGEX_ALL, 0);
128
129         regex_init ();
130
131         while (!ret && type != EMPATHY_REGEX_ALL) {
132                 ret = regexec (&dingus[type], msg + offset, 1, matches, 0);
133                 if (ret == 0) {
134                         gint s;
135
136                         num_matches++;
137
138                         s = matches[0].rm_so + offset;
139                         offset = matches[0].rm_eo + offset;
140
141                         g_array_append_val (start, s);
142                         g_array_append_val (end, offset);
143                 }
144         }
145
146         if (type != EMPATHY_REGEX_ALL) {
147                 empathy_debug (DEBUG_DOMAIN,
148                               "Found %d matches for regex type:%d",
149                               num_matches, type);
150                 return num_matches;
151         }
152
153         /* If EMPATHY_REGEX_ALL then we run ALL regex's on the string. */
154         for (i = 0; i < EMPATHY_REGEX_ALL; i++, ret = 0) {
155                 while (!ret) {
156                         ret = regexec (&dingus[i], msg + offset, 1, matches, 0);
157                         if (ret == 0) {
158                                 gint s;
159
160                                 num_matches++;
161
162                                 s = matches[0].rm_so + offset;
163                                 offset = matches[0].rm_eo + offset;
164
165                                 g_array_append_val (start, s);
166                                 g_array_append_val (end, offset);
167                         }
168                 }
169         }
170
171         empathy_debug (DEBUG_DOMAIN,
172                       "Found %d matches for ALL regex types",
173                       num_matches);
174
175         return num_matches;
176 }
177
178 gint
179 empathy_strcasecmp (const gchar *s1,
180                    const gchar *s2)
181 {
182         return empathy_strncasecmp (s1, s2, -1);
183 }
184
185 gint
186 empathy_strncasecmp (const gchar *s1,
187                     const gchar *s2,
188                     gsize        n)
189 {
190         gchar *u1, *u2;
191         gint   ret_val;
192
193         u1 = g_utf8_casefold (s1, n);
194         u2 = g_utf8_casefold (s2, n);
195
196         ret_val = g_utf8_collate (u1, u2);
197         g_free (u1);
198         g_free (u2);
199
200         return ret_val;
201 }
202
203 gboolean
204 empathy_xml_validate (xmlDoc      *doc,
205                      const gchar *dtd_filename)
206 {
207         gchar        *path, *escaped;
208         xmlValidCtxt  cvp;
209         xmlDtd       *dtd;
210         gboolean      ret;
211
212         path = g_build_filename (UNINSTALLED_DTD_DIR, dtd_filename, NULL);
213         if (!g_file_test (path, G_FILE_TEST_EXISTS)) {
214                 g_free (path);
215                 path = g_build_filename (DATADIR, "empathy", dtd_filename, NULL);
216         }
217         empathy_debug (DEBUG_DOMAIN, "Loading dtd file %s", path);
218
219         /* The list of valid chars is taken from libxml. */
220         escaped = xmlURIEscapeStr (path, ":@&=+$,/?;");
221         g_free (path);
222
223         memset (&cvp, 0, sizeof (cvp));
224         dtd = xmlParseDTD (NULL, escaped);
225         ret = xmlValidateDtd (&cvp, doc, dtd);
226
227         xmlFree (escaped);
228         xmlFreeDtd (dtd);
229
230         return ret;
231 }
232
233 xmlNodePtr
234 empathy_xml_node_get_child (xmlNodePtr   node, 
235                            const gchar *child_name)
236 {
237         xmlNodePtr l;
238
239         g_return_val_if_fail (node != NULL, NULL);
240         g_return_val_if_fail (child_name != NULL, NULL);
241
242         for (l = node->children; l; l = l->next) {
243                 if (l->name && strcmp (l->name, child_name) == 0) {
244                         return l;
245                 }
246         }
247
248         return NULL;
249 }
250
251 xmlChar *
252 empathy_xml_node_get_child_content (xmlNodePtr   node, 
253                                    const gchar *child_name)
254 {
255         xmlNodePtr l;
256
257         g_return_val_if_fail (node != NULL, NULL);
258         g_return_val_if_fail (child_name != NULL, NULL);
259
260         l = empathy_xml_node_get_child (node, child_name);
261         if (l) {
262                 return xmlNodeGetContent (l);
263         }
264                 
265         return NULL;
266 }
267
268 xmlNodePtr
269 empathy_xml_node_find_child_prop_value (xmlNodePtr   node, 
270                                        const gchar *prop_name,
271                                        const gchar *prop_value)
272 {
273         xmlNodePtr l;
274         xmlNodePtr found = NULL;
275
276         g_return_val_if_fail (node != NULL, NULL);
277         g_return_val_if_fail (prop_name != NULL, NULL);
278         g_return_val_if_fail (prop_value != NULL, NULL);
279
280         for (l = node->children; l && !found; l = l->next) {
281                 xmlChar *prop;
282
283                 if (!xmlHasProp (l, prop_name)) {
284                         continue;
285                 }
286
287                 prop = xmlGetProp (l, prop_name);
288                 if (prop && strcmp (prop, prop_value) == 0) {
289                         found = l;
290                 }
291                 
292                 xmlFree (prop);
293         }
294                 
295         return found;
296 }
297
298 guint
299 empathy_account_hash (gconstpointer key)
300 {
301         g_return_val_if_fail (MC_IS_ACCOUNT (key), 0);
302
303         return g_str_hash (mc_account_get_unique_name (MC_ACCOUNT (key)));
304 }
305
306 gboolean
307 empathy_account_equal (gconstpointer a,
308                        gconstpointer b)
309 {
310         const gchar *name_a;
311         const gchar *name_b;
312
313         g_return_val_if_fail (MC_IS_ACCOUNT (a), FALSE);
314         g_return_val_if_fail (MC_IS_ACCOUNT (b), FALSE);
315
316         name_a = mc_account_get_unique_name (MC_ACCOUNT (a));
317         name_b = mc_account_get_unique_name (MC_ACCOUNT (b));
318
319         return g_str_equal (name_a, name_b);
320 }
321
322 MissionControl *
323 empathy_mission_control_new (void)
324 {
325         static MissionControl *mc = NULL;
326
327         if (!mc) {
328                 mc = mission_control_new (tp_get_bus ());
329                 g_object_add_weak_pointer (G_OBJECT (mc), (gpointer) &mc);
330         } else {
331                 g_object_ref (mc);
332         }
333
334         return mc;
335 }
336
337 gchar *
338 empathy_inspect_channel (McAccount *account,
339                          TpChan    *tp_chan)
340 {
341         g_return_val_if_fail (MC_IS_ACCOUNT (account), NULL);
342         g_return_val_if_fail (TELEPATHY_IS_CHAN (tp_chan), NULL);
343
344         return empathy_inspect_handle (account,
345                                        tp_chan->handle,
346                                        tp_chan->handle_type);
347 }
348
349 gchar *
350 empathy_inspect_handle (McAccount *account,
351                         guint      handle,
352                         guint      handle_type)
353 {
354         MissionControl  *mc;
355         TpConn          *tp_conn;
356         GArray          *handles;
357         gchar          **names;
358         gchar           *name;
359         GError          *error = NULL;
360
361         g_return_val_if_fail (MC_IS_ACCOUNT (account), NULL);
362         g_return_val_if_fail (handle != 0, NULL);
363         g_return_val_if_fail (handle_type != 0, NULL);
364
365         mc = empathy_mission_control_new ();
366         tp_conn = mission_control_get_connection (mc, account, NULL);
367         g_object_unref (mc);
368
369         if (!tp_conn) {
370                 return NULL;
371         }
372
373         /* Get the handle's name */
374         handles = g_array_new (FALSE, FALSE, sizeof (guint));
375         g_array_append_val (handles, handle);
376         if (!tp_conn_inspect_handles (DBUS_G_PROXY (tp_conn),
377                                       handle_type,
378                                       handles,
379                                       &names,
380                                       &error)) {
381                 empathy_debug (DEBUG_DOMAIN, 
382                               "Couldn't get id: %s",
383                               error ? error->message : "No error given");
384
385                 g_clear_error (&error);
386                 g_array_free (handles, TRUE);
387                 g_object_unref (tp_conn);
388                 
389                 return NULL;
390         }
391
392         g_array_free (handles, TRUE);
393         name = *names;
394         g_free (names);
395         g_object_unref (tp_conn);
396
397         return name;
398 }
399
400 void
401 empathy_call_with_contact (EmpathyContact *contact)
402 {
403 #ifdef HAVE_VOIP
404         MissionControl        *mc;
405         McAccount             *account;
406         TpConn                *tp_conn;
407         gchar                 *object_path;
408         const gchar           *bus_name;
409         TpChan                *new_chan;
410         EmpathyContactFactory *factory;
411         EmpathyTpGroup        *group;
412         EmpathyContact        *self_contact;
413         GError                *error = NULL;
414
415         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
416
417         /* StreamedMedia channels must have handle=0 and handle_type=none.
418          * To call a contact we have to add him in the group interface of the
419          * channel. MissionControl will detect the channel creation and 
420          * dispatch it to the VoIP chandler automatically. */
421
422         mc = empathy_mission_control_new ();
423         account = empathy_contact_get_account (contact);
424         tp_conn = mission_control_get_connection (mc, account, NULL);
425         /* FIXME: Should be async */
426         if (!tp_conn_request_channel (DBUS_G_PROXY (tp_conn),
427                                       TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
428                                       TP_HANDLE_TYPE_NONE,
429                                       0,
430                                       FALSE,
431                                       &object_path,
432                                       &error)) {
433                 empathy_debug (DEBUG_DOMAIN, 
434                               "Couldn't request channel: %s",
435                               error ? error->message : "No error given");
436                 g_clear_error (&error);
437                 g_object_unref (mc);
438                 g_object_unref (tp_conn);
439                 return;
440         }
441
442         bus_name = dbus_g_proxy_get_bus_name (DBUS_G_PROXY (tp_conn));
443         new_chan = tp_chan_new (tp_get_bus (),
444                                 bus_name,
445                                 object_path,
446                                 TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
447                                 TP_HANDLE_TYPE_NONE,
448                                 0);
449
450         group = empathy_tp_group_new (account, new_chan);
451         factory = empathy_contact_factory_new ();
452         self_contact = empathy_contact_factory_get_user (factory, account);
453         empathy_tp_group_add_member (group, contact, "");
454         empathy_tp_group_add_member (group, self_contact, "");  
455
456         g_object_unref (factory);
457         g_object_unref (self_contact);
458         g_object_unref (group);
459         g_object_unref (mc);
460         g_object_unref (tp_conn);
461         g_object_unref (new_chan);
462         g_free (object_path);
463 #endif
464 }
465
466 #ifdef HAVE_VOIP
467 struct empathy_call_cb_user_data {
468         guint handler;
469         GObject *factory;
470 };
471
472 static void
473 empathy_call_with_contact_id_got_handle_cb (EmpathyContact *contact, 
474   GParamSpec *property, gpointer user_data) {
475
476         struct empathy_call_cb_user_data *ud =
477                 (struct empathy_call_cb_user_data *) user_data;
478
479         g_signal_handler_disconnect (contact, ud->handler);
480
481         empathy_call_with_contact (contact);
482         g_object_unref (ud->factory);
483         g_object_unref (contact);
484         g_free (ud);
485 }
486 #endif
487
488 void
489 empathy_call_with_contact_id (McAccount *account, const gchar *contact_id)
490 {
491 #ifdef HAVE_VOIP
492         EmpathyContactFactory *factory;
493         EmpathyContact        *contact;
494
495         factory = empathy_contact_factory_new ();
496         contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
497
498         if (empathy_contact_get_handle (contact) != 0) {
499                 empathy_call_with_contact (contact);
500                 g_object_unref (contact);
501                 g_object_unref (factory);
502         } else {
503                 struct empathy_call_cb_user_data *ud;
504                 ud = g_malloc0 (sizeof (struct empathy_call_cb_user_data));
505                 ud->factory = G_OBJECT (factory);
506                 ud->handler = g_signal_connect (G_OBJECT (contact), "notify::handle",
507                         G_CALLBACK (empathy_call_with_contact_id_got_handle_cb), ud);
508         }
509
510 #endif
511 }
512
513 void
514 empathy_chat_with_contact (EmpathyContact  *contact)
515 {
516         MissionControl *mc;
517
518         mc = empathy_mission_control_new ();
519         mission_control_request_channel (mc,
520                                          empathy_contact_get_account (contact),
521                                          TP_IFACE_CHANNEL_TYPE_TEXT,
522                                          empathy_contact_get_handle (contact),
523                                          TP_HANDLE_TYPE_CONTACT,
524                                          NULL, NULL);
525         g_object_unref (mc);
526 }
527
528 void
529 empathy_chat_with_contact_id (McAccount *account, const gchar *contact_id)
530 {
531         MissionControl *mc;
532
533         mc = empathy_mission_control_new ();
534         mission_control_request_channel_with_string_handle (mc,
535                                                             account,
536                                                             TP_IFACE_CHANNEL_TYPE_TEXT,
537                                                             contact_id,
538                                                             TP_HANDLE_TYPE_CONTACT,
539                                                             NULL, NULL);
540         g_object_unref (mc);
541 }
542
543 const gchar *
544 empathy_presence_get_default_message (McPresence presence)
545 {
546         switch (presence) {
547         case MC_PRESENCE_AVAILABLE:
548                 return _("Available");
549         case MC_PRESENCE_DO_NOT_DISTURB:
550                 return _("Busy");
551         case MC_PRESENCE_AWAY:
552         case MC_PRESENCE_EXTENDED_AWAY:
553                 return _("Away");
554         case MC_PRESENCE_HIDDEN:
555                 return _("Hidden");
556         case MC_PRESENCE_OFFLINE:
557         case MC_PRESENCE_UNSET:
558                 return _("Offline");
559         default:
560                 g_assert_not_reached ();
561         }
562
563         return NULL;
564 }
565
566 const gchar *
567 empathy_presence_to_str (McPresence presence)
568 {
569         switch (presence) {
570         case MC_PRESENCE_AVAILABLE:
571                 return "available";
572         case MC_PRESENCE_DO_NOT_DISTURB:
573                 return "busy";
574         case MC_PRESENCE_AWAY:
575                 return "away";
576         case MC_PRESENCE_EXTENDED_AWAY:
577                 return "ext_away";
578         case MC_PRESENCE_HIDDEN:
579                 return "hidden";
580         case MC_PRESENCE_OFFLINE:
581                 return "offline";
582         case MC_PRESENCE_UNSET:
583                 return "unset";
584         default:
585                 g_assert_not_reached ();
586         }
587
588         return NULL;
589 }
590
591 McPresence
592 empathy_presence_from_str (const gchar *str)
593 {
594         if (strcmp (str, "available") == 0) {
595                 return MC_PRESENCE_AVAILABLE;
596         } else if ((strcmp (str, "dnd") == 0) || (strcmp (str, "busy") == 0)) {
597                 return MC_PRESENCE_DO_NOT_DISTURB;
598         } else if ((strcmp (str, "away") == 0) || (strcmp (str, "brb") == 0)) {
599                 return MC_PRESENCE_AWAY;
600         } else if ((strcmp (str, "xa") == 0) || (strcmp (str, "ext_away") == 0)) {
601                 return MC_PRESENCE_EXTENDED_AWAY;
602         } else if (strcmp (str, "hidden") == 0) {
603                 return MC_PRESENCE_HIDDEN;
604         } else if (strcmp (str, "offline") == 0) {
605                 return MC_PRESENCE_OFFLINE;
606         } else if (strcmp (str, "unset") == 0) {
607                 return MC_PRESENCE_UNSET;
608         }
609
610         return MC_PRESENCE_AVAILABLE;
611 }
612