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