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