]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
Merge branch 'requests'. Fixes: #598905
[empathy.git] / libempathy / empathy-dispatcher.c
1 /* * Copyright (C) 2007-2009 Collabora Ltd.
2  *
3  * This library is free software; you can redistribute it and/or
4  * modify it under the terms of the GNU Lesser General Public
5  * License as published by the Free Software Foundation; either
6  * version 2.1 of the License, or (at your option) any later version.
7  *
8  * This library is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public
14  * License along with this library; if not, write to the Free Software
15  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
16  *
17  * Authors: Xavier Claessens <xclaesse@gmail.com>
18  *          Sjoerd Simons <sjoerd.simons@collabora.co.uk>
19  *          Cosimo Cecchi <cosimo.cecchi@collabora.co.uk>
20  */
21
22 #define DISPATCHER_BUS_NAME TP_CLIENT_BUS_NAME_BASE "Empathy"
23 #define DISPATCHER_OBJECT_PATH TP_CLIENT_OBJECT_PATH_BASE "Empathy"
24
25 #include <config.h>
26
27 #include <string.h>
28
29 #include <glib/gi18n-lib.h>
30
31 #include <telepathy-glib/account-manager.h>
32 #include <telepathy-glib/enums.h>
33 #include <telepathy-glib/connection.h>
34 #include <telepathy-glib/channel-dispatcher.h>
35 #include <telepathy-glib/channel-request.h>
36 #include <telepathy-glib/util.h>
37 #include <telepathy-glib/dbus.h>
38 #include <telepathy-glib/proxy-subclass.h>
39 #include <telepathy-glib/gtypes.h>
40 #include <telepathy-glib/defs.h>
41 #include <telepathy-glib/svc-client.h>
42 #include <telepathy-glib/svc-generic.h>
43 #include <telepathy-glib/interfaces.h>
44
45 #include <extensions/extensions.h>
46
47 #include "empathy-dispatcher.h"
48 #include "empathy-handler.h"
49 #include "empathy-utils.h"
50 #include "empathy-tp-contact-factory.h"
51 #include "empathy-chatroom-manager.h"
52 #include "empathy-utils.h"
53
54 #define DEBUG_FLAG EMPATHY_DEBUG_DISPATCHER
55 #include <libempathy/empathy-debug.h>
56
57 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyDispatcher)
58 typedef struct
59 {
60   gboolean dispose_has_run;
61
62   TpAccountManager *account_manager;
63   /* connection to connection data mapping */
64   GHashTable *connections;
65   GHashTable *outstanding_classes_requests;
66   gpointer token;
67
68   /* channels which the dispatcher is listening "invalidated" */
69   GList *channels;
70   GPtrArray *array;
71
72   /* main handler */
73   EmpathyHandler *handler;
74
75   /* extra handlers */
76   GList *handlers;
77
78   GHashTable *request_channel_class_async_ids;
79   /* (TpAccount *) => gulong
80    * Signal handler ID of the "status-changed" signal */
81   GHashTable *status_changed_handlers;
82
83   TpChannelDispatcher *channel_dispatcher;
84   TpDBusDaemon *dbus;
85 } EmpathyDispatcherPriv;
86
87 static GList *
88 empathy_dispatcher_get_channels (EmpathyHandler *handler,
89     gpointer user_data);
90
91 static gboolean
92 empathy_dispatcher_handle_channels (EmpathyHandler *handler,
93     const gchar *account_path,
94     const gchar *connection_path,
95     const GPtrArray *channels,
96     const GPtrArray *requests_satisfied,
97     guint64 timestamp,
98     GHashTable *handler_info,
99     gpointer user_data,
100     GError **error);
101
102 G_DEFINE_TYPE (EmpathyDispatcher, empathy_dispatcher, G_TYPE_OBJECT);
103
104 enum
105 {
106   PROP_INTERFACES = 1,
107   PROP_HANDLER,
108 };
109
110 enum
111 {
112   OBSERVE,
113   APPROVE,
114   DISPATCH,
115   LAST_SIGNAL
116 };
117
118 static guint signals[LAST_SIGNAL];
119 static EmpathyDispatcher *dispatcher = NULL;
120
121 static void dispatcher_init_connection_if_needed (
122     EmpathyDispatcher *dispatcher,
123     TpConnection *connection);
124
125 static GList * empathy_dispatcher_find_channel_classes
126   (EmpathyDispatcher *dispatcher, TpConnection *connection,
127    const gchar *channel_type, guint handle_type, GArray *fixed_properties);
128
129
130 typedef struct
131 {
132   EmpathyDispatcher *dispatcher;
133   EmpathyDispatchOperation *operation;
134   TpConnection *connection;
135   gboolean should_ensure;
136   gchar *channel_type;
137   guint handle_type;
138   guint handle;
139   EmpathyContact *contact;
140   TpProxyPendingCall *pending_call;
141
142   /* Properties to pass to the channel when requesting it */
143   GHashTable *request;
144   EmpathyDispatcherRequestCb *cb;
145   gpointer user_data;
146   gpointer *request_data;
147
148   TpChannelRequest *channel_request;
149 } DispatcherRequestData;
150
151 typedef struct
152 {
153   TpChannel *channel;
154   /* Channel type specific wrapper object */
155   GObject *channel_wrapper;
156 } DispatchData;
157
158 typedef struct
159 {
160   /* ObjectPath => DispatchData.. */
161   GHashTable *dispatched_channels;
162   /* ObjectPath -> EmpathyDispatchOperations */
163   GHashTable *dispatching_channels;
164
165   /* List of DispatcherRequestData */
166   GList *outstanding_requests;
167   /* List of requestable channel classes */
168   GPtrArray *requestable_channels;
169 } ConnectionData;
170
171 typedef struct
172 {
173   EmpathyDispatcher *dispatcher;
174   TpConnection *connection;
175   char *channel_type;
176   guint handle_type;
177   GArray *properties;
178   EmpathyDispatcherFindChannelClassCb *callback;
179   gpointer user_data;
180 } FindChannelRequest;
181
182 static void
183 empathy_dispatcher_call_create_or_ensure_channel (
184     EmpathyDispatcher *dispatcher,
185     DispatcherRequestData *request_data);
186
187 static void
188 dispatcher_request_failed (EmpathyDispatcher *dispatcher,
189     DispatcherRequestData *request_data,
190     const GError *error);
191
192 static DispatchData *
193 new_dispatch_data (TpChannel *channel,
194                    GObject *channel_wrapper)
195 {
196   DispatchData *d = g_slice_new0 (DispatchData);
197   d->channel = g_object_ref (channel);
198   if (channel_wrapper != NULL)
199     d->channel_wrapper = g_object_ref (channel_wrapper);
200
201   return d;
202 }
203
204 static void
205 free_dispatch_data (DispatchData *data)
206 {
207   g_object_unref (data->channel);
208   if (data->channel_wrapper != NULL)
209     g_object_unref (data->channel_wrapper);
210
211   g_slice_free (DispatchData, data);
212 }
213
214 static DispatcherRequestData *
215 new_dispatcher_request_data (EmpathyDispatcher *self,
216                              TpConnection *connection,
217                              const gchar *channel_type,
218                              guint handle_type,
219                              guint handle,
220                              GHashTable *request,
221                              EmpathyContact *contact,
222                              EmpathyDispatcherRequestCb *cb,
223                              gpointer user_data)
224 {
225   DispatcherRequestData *result = g_slice_new0 (DispatcherRequestData);
226
227   result->dispatcher = g_object_ref (self);
228   result->connection = connection;
229
230   result->should_ensure = FALSE;
231
232   result->channel_type = g_strdup (channel_type);
233   result->handle_type = handle_type;
234   result->handle = handle;
235   result->request = request;
236
237   if (contact != NULL)
238     result->contact = g_object_ref (contact);
239
240   result->cb = cb;
241   result->user_data = user_data;
242
243   return result;
244 }
245
246 static void
247 free_dispatcher_request_data (DispatcherRequestData *r)
248 {
249   g_free (r->channel_type);
250
251   if (r->dispatcher != NULL)
252     g_object_unref (r->dispatcher);
253
254   if (r->contact != NULL)
255     g_object_unref (r->contact);
256
257   if (r->request != NULL)
258     g_hash_table_unref (r->request);
259
260
261   if (r->pending_call != NULL)
262     tp_proxy_pending_call_cancel (r->pending_call);
263
264   if (r->channel_request != NULL)
265     g_object_unref (r->channel_request);
266
267   g_slice_free (DispatcherRequestData, r);
268 }
269
270 static ConnectionData *
271 new_connection_data (void)
272 {
273   ConnectionData *cd = g_slice_new0 (ConnectionData);
274
275   cd->dispatched_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
276       g_free, (GDestroyNotify) free_dispatch_data);
277
278   cd->dispatching_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
279       g_free, g_object_unref);
280
281   return cd;
282 }
283
284 static void
285 free_connection_data (ConnectionData *cd)
286 {
287   GList *l;
288   guint i;
289
290   g_hash_table_destroy (cd->dispatched_channels);
291   g_hash_table_destroy (cd->dispatching_channels);
292
293   for (l = cd->outstanding_requests ; l != NULL; l = g_list_delete_link (l,l))
294     {
295       free_dispatcher_request_data (l->data);
296     }
297
298   if (cd->requestable_channels  != NULL)
299     {
300       for (i = 0 ; i < cd->requestable_channels->len ; i++)
301           g_value_array_free (
302             g_ptr_array_index (cd->requestable_channels, i));
303       g_ptr_array_free (cd->requestable_channels, TRUE);
304     }
305 }
306
307 static void
308 free_find_channel_request (FindChannelRequest *r)
309 {
310   guint idx;
311   char *str;
312
313   g_object_unref (r->dispatcher);
314   g_free (r->channel_type);
315
316   if (r->properties != NULL)
317     {
318       for (idx = 0; idx < r->properties->len ; idx++)
319         {
320           str = g_array_index (r->properties, char *, idx);
321           g_free (str);
322         }
323
324       g_array_free (r->properties, TRUE);
325     }
326
327   g_slice_free (FindChannelRequest, r);
328 }
329
330 static void
331 dispatcher_connection_invalidated_cb (TpConnection *connection,
332                                       guint domain,
333                                       gint code,
334                                       gchar *message,
335                                       EmpathyDispatcher *self)
336 {
337   EmpathyDispatcherPriv *priv = GET_PRIV (self);
338
339   DEBUG ("Error: %s", message);
340   g_hash_table_remove (priv->connections, connection);
341 }
342
343 static void
344 dispatch_operation_flush_requests (EmpathyDispatcher *self,
345                                    EmpathyDispatchOperation *operation,
346                                    GError *error,
347                                    ConnectionData *cd)
348 {
349   GList *l;
350
351   l = cd->outstanding_requests;
352   while (l != NULL)
353     {
354       DispatcherRequestData *d = (DispatcherRequestData *) l->data;
355       GList *lt = l;
356
357       l = g_list_next (l);
358
359       if (d->operation == operation)
360         {
361           if (d->cb != NULL)
362             {
363               if (error != NULL)
364                 d->cb (NULL, error, d->user_data);
365               else
366                 d->cb (operation, NULL, d->user_data);
367             }
368
369           cd->outstanding_requests = g_list_delete_link
370             (cd->outstanding_requests, lt);
371
372           free_dispatcher_request_data (d);
373         }
374     }
375 }
376
377 static void
378 dispatcher_channel_invalidated_cb (TpProxy *proxy,
379                                    guint domain,
380                                    gint code,
381                                    gchar *message,
382                                    EmpathyDispatcher *self)
383 {
384   /* Channel went away... */
385   EmpathyDispatcherPriv *priv = GET_PRIV (self);
386   TpConnection *connection;
387   ConnectionData *cd;
388   const gchar *object_path;
389
390   connection = tp_channel_borrow_connection (TP_CHANNEL (proxy));
391
392   cd = g_hash_table_lookup (priv->connections, connection);
393   /* Connection itself invalidated? */
394   if (cd == NULL)
395     return;
396
397   object_path = tp_proxy_get_object_path (proxy);
398
399   DEBUG ("Channel %s invalidated", object_path);
400
401   g_hash_table_remove (cd->dispatched_channels, object_path);
402   g_hash_table_remove (cd->dispatching_channels, object_path);
403
404   priv->channels = g_list_remove (priv->channels, proxy);
405 }
406
407 static void
408 dispatch_operation_approved_cb (EmpathyDispatchOperation *operation,
409                                 EmpathyDispatcher *self)
410 {
411   g_assert (empathy_dispatch_operation_is_incoming (operation));
412   DEBUG ("Send of for dispatching: %s",
413     empathy_dispatch_operation_get_object_path (operation));
414   g_signal_emit (self, signals[DISPATCH], 0, operation);
415 }
416
417 static void
418 dispatch_operation_claimed_cb (EmpathyDispatchOperation *operation,
419                                EmpathyDispatcher *self)
420 {
421   /* Our job is done, remove the dispatch operation and mark the channel as
422    * dispatched */
423   EmpathyDispatcherPriv *priv = GET_PRIV (self);
424   TpConnection *connection;
425   ConnectionData *cd;
426   const gchar *object_path;
427
428   connection = empathy_dispatch_operation_get_tp_connection (operation);
429   cd = g_hash_table_lookup (priv->connections, connection);
430   g_assert (cd != NULL);
431
432   object_path = empathy_dispatch_operation_get_object_path (operation);
433
434   if (g_hash_table_lookup (cd->dispatched_channels, object_path) == NULL)
435     {
436       DispatchData *d;
437       d = new_dispatch_data (
438         empathy_dispatch_operation_get_channel (operation),
439         empathy_dispatch_operation_get_channel_wrapper (operation));
440       g_hash_table_insert (cd->dispatched_channels,
441         g_strdup (object_path), d);
442     }
443   g_hash_table_remove (cd->dispatching_channels, object_path);
444
445   DEBUG ("Channel claimed: %s", object_path);
446 }
447
448 static void
449 dispatch_operation_ready_cb (EmpathyDispatchOperation *operation,
450                              EmpathyDispatcher *self)
451 {
452   EmpathyDispatcherPriv *priv = GET_PRIV (self);
453   TpConnection *connection;
454   ConnectionData *cd;
455   EmpathyDispatchOperationState status;
456
457   g_signal_connect (operation, "approved",
458     G_CALLBACK (dispatch_operation_approved_cb), self);
459
460   g_signal_connect (operation, "claimed",
461     G_CALLBACK (dispatch_operation_claimed_cb), self);
462
463   /* Signal the observers */
464   DEBUG ("Send to observers: %s",
465     empathy_dispatch_operation_get_object_path (operation));
466   g_signal_emit (self, signals[OBSERVE], 0, operation);
467
468   empathy_dispatch_operation_start (operation);
469
470   /* Signal potential requestors */
471   connection =  empathy_dispatch_operation_get_tp_connection (operation);
472   cd = g_hash_table_lookup (priv->connections, connection);
473   g_assert (cd != NULL);
474
475   g_object_ref (operation);
476   g_object_ref (self);
477
478   dispatch_operation_flush_requests (self, operation, NULL, cd);
479   status = empathy_dispatch_operation_get_status (operation);
480   g_object_unref (operation);
481
482   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_CLAIMED)
483     return;
484
485   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
486     {
487       DEBUG ("Send to approvers: %s",
488         empathy_dispatch_operation_get_object_path (operation));
489       g_signal_emit (self, signals[APPROVE], 0, operation);
490     }
491   else
492     {
493       g_assert (status == EMPATHY_DISPATCHER_OPERATION_STATE_DISPATCHING);
494       DEBUG ("Send of for dispatching: %s",
495         empathy_dispatch_operation_get_object_path (operation));
496       g_signal_emit (self, signals[DISPATCH], 0, operation);
497     }
498
499   g_object_unref (self);
500 }
501
502 static void
503 dispatcher_start_dispatching (EmpathyDispatcher *self,
504                               EmpathyDispatchOperation *operation,
505                               ConnectionData *cd)
506 {
507   const gchar *object_path =
508     empathy_dispatch_operation_get_object_path (operation);
509
510   DEBUG ("Dispatching process started for %s", object_path);
511
512   if (g_hash_table_lookup (cd->dispatching_channels, object_path) == NULL)
513     {
514       g_hash_table_insert (cd->dispatching_channels,
515         g_strdup (object_path), operation);
516
517       switch (empathy_dispatch_operation_get_status (operation))
518         {
519           case EMPATHY_DISPATCHER_OPERATION_STATE_PREPARING:
520             g_signal_connect (operation, "ready",
521               G_CALLBACK (dispatch_operation_ready_cb), self);
522             break;
523           case EMPATHY_DISPATCHER_OPERATION_STATE_PENDING:
524             dispatch_operation_ready_cb (operation, self);
525             break;
526           default:
527             g_assert_not_reached ();
528         }
529
530     }
531   else if (empathy_dispatch_operation_get_status (operation) >=
532       EMPATHY_DISPATCHER_OPERATION_STATE_PENDING)
533     {
534       /* Already dispatching and the operation is pending, thus the observers
535        * have seen it (if applicable), so we can flush the request right away.
536        */
537       dispatch_operation_flush_requests (self, operation, NULL, cd);
538     }
539 }
540
541 static void
542 dispatcher_connection_new_channel (EmpathyDispatcher *self,
543                                    TpConnection *connection,
544                                    const gchar *object_path,
545                                    const gchar *channel_type,
546                                    guint handle_type,
547                                    guint handle,
548                                    GHashTable *properties,
549                                    gboolean incoming,
550                                    const GPtrArray *requests_satisfied)
551 {
552   EmpathyDispatcherPriv *priv = GET_PRIV (self);
553   TpChannel         *channel;
554   ConnectionData *cd;
555   EmpathyDispatchOperation *operation;
556   int i;
557   /* Channel types we never want to dispatch because they're either deprecated
558    * or can't sensibly be dispatch (e.g. channels that should always be
559    * requested) */
560   const char *blacklist[] = {
561     TP_IFACE_CHANNEL_TYPE_CONTACT_LIST,
562     TP_IFACE_CHANNEL_TYPE_TUBES,
563     TP_IFACE_CHANNEL_TYPE_ROOM_LIST,
564     NULL
565   };
566
567   dispatcher_init_connection_if_needed (self, connection);
568
569   cd = g_hash_table_lookup (priv->connections, connection);
570
571   for (i = 0 ; blacklist[i] != NULL; i++)
572     {
573       if (!tp_strdiff (channel_type, blacklist[i]))
574         {
575           DEBUG ("Ignoring blacklisted channel type %s on %s",
576             channel_type, object_path);
577           return;
578         }
579     }
580
581   DEBUG ("%s channel of type %s on %s", incoming ? "incoming" : "outgoing",
582     channel_type, object_path);
583
584   if ((operation = g_hash_table_lookup (cd->dispatching_channels,
585       object_path)) != NULL)
586     {
587       /* This operation was already being dispatched, assume we got the channel
588        * again because something asked for it and approve it right away */
589       empathy_dispatch_operation_approve (operation);
590       return;
591     }
592
593   if (properties == NULL)
594     channel = tp_channel_new (connection, object_path, channel_type,
595       handle_type, handle, NULL);
596   else
597     channel = tp_channel_new_from_properties (connection, object_path,
598       properties, NULL);
599
600   g_signal_connect (channel, "invalidated",
601     G_CALLBACK (dispatcher_channel_invalidated_cb),
602     self);
603
604   priv->channels = g_list_prepend (priv->channels, channel);
605
606   operation = empathy_dispatch_operation_new (connection, channel, NULL,
607     incoming);
608
609   g_object_unref (channel);
610
611   if (!incoming && requests_satisfied != NULL)
612     {
613       GList *l;
614       gboolean found = FALSE;
615
616       l = cd->outstanding_requests;
617
618       while (l != NULL)
619         {
620           DispatcherRequestData *d = (DispatcherRequestData *) l->data;
621           guint n;
622           const gchar *path;
623
624           l = g_list_next (l);
625           if (d->request == NULL)
626             continue;
627
628           if (d->operation != NULL)
629             continue;
630
631           path = tp_proxy_get_object_path (d->channel_request);
632           for (n = 0; n < requests_satisfied->len ; n++)
633             {
634               const gchar *p = g_ptr_array_index (requests_satisfied, n);
635               if (!tp_strdiff (p, path))
636                 {
637                   DEBUG ("Channel satified request %s"
638                    "(already dispatched: %d)", p, found);
639                   if (!found)
640                     {
641                       d->operation = operation;
642                       found = TRUE;
643                       continue;
644                     }
645                   else
646                     {
647                       GError err = { TP_ERRORS, TP_ERROR_NOT_YOURS,
648                         "Not yours!" };
649                       dispatcher_request_failed (dispatcher, d, &err);
650                     }
651                 }
652             }
653         }
654     }
655
656   if (g_hash_table_lookup (cd->dispatched_channels, object_path) != NULL)
657     empathy_dispatch_operation_approve (operation);
658
659   dispatcher_start_dispatching (dispatcher, operation, cd);
660 }
661
662 static void
663 dispatcher_connection_new_channel_with_properties (
664     EmpathyDispatcher *self,
665     TpConnection *connection,
666     const gchar *object_path,
667     GHashTable *properties,
668     const GPtrArray *requests_satisfied)
669 {
670   const gchar *channel_type;
671   guint handle_type;
672   guint handle;
673   gboolean requested;
674   gboolean valid;
675
676   channel_type = tp_asv_get_string (properties,
677     TP_IFACE_CHANNEL ".ChannelType");
678   if (channel_type == NULL)
679     {
680       g_message ("%s had an invalid ChannelType property", object_path);
681       return;
682     }
683
684   handle_type = tp_asv_get_uint32 (properties,
685     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
686   if (!valid)
687     {
688       g_message ("%s had an invalid TargetHandleType property", object_path);
689       return;
690     }
691
692   handle = tp_asv_get_uint32 (properties,
693     TP_IFACE_CHANNEL ".TargetHandle", &valid);
694   if (!valid)
695     {
696       g_message ("%s had an invalid TargetHandle property", object_path);
697       return;
698     }
699
700   /* We assume there is no channel dispather, so we're the only one dispatching
701    * it. Which means that a requested channel it is outgoing one */
702   requested = tp_asv_get_boolean (properties,
703     TP_IFACE_CHANNEL ".Requested", &valid);
704   if (!valid)
705     {
706       g_message ("%s had an invalid Requested property", object_path);
707       requested = FALSE;
708     }
709
710   dispatcher_connection_new_channel (self, connection,
711     object_path, channel_type, handle_type, handle, properties, !requested,
712     requests_satisfied);
713 }
714
715 static void
716 dispatcher_connection_got_all (TpProxy *proxy,
717                                GHashTable *properties,
718                                const GError *error,
719                                gpointer user_data,
720                                GObject *object)
721 {
722   EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
723   EmpathyDispatcherPriv *priv = GET_PRIV (self);
724   GPtrArray *requestable_channels;
725   GPtrArray *existing_channels;
726
727   if (error) {
728     DEBUG ("Error: %s", error->message);
729     return;
730   }
731
732   requestable_channels = tp_asv_get_boxed (properties,
733     "RequestableChannelClasses", TP_ARRAY_TYPE_REQUESTABLE_CHANNEL_CLASS_LIST);
734
735   if (requestable_channels == NULL)
736     DEBUG ("No RequestableChannelClasses property !?! on connection");
737   else
738     {
739       ConnectionData *cd;
740       GList *requests, *l;
741       FindChannelRequest *request;
742       GList *retval;
743
744       cd = g_hash_table_lookup (priv->connections, proxy);
745       g_assert (cd != NULL);
746
747       cd->requestable_channels = g_boxed_copy (
748         TP_ARRAY_TYPE_REQUESTABLE_CHANNEL_CLASS_LIST, requestable_channels);
749
750       requests = g_hash_table_lookup (priv->outstanding_classes_requests,
751           proxy);
752
753       for (l = requests; l != NULL; l = l->next)
754         {
755           request = l->data;
756
757           retval = empathy_dispatcher_find_channel_classes (self,
758               TP_CONNECTION (proxy), request->channel_type,
759               request->handle_type, request->properties);
760           request->callback (retval, request->user_data);
761
762           free_find_channel_request (request);
763           g_list_free (retval);
764         }
765
766       g_list_free (requests);
767
768       g_hash_table_remove (priv->outstanding_classes_requests, proxy);
769     }
770
771   existing_channels = tp_asv_get_boxed (properties,
772       "Channels", TP_ARRAY_TYPE_CHANNEL_DETAILS_LIST);
773
774   if (existing_channels != NULL)
775     {
776       guint idx;
777
778       for (idx = 0; idx < existing_channels->len; idx++)
779         {
780           GValueArray *values = g_ptr_array_index (existing_channels, idx);
781           const gchar *object_path;
782           GHashTable *props;
783
784           object_path = g_value_get_boxed (g_value_array_get_nth (values, 0));
785           props = g_value_get_boxed (g_value_array_get_nth (values, 1));
786
787           if (tp_strdiff (tp_asv_get_string (props,
788                       TP_IFACE_CHANNEL ".ChannelType"),
789                   TP_IFACE_CHANNEL_TYPE_TEXT))
790             continue;
791
792           dispatcher_connection_new_channel_with_properties (self,
793               TP_CONNECTION (proxy), object_path, properties, NULL);
794         }
795     }
796 }
797
798 static void
799 dispatcher_connection_advertise_capabilities_cb (TpConnection    *connection,
800                                                  const GPtrArray *capabilities,
801                                                  const GError    *error,
802                                                  gpointer         user_data,
803                                                  GObject         *self)
804 {
805   if (error)
806     DEBUG ("Error: %s", error->message);
807 }
808
809 static void
810 connection_ready_cb (TpConnection *connection,
811     const GError *error,
812     gpointer user_data)
813 {
814   EmpathyDispatcher *self = EMPATHY_DISPATCHER (user_data);
815   GPtrArray   *capabilities;
816   GType        cap_type;
817   GValue       cap = {0, };
818   const gchar *remove_ = NULL;
819
820   if (error != NULL)
821     {
822       DEBUG ("Error: %s", error->message);
823       goto out;
824     }
825
826   if (tp_proxy_has_interface_by_id (TP_PROXY (connection),
827       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
828     {
829       tp_cli_dbus_properties_call_get_all (connection, -1,
830         TP_IFACE_CONNECTION_INTERFACE_REQUESTS,
831         dispatcher_connection_got_all,
832         NULL, NULL, G_OBJECT (self));
833     }
834
835   /* Advertise VoIP capabilities */
836   capabilities = g_ptr_array_sized_new (1);
837   cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
838     G_TYPE_UINT, G_TYPE_INVALID);
839   g_value_init (&cap, cap_type);
840   g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
841   dbus_g_type_struct_set (&cap,
842         0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
843         1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
844            TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
845            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
846            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P |
847            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_ICE_UDP,
848            G_MAXUINT);
849   g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
850
851   tp_cli_connection_interface_capabilities_call_advertise_capabilities (
852     connection, -1, capabilities, &remove_,
853     dispatcher_connection_advertise_capabilities_cb,
854     NULL, NULL, G_OBJECT (self));
855
856   g_value_unset (&cap);
857   g_ptr_array_free (capabilities, TRUE);
858 out:
859   g_object_unref (self);
860 }
861
862 static void
863 dispatcher_init_connection_if_needed (EmpathyDispatcher *self,
864     TpConnection *connection)
865 {
866   EmpathyDispatcherPriv *priv = GET_PRIV (self);
867
868   if (g_hash_table_lookup (priv->connections, connection) != NULL)
869     return;
870
871   g_hash_table_insert (priv->connections, g_object_ref (connection),
872     new_connection_data ());
873
874   g_signal_connect (connection, "invalidated",
875     G_CALLBACK (dispatcher_connection_invalidated_cb), self);
876
877   /* Ensure to keep the self object alive while the call_when_ready is
878    * running */
879   g_object_ref (self);
880   tp_connection_call_when_ready (connection, connection_ready_cb, self);
881 }
882
883 static void
884 dispatcher_status_changed_cb (TpAccount *account,
885                               guint old_status,
886                               guint new_status,
887                               guint reason,
888                               gchar *dbus_error_name,
889                               GHashTable *details,
890                               EmpathyDispatcher *self)
891 {
892   TpConnection *conn = tp_account_get_connection (account);
893
894   if (conn != NULL)
895     dispatcher_init_connection_if_needed (self, conn);
896 }
897
898 static void
899 remove_idle_handlers (gpointer key,
900                       gpointer value,
901                       gpointer user_data)
902 {
903   guint source_id;
904
905   source_id = GPOINTER_TO_UINT (value);
906   g_source_remove (source_id);
907 }
908
909 static GObject *
910 dispatcher_constructor (GType type,
911                         guint n_construct_params,
912                         GObjectConstructParam *construct_params)
913 {
914   GObject *retval;
915   EmpathyDispatcherPriv *priv;
916
917   if (dispatcher != NULL)
918     return g_object_ref (dispatcher);
919
920   retval = G_OBJECT_CLASS (empathy_dispatcher_parent_class)->constructor
921     (type, n_construct_params, construct_params);
922
923   dispatcher = EMPATHY_DISPATCHER (retval);
924   g_object_add_weak_pointer (retval, (gpointer) &dispatcher);
925
926   priv = GET_PRIV (dispatcher);
927
928   if (priv->handler == NULL)
929     priv->handler = empathy_handler_new (NULL, NULL, NULL);
930
931   empathy_handler_set_handle_channels_func (priv->handler,
932     empathy_dispatcher_handle_channels,
933     dispatcher);
934
935   empathy_handler_set_channels_func (priv->handler,
936     empathy_dispatcher_get_channels,
937     dispatcher);
938
939   return retval;
940 }
941
942 static void
943 dispatcher_dispose (GObject *object)
944 {
945   EmpathyDispatcherPriv *priv = GET_PRIV (object);
946   GHashTableIter iter;
947   gpointer connection;
948   GList *l;
949
950   if (priv->dispose_has_run)
951     return;
952
953   priv->dispose_has_run = TRUE;
954
955   for (l = priv->handlers ; l != NULL; l = g_list_next (l))
956     g_object_unref (G_OBJECT (l->data));
957
958   g_list_free (priv->handlers);
959   priv->handlers = NULL;
960
961   if (priv->handler != NULL)
962     g_object_unref (priv->handler);
963   priv->handler = NULL;
964
965   g_hash_table_iter_init (&iter, priv->connections);
966   while (g_hash_table_iter_next (&iter, &connection, NULL))
967     {
968       g_signal_handlers_disconnect_by_func (connection,
969           dispatcher_connection_invalidated_cb, object);
970     }
971
972   g_hash_table_destroy (priv->connections);
973   priv->connections = NULL;
974
975   if (priv->channel_dispatcher != NULL)
976     g_object_unref (priv->channel_dispatcher);
977   priv->channel_dispatcher = NULL;
978
979   if (priv->dbus != NULL)
980     g_object_unref (priv->dbus);
981   priv->dbus = NULL;
982
983   G_OBJECT_CLASS (empathy_dispatcher_parent_class)->dispose (object);
984 }
985
986 static void
987 dispatcher_finalize (GObject *object)
988 {
989   EmpathyDispatcherPriv *priv = GET_PRIV (object);
990   GList *l;
991   GHashTableIter iter;
992   gpointer connection;
993   GList *list;
994   gpointer account, id;
995
996   if (priv->request_channel_class_async_ids != NULL)
997     {
998       g_hash_table_foreach (priv->request_channel_class_async_ids,
999         remove_idle_handlers, NULL);
1000       g_hash_table_destroy (priv->request_channel_class_async_ids);
1001     }
1002
1003   for (l = priv->channels; l; l = l->next)
1004     {
1005       g_signal_handlers_disconnect_by_func (l->data,
1006           dispatcher_channel_invalidated_cb, object);
1007     }
1008
1009   g_list_free (priv->channels);
1010
1011   g_hash_table_iter_init (&iter, priv->outstanding_classes_requests);
1012   while (g_hash_table_iter_next (&iter, &connection, (gpointer *) &list))
1013     {
1014       g_list_foreach (list, (GFunc) free_find_channel_request, NULL);
1015       g_list_free (list);
1016     }
1017
1018   g_hash_table_iter_init (&iter, priv->status_changed_handlers);
1019   while (g_hash_table_iter_next (&iter, &account, &id))
1020     {
1021       g_signal_handler_disconnect (account, GPOINTER_TO_UINT (id));
1022     }
1023   g_hash_table_destroy (priv->status_changed_handlers);
1024
1025   g_object_unref (priv->account_manager);
1026
1027   g_hash_table_destroy (priv->outstanding_classes_requests);
1028 }
1029
1030 static void
1031 dispatcher_set_property (GObject *object,
1032   guint property_id,
1033   const GValue *value,
1034   GParamSpec *pspec)
1035 {
1036   EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
1037   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1038
1039   switch (property_id)
1040     {
1041       case PROP_HANDLER:
1042         priv->handler = g_value_dup_object (value);
1043         break;
1044       default:
1045         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1046         break;
1047     }
1048 }
1049
1050 static void
1051 dispatcher_get_property (GObject *object,
1052   guint property_id,
1053   GValue *value,
1054   GParamSpec *pspec)
1055 {
1056   EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
1057   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1058
1059   switch (property_id)
1060     {
1061       case PROP_HANDLER:
1062         g_value_set_object (value, priv->handler);
1063         break;
1064       default:
1065         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1066         break;
1067     }
1068 }
1069
1070 static void
1071 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
1072 {
1073   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1074   GParamSpec *param_spec;
1075
1076   object_class->dispose = dispatcher_dispose;
1077   object_class->finalize = dispatcher_finalize;
1078   object_class->constructor = dispatcher_constructor;
1079
1080   object_class->get_property = dispatcher_get_property;
1081   object_class->set_property = dispatcher_set_property;
1082
1083   param_spec = g_param_spec_object ("handler", "handler",
1084     "The main Telepathy Client Hander object",
1085     EMPATHY_TYPE_HANDLER,
1086     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT_ONLY);
1087   g_object_class_install_property (object_class,
1088     PROP_HANDLER, param_spec);
1089
1090   signals[OBSERVE] =
1091     g_signal_new ("observe",
1092       G_TYPE_FROM_CLASS (klass),
1093       G_SIGNAL_RUN_LAST,
1094       0,
1095       NULL, NULL,
1096       g_cclosure_marshal_VOID__OBJECT,
1097       G_TYPE_NONE,
1098       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1099
1100   signals[APPROVE] =
1101     g_signal_new ("approve",
1102       G_TYPE_FROM_CLASS (klass),
1103       G_SIGNAL_RUN_LAST,
1104       0,
1105       NULL, NULL,
1106       g_cclosure_marshal_VOID__OBJECT,
1107       G_TYPE_NONE,
1108       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1109
1110   signals[DISPATCH] =
1111     g_signal_new ("dispatch",
1112       G_TYPE_FROM_CLASS (klass),
1113       G_SIGNAL_RUN_LAST,
1114       0,
1115       NULL, NULL,
1116       g_cclosure_marshal_VOID__OBJECT,
1117       G_TYPE_NONE,
1118       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1119
1120
1121   g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
1122 }
1123
1124 static void
1125 connect_account (EmpathyDispatcher *self,
1126     TpAccount *account)
1127 {
1128   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1129   TpConnection *conn = tp_account_get_connection (account);
1130   gulong id;
1131
1132   id = GPOINTER_TO_UINT (g_hash_table_lookup (priv->status_changed_handlers,
1133         account));
1134
1135   if (id != 0)
1136     return;
1137
1138   if (conn != NULL)
1139     dispatcher_status_changed_cb (account, 0, 0, 0, NULL, NULL, self);
1140
1141   id = g_signal_connect (account, "status-changed",
1142       G_CALLBACK (dispatcher_status_changed_cb), self);
1143
1144   g_hash_table_insert (priv->status_changed_handlers, account,
1145       GUINT_TO_POINTER (id));
1146 }
1147
1148 static void
1149 account_manager_prepared_cb (GObject *source_object,
1150                              GAsyncResult *result,
1151                              gpointer user_data)
1152 {
1153   GList *accounts, *l;
1154   EmpathyDispatcher *self = user_data;
1155   TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
1156   GError *error = NULL;
1157
1158   if (!tp_account_manager_prepare_finish (account_manager, result, &error))
1159     {
1160       DEBUG ("Failed to prepare account manager: %s", error->message);
1161       g_error_free (error);
1162       return;
1163     }
1164
1165   accounts = tp_account_manager_get_valid_accounts (account_manager);
1166   for (l = accounts; l; l = l->next)
1167     {
1168       TpAccount *a = l->data;
1169
1170       connect_account (self, a);
1171     }
1172   g_list_free (accounts);
1173 }
1174
1175 static void
1176 account_prepare_cb (GObject *source_object,
1177     GAsyncResult *result,
1178     gpointer user_data)
1179 {
1180   EmpathyDispatcher *self = user_data;
1181   TpAccount *account = TP_ACCOUNT (source_object);
1182   GError *error = NULL;
1183
1184   if (!tp_account_prepare_finish (account, result, &error))
1185     {
1186       DEBUG ("Failed to prepare account: %s", error->message);
1187       g_error_free (error);
1188       return;
1189     }
1190
1191   connect_account (self, account);
1192 }
1193
1194 static void
1195 account_validity_changed_cb (TpAccountManager *manager,
1196     TpAccount *account,
1197     gboolean valid,
1198     gpointer user_data)
1199 {
1200   if (!valid)
1201     return;
1202
1203   tp_account_prepare_async (account, NULL, account_prepare_cb, user_data);
1204 }
1205
1206 static void
1207 empathy_dispatcher_init (EmpathyDispatcher *self)
1208 {
1209   EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
1210     EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
1211
1212   self->priv = priv;
1213   priv->account_manager = tp_account_manager_dup ();
1214
1215   priv->connections = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1216     g_object_unref, (GDestroyNotify) free_connection_data);
1217
1218   priv->outstanding_classes_requests = g_hash_table_new_full (g_direct_hash,
1219     g_direct_equal, g_object_unref, NULL);
1220
1221   priv->channels = NULL;
1222
1223   tp_account_manager_prepare_async (priv->account_manager, NULL,
1224       account_manager_prepared_cb, self);
1225
1226   empathy_signal_connect_weak (priv->account_manager,
1227       "account-validity-changed", G_CALLBACK (account_validity_changed_cb),
1228       G_OBJECT (self));
1229
1230   priv->request_channel_class_async_ids = g_hash_table_new (g_direct_hash,
1231     g_direct_equal);
1232   priv->status_changed_handlers = g_hash_table_new (g_direct_hash,
1233       g_direct_equal);
1234
1235   priv->dbus = tp_dbus_daemon_dup (NULL);
1236   priv->channel_dispatcher = tp_channel_dispatcher_new (priv->dbus);
1237 }
1238
1239 EmpathyDispatcher *
1240 empathy_dispatcher_new (const gchar *name,
1241   GPtrArray *filters,
1242   GStrv capabilities)
1243 {
1244   EmpathyHandler *handler;
1245   EmpathyDispatcher *ret;
1246
1247   g_assert (dispatcher == NULL);
1248   handler = empathy_handler_new (name, filters, capabilities);
1249
1250   ret = EMPATHY_DISPATCHER (
1251     g_object_new (EMPATHY_TYPE_DISPATCHER,
1252       "handler", handler,
1253       NULL));
1254   g_object_unref (handler);
1255
1256   return ret;
1257 }
1258
1259 EmpathyDispatcher *
1260 empathy_dispatcher_dup_singleton (void)
1261 {
1262   return EMPATHY_DISPATCHER (g_object_new (EMPATHY_TYPE_DISPATCHER, NULL));
1263 }
1264
1265 static void
1266 dispatcher_request_failed (EmpathyDispatcher *self,
1267                            DispatcherRequestData *request_data,
1268                            const GError *error)
1269 {
1270   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1271   ConnectionData *conn_data;
1272
1273   conn_data = g_hash_table_lookup (priv->connections,
1274       request_data->connection);
1275   if (request_data->cb != NULL)
1276     request_data->cb (NULL, error, request_data->user_data);
1277
1278   if (conn_data != NULL)
1279     {
1280       conn_data->outstanding_requests =
1281           g_list_remove (conn_data->outstanding_requests, request_data);
1282     }
1283   /* else Connection has been invalidated */
1284
1285   free_dispatcher_request_data (request_data);
1286 }
1287
1288 static void
1289 dispatcher_connection_new_requested_channel (EmpathyDispatcher *self,
1290   DispatcherRequestData *request_data,
1291   const gchar *object_path,
1292   GHashTable *properties,
1293   const GError *error)
1294 {
1295   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1296   EmpathyDispatchOperation *operation = NULL;
1297   ConnectionData *conn_data;
1298
1299   /* The DispatcherRequestData owns a ref on the self object. As the request
1300    * data could be destroyed (when calling dispatcher_request_failed for
1301    * example) we keep a ref on self to be sure it stays alive while we are
1302    * executing this function. */
1303   g_object_ref (self);
1304
1305   conn_data = g_hash_table_lookup (priv->connections,
1306     request_data->connection);
1307
1308   if (error)
1309     {
1310       DEBUG ("Channel request failed: %s", error->message);
1311
1312       dispatcher_request_failed (self, request_data, error);
1313
1314       return;
1315     }
1316
1317   operation = g_hash_table_lookup (conn_data->dispatching_channels,
1318         object_path);
1319
1320   if (operation == NULL)
1321     {
1322       DispatchData *data = g_hash_table_lookup (conn_data->dispatched_channels,
1323         object_path);
1324
1325       if (data != NULL)
1326         {
1327           operation = empathy_dispatch_operation_new_with_wrapper (
1328             request_data->connection,
1329             data->channel, request_data->contact, FALSE,
1330             data->channel_wrapper);
1331         }
1332       else
1333         {
1334           TpChannel *channel;
1335
1336           if (properties != NULL)
1337             channel = tp_channel_new_from_properties (request_data->connection,
1338               object_path, properties, NULL);
1339           else
1340             channel = tp_channel_new (request_data->connection, object_path,
1341               request_data->channel_type, request_data->handle_type,
1342               request_data->handle, NULL);
1343
1344           g_signal_connect (channel, "invalidated",
1345             G_CALLBACK (dispatcher_channel_invalidated_cb),
1346             request_data->dispatcher);
1347
1348           priv->channels = g_list_prepend (priv->channels, channel);
1349
1350           operation = empathy_dispatch_operation_new (request_data->connection,
1351              channel, request_data->contact, FALSE);
1352           g_object_unref (channel);
1353         }
1354     }
1355   else
1356     {
1357       /* Already existed set potential extra information */
1358       g_object_set (G_OBJECT (operation),
1359         "contact", request_data->contact,
1360         NULL);
1361     }
1362
1363   request_data->operation = operation;
1364
1365   /* (pre)-approve this right away as we requested it
1366    * This might cause the channel to be claimed, in which case the operation
1367    * will disappear. So ref it, and check the status before starting the
1368    * dispatching */
1369
1370   g_object_ref (operation);
1371   empathy_dispatch_operation_approve (operation);
1372
1373    if (empathy_dispatch_operation_get_status (operation) <
1374      EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
1375       dispatcher_start_dispatching (request_data->dispatcher, operation,
1376           conn_data);
1377
1378   g_object_unref (operation);
1379 }
1380
1381 static void
1382 dispatcher_request_channel_cb (TpConnection *connection,
1383                                const gchar  *object_path,
1384                                const GError *error,
1385                                gpointer user_data,
1386                                GObject *weak_object)
1387 {
1388   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1389   EmpathyDispatcher *self =
1390       EMPATHY_DISPATCHER (request_data->dispatcher);
1391
1392   request_data->pending_call = NULL;
1393
1394   dispatcher_connection_new_requested_channel (self,
1395     request_data, object_path, NULL, error);
1396 }
1397
1398 static void
1399 dispatcher_request_channel (DispatcherRequestData *request_data)
1400 {
1401   if (tp_proxy_has_interface_by_id (TP_PROXY (request_data->connection),
1402       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
1403     {
1404       /* Extend the request_data to be a valid request */
1405       g_assert (request_data->request == NULL);
1406       request_data->request = tp_asv_new (
1407         TP_IFACE_CHANNEL ".ChannelType",
1408           G_TYPE_STRING, request_data->channel_type,
1409         TP_IFACE_CHANNEL ".TargetHandleType",
1410           G_TYPE_UINT, request_data->handle_type,
1411         NULL);
1412
1413       if (request_data->handle_type != TP_HANDLE_TYPE_NONE)
1414         tp_asv_set_uint32 (request_data->request,
1415           TP_IFACE_CHANNEL ".TargetHandle", request_data->handle);
1416
1417       empathy_dispatcher_call_create_or_ensure_channel (
1418         request_data->dispatcher, request_data);
1419     }
1420   else
1421     {
1422       request_data->pending_call = tp_cli_connection_call_request_channel (
1423         request_data->connection, -1,
1424         request_data->channel_type,
1425         request_data->handle_type,
1426         request_data->handle,
1427         TRUE, dispatcher_request_channel_cb,
1428         request_data, NULL, NULL);
1429     }
1430 }
1431
1432 void
1433 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1434                                       EmpathyDispatcherRequestCb *callback,
1435                                       gpointer user_data)
1436 {
1437   EmpathyDispatcher *self;
1438   EmpathyDispatcherPriv *priv;
1439   TpConnection *connection;
1440   ConnectionData *connection_data;
1441   DispatcherRequestData *request_data;
1442
1443   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1444
1445   self = empathy_dispatcher_dup_singleton ();
1446   priv = GET_PRIV (self);
1447
1448   connection = empathy_contact_get_connection (contact);
1449   connection_data = g_hash_table_lookup (priv->connections, connection);
1450
1451   /* The contact handle might not be known yet */
1452   request_data = new_dispatcher_request_data (self, connection,
1453     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT,
1454     empathy_contact_get_handle (contact), NULL, contact, callback, user_data);
1455   request_data->should_ensure = TRUE;
1456
1457   connection_data->outstanding_requests = g_list_prepend
1458     (connection_data->outstanding_requests, request_data);
1459
1460   dispatcher_request_channel (request_data);
1461
1462   g_object_unref (self);
1463 }
1464
1465 typedef struct
1466 {
1467   EmpathyDispatcher *dispatcher;
1468   EmpathyDispatcherRequestCb *callback;
1469   gpointer user_data;
1470 } ChatWithContactIdData;
1471
1472 static void
1473 dispatcher_chat_with_contact_id_cb (EmpathyTpContactFactory *factory,
1474                                     EmpathyContact          *contact,
1475                                     const GError            *error,
1476                                     gpointer                 user_data,
1477                                     GObject                 *weak_object)
1478 {
1479   ChatWithContactIdData *data = user_data;
1480
1481   if (error)
1482     {
1483       /* FIXME: Should call data->callback with the error */
1484       DEBUG ("Error: %s", error->message);
1485     }
1486   else
1487     {
1488       empathy_dispatcher_chat_with_contact (contact, data->callback,
1489           data->user_data);
1490     }
1491
1492   g_object_unref (data->dispatcher);
1493   g_slice_free (ChatWithContactIdData, data);
1494 }
1495
1496 void
1497 empathy_dispatcher_chat_with_contact_id (TpConnection *connection,
1498                                          const gchar *contact_id,
1499                                          EmpathyDispatcherRequestCb *callback,
1500                                          gpointer user_data)
1501 {
1502   EmpathyDispatcher *self;
1503   EmpathyTpContactFactory *factory;
1504   ChatWithContactIdData *data;
1505
1506   g_return_if_fail (TP_IS_CONNECTION (connection));
1507   g_return_if_fail (!EMP_STR_EMPTY (contact_id));
1508
1509   self = empathy_dispatcher_dup_singleton ();
1510   factory = empathy_tp_contact_factory_dup_singleton (connection);
1511   data = g_slice_new0 (ChatWithContactIdData);
1512   data->dispatcher = self;
1513   data->callback = callback;
1514   data->user_data = user_data;
1515   empathy_tp_contact_factory_get_from_id (factory, contact_id,
1516       dispatcher_chat_with_contact_id_cb, data, NULL, NULL);
1517
1518   g_object_unref (factory);
1519 }
1520
1521 static void
1522 dispatcher_request_handles_cb (TpConnection *connection,
1523                                const GArray *handles,
1524                                const GError *error,
1525                                gpointer user_data,
1526                                GObject *object)
1527 {
1528   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1529
1530   request_data->pending_call = NULL;
1531
1532   if (error != NULL)
1533     {
1534       EmpathyDispatcher *self = request_data->dispatcher;
1535       EmpathyDispatcherPriv *priv = GET_PRIV (self);
1536       ConnectionData *cd;
1537
1538       cd = g_hash_table_lookup (priv->connections, request_data->connection);
1539
1540       if (request_data->cb)
1541         request_data->cb (NULL, error, request_data->user_data);
1542
1543       cd->outstanding_requests = g_list_remove (cd->outstanding_requests,
1544         request_data);
1545
1546       free_dispatcher_request_data (request_data);
1547       return;
1548     }
1549
1550   request_data->handle = g_array_index (handles, guint, 0);
1551   dispatcher_request_channel (request_data);
1552 }
1553
1554 void
1555 empathy_dispatcher_join_muc (TpConnection *connection,
1556                              const gchar *roomname,
1557                              EmpathyDispatcherRequestCb *callback,
1558                              gpointer user_data)
1559 {
1560   EmpathyDispatcher *self;
1561   EmpathyDispatcherPriv *priv;
1562   DispatcherRequestData *request_data;
1563   ConnectionData *connection_data;
1564   const gchar *names[] = { roomname, NULL };
1565
1566   g_return_if_fail (TP_IS_CONNECTION (connection));
1567   g_return_if_fail (!EMP_STR_EMPTY (roomname));
1568
1569   self = empathy_dispatcher_dup_singleton ();
1570   priv = GET_PRIV (self);
1571
1572   connection_data = g_hash_table_lookup (priv->connections, connection);
1573   g_assert (connection_data != NULL);
1574
1575   /* Don't know the room handle yet */
1576   request_data  = new_dispatcher_request_data (self, connection,
1577     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_ROOM, 0, NULL,
1578     NULL, callback, user_data);
1579   request_data->should_ensure = TRUE;
1580
1581   connection_data->outstanding_requests = g_list_prepend
1582     (connection_data->outstanding_requests, request_data);
1583
1584   request_data->pending_call = tp_cli_connection_call_request_handles (
1585     connection, -1,
1586     TP_HANDLE_TYPE_ROOM, names,
1587     dispatcher_request_handles_cb, request_data, NULL, NULL);
1588
1589   g_object_unref (self);
1590 }
1591
1592 static void
1593 dispatcher_channel_request_failed_cb (TpChannelRequest *request,
1594   const gchar *error,
1595   const gchar *message,
1596   gpointer user_data,
1597   GObject *weak_object)
1598 {
1599   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1600   EmpathyDispatcher *self =
1601       EMPATHY_DISPATCHER (request_data->dispatcher);
1602   GError *err = NULL;
1603
1604   request_data->pending_call = NULL;
1605
1606   DEBUG ("Request failed: %s - %s %s",
1607     tp_proxy_get_object_path (request),
1608     error, message);
1609
1610   tp_proxy_dbus_error_to_gerror (TP_PROXY (request),
1611     error, message, &err);
1612
1613   dispatcher_request_failed (self, request_data, err);
1614
1615   g_error_free (err);
1616 }
1617
1618 static void
1619 dispatcher_channel_request_succeeded_cb (TpChannelRequest *request,
1620   gpointer user_data,
1621   GObject *weak_object)
1622 {
1623   EmpathyDispatcher *self = EMPATHY_DISPATCHER (weak_object);
1624   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1625   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1626   ConnectionData *conn_data;
1627
1628   conn_data = g_hash_table_lookup (priv->connections,
1629     request_data->connection);
1630
1631   DEBUG ("Request succeeded: %s", tp_proxy_get_object_path (request));
1632
1633   /* When success gets called the internal request should have been satisfied,
1634    * if it's still in outstanding_requests and doesn't have an operation
1635    * assigned to it, the channel got handled by someone else.. */
1636
1637   if (g_list_find (conn_data->outstanding_requests, request_data) == NULL)
1638     return;
1639
1640   if (request_data->operation == NULL)
1641     {
1642       GError err = { TP_ERRORS, TP_ERROR_NOT_YOURS, "Not yours!" };
1643       dispatcher_request_failed (self, request_data, &err);
1644     }
1645 }
1646
1647 static void
1648 dispatcher_channel_request_proceed_cb (TpChannelRequest *request,
1649   const GError *error,
1650   gpointer user_data,
1651   GObject *weak_object)
1652 {
1653   EmpathyDispatcher *self = EMPATHY_DISPATCHER (weak_object);
1654   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1655
1656   request_data->pending_call = NULL;
1657
1658   if (error != NULL)
1659     dispatcher_request_failed (self, request_data, error);
1660 }
1661
1662 static void
1663 dispatcher_create_channel_cb (TpChannelDispatcher *proxy,
1664     const gchar *request_path,
1665     const GError *error,
1666     gpointer user_data,
1667     GObject *weak_object)
1668 {
1669   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1670   EmpathyDispatcher *self = EMPATHY_DISPATCHER (request_data->dispatcher);
1671   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1672   TpChannelRequest *request;
1673   GError *err = NULL;
1674
1675   request_data->pending_call = NULL;
1676
1677   if (error != NULL)
1678     {
1679       dispatcher_request_failed (self, request_data, error);
1680       return;
1681     }
1682
1683   request = tp_channel_request_new (priv->dbus, request_path, NULL, NULL);
1684   request_data->channel_request = request;
1685
1686   if (tp_cli_channel_request_connect_to_failed (request,
1687       dispatcher_channel_request_failed_cb, request_data,
1688       NULL, G_OBJECT (self), &err) == NULL)
1689     {
1690       dispatcher_request_failed (self, request_data, err);
1691       g_error_free (err);
1692       return;
1693     }
1694
1695   if (tp_cli_channel_request_connect_to_succeeded (request,
1696       dispatcher_channel_request_succeeded_cb, request_data,
1697       NULL, G_OBJECT (self), &err) == NULL)
1698     {
1699       dispatcher_request_failed (self, request_data, err);
1700       g_error_free (err);
1701       return;
1702     }
1703
1704   request_data->pending_call = tp_cli_channel_request_call_proceed (request,
1705     -1, dispatcher_channel_request_proceed_cb,
1706     request_data, NULL, G_OBJECT (self));
1707 }
1708
1709 static void
1710 empathy_dispatcher_call_create_or_ensure_channel (
1711     EmpathyDispatcher *self,
1712     DispatcherRequestData *request_data)
1713 {
1714   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1715   TpAccount *account;
1716   const gchar *handler = "";
1717
1718   account = empathy_get_account_for_connection (request_data->connection);
1719
1720   g_assert (account != NULL);
1721
1722   if (request_data->cb)
1723     handler = empathy_handler_get_busname (priv->handler);
1724
1725   if (request_data->should_ensure)
1726     {
1727       request_data->pending_call =
1728           tp_cli_channel_dispatcher_call_ensure_channel (
1729               priv->channel_dispatcher,
1730               -1, tp_proxy_get_object_path (TP_PROXY (account)),
1731               request_data->request, 0, handler,
1732               dispatcher_create_channel_cb, request_data, NULL, NULL);
1733     }
1734   else
1735     {
1736       request_data->pending_call =
1737           tp_cli_channel_dispatcher_call_create_channel (
1738               priv->channel_dispatcher,
1739               -1, tp_proxy_get_object_path (TP_PROXY (account)),
1740               request_data->request, 0, handler,
1741               dispatcher_create_channel_cb, request_data, NULL,
1742               G_OBJECT (dispatcher));
1743     }
1744 }
1745
1746 /**
1747  * empathy_dispatcher_create_channel:
1748  * @self: the EmpathyDispatcher
1749  * @connection: the Connection to dispatch on
1750  * @request: an a{sv} map of properties for the request, i.e. using tp_asv_new()
1751  * @callback: a callback for when the channel arrives (or NULL)
1752  * @user_data: optional user data (or NULL)
1753  *
1754  * When calling this function, #EmpathyDispatcher takes ownership of your
1755  * reference to @request. DO NOT unref or destroy @request. When the request is
1756  * done, @request will be unreferenced. Take another reference if you want to
1757  * keep it around.
1758  */
1759 void
1760 empathy_dispatcher_create_channel (EmpathyDispatcher *self,
1761                                    TpConnection *connection,
1762                                    GHashTable *request,
1763                                    EmpathyDispatcherRequestCb *callback,
1764                                    gpointer user_data)
1765 {
1766   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1767   ConnectionData *connection_data;
1768   DispatcherRequestData *request_data;
1769   const gchar *channel_type;
1770   guint handle_type;
1771   guint handle;
1772   gboolean valid;
1773
1774   g_return_if_fail (EMPATHY_IS_DISPATCHER (self));
1775   g_return_if_fail (TP_IS_CONNECTION (connection));
1776   g_return_if_fail (request != NULL);
1777
1778   connection_data = g_hash_table_lookup (priv->connections, connection);
1779   g_assert (connection_data != NULL);
1780
1781   channel_type = tp_asv_get_string (request, TP_IFACE_CHANNEL ".ChannelType");
1782
1783   handle_type = tp_asv_get_uint32 (request,
1784     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1785   if (!valid)
1786     handle_type = TP_UNKNOWN_HANDLE_TYPE;
1787
1788   handle = tp_asv_get_uint32 (request, TP_IFACE_CHANNEL ".TargetHandle", NULL);
1789
1790   request_data  = new_dispatcher_request_data (self, connection,
1791     channel_type, handle_type, handle, request,
1792     NULL, callback, user_data);
1793
1794   connection_data->outstanding_requests = g_list_prepend
1795     (connection_data->outstanding_requests, request_data);
1796
1797   empathy_dispatcher_call_create_or_ensure_channel (self, request_data);
1798 }
1799
1800 static gboolean
1801 channel_class_matches (GValueArray *class,
1802                        const char *channel_type,
1803                        guint handle_type,
1804                        GArray *fixed_properties)
1805 {
1806   GHashTable *fprops;
1807   GValue *v;
1808   const char *c_type;
1809   guint h_type;
1810   gboolean valid;
1811
1812   v = g_value_array_get_nth (class, 0);
1813
1814   /* if the class doesn't match channel type discard it. */
1815   fprops = g_value_get_boxed (v);
1816   c_type = tp_asv_get_string (fprops, TP_IFACE_CHANNEL ".ChannelType");
1817
1818   if (tp_strdiff (channel_type, c_type))
1819     return FALSE;
1820
1821   /* we have the right channel type, see if the handle type matches */
1822   h_type = tp_asv_get_uint32 (fprops,
1823                               TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1824
1825   if (!valid || handle_type != h_type)
1826     return FALSE;
1827
1828   if (fixed_properties != NULL)
1829     {
1830       gpointer h_key, h_val;
1831       guint idx;
1832       GHashTableIter iter;
1833       gboolean found;
1834
1835       g_hash_table_iter_init (&iter, fprops);
1836
1837       while (g_hash_table_iter_next (&iter, &h_key, &h_val))
1838         {
1839           /* discard ChannelType and TargetHandleType, as we already
1840            * checked them.
1841            */
1842           if (!tp_strdiff ((char *) h_key, TP_IFACE_CHANNEL ".ChannelType") ||
1843               !tp_strdiff
1844                 ((char *) h_key, TP_IFACE_CHANNEL ".TargetHandleType"))
1845             continue;
1846
1847           found = FALSE;
1848
1849           for (idx = 0; idx < fixed_properties->len; idx++)
1850             {
1851               /* if |key| doesn't exist in |fixed_properties|, discard
1852                * the class.
1853                */
1854               if (!tp_strdiff
1855                     ((char *) h_key,
1856                      g_array_index (fixed_properties, char *, idx)))
1857                 {
1858                   found = TRUE;
1859                   /* exit the for() loop */
1860                   break;
1861                 }
1862             }
1863
1864           if (!found)
1865             return FALSE;
1866         }
1867     }
1868   else
1869     {
1870       /* if no fixed_properties are specified, discard the classes
1871        * with some fixed properties other than the two we already
1872        * checked.
1873        */
1874       if (g_hash_table_size (fprops) > 2)
1875         return FALSE;
1876     }
1877
1878   return TRUE;
1879 }
1880
1881 static GList *
1882 empathy_dispatcher_find_channel_classes (EmpathyDispatcher *self,
1883                                          TpConnection *connection,
1884                                          const gchar *channel_type,
1885                                          guint handle_type,
1886                                          GArray *fixed_properties)
1887 {
1888   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1889   GValueArray *class;
1890   GPtrArray *classes;
1891   GList *matching_classes;
1892   guint i;
1893   ConnectionData *cd;
1894
1895   g_return_val_if_fail (channel_type != NULL, NULL);
1896   g_return_val_if_fail (handle_type != 0, NULL);
1897
1898   cd = g_hash_table_lookup (priv->connections, connection);
1899
1900   if (cd == NULL)
1901     return NULL;
1902
1903   classes = cd->requestable_channels;
1904   if (classes == NULL)
1905     return NULL;
1906
1907   matching_classes = NULL;
1908
1909   for (i = 0; i < classes->len; i++)
1910     {
1911       class = g_ptr_array_index (classes, i);
1912
1913       if (!channel_class_matches
1914           (class, channel_type, handle_type, fixed_properties))
1915         continue;
1916
1917       matching_classes = g_list_prepend (matching_classes, class);
1918     }
1919
1920   return matching_classes;
1921 }
1922
1923 static gboolean
1924 find_channel_class_idle_cb (gpointer user_data)
1925 {
1926   GList *retval;
1927   GList *requests;
1928   FindChannelRequest *request = user_data;
1929   ConnectionData *cd;
1930   gboolean is_ready = TRUE;
1931   EmpathyDispatcherPriv *priv = GET_PRIV (request->dispatcher);
1932
1933   g_hash_table_remove (priv->request_channel_class_async_ids, request);
1934
1935   cd = g_hash_table_lookup (priv->connections, request->connection);
1936
1937   if (cd == NULL)
1938     is_ready = FALSE;
1939   else if (cd->requestable_channels == NULL)
1940     is_ready = FALSE;
1941
1942   if (is_ready)
1943     {
1944       retval = empathy_dispatcher_find_channel_classes (request->dispatcher,
1945           request->connection, request->channel_type, request->handle_type,
1946           request->properties);
1947
1948       request->callback (retval, request->user_data);
1949       free_find_channel_request (request);
1950       g_list_free (retval);
1951
1952       return FALSE;
1953     }
1954
1955   requests = g_hash_table_lookup (priv->outstanding_classes_requests,
1956       request->connection);
1957   requests = g_list_prepend (requests, request);
1958
1959   g_hash_table_insert (priv->outstanding_classes_requests,
1960       request->connection, requests);
1961
1962   return FALSE;
1963 }
1964
1965 static GArray *
1966 setup_varargs (va_list var_args,
1967                const char *channel_namespace,
1968                const char *first_property_name)
1969 {
1970   const char *name;
1971   char *name_full;
1972   GArray *properties;
1973
1974   if (first_property_name == NULL)
1975     return NULL;
1976
1977   name = first_property_name;
1978   properties = g_array_new (TRUE, TRUE, sizeof (char *));
1979
1980   while (name != NULL)
1981     {
1982       name_full = g_strdup (name);
1983       properties = g_array_append_val (properties, name_full);
1984       name = va_arg (var_args, char *);
1985     }
1986
1987   return properties;
1988 }
1989
1990 /**
1991  * empathy_dispatcher_find_requestable_channel_classes:
1992  * @dispatcher: an #EmpathyDispatcher
1993  * @connection: a #TpConnection
1994  * @channel_type: a string identifying the type of the channel to lookup
1995  * @handle_type: the handle type for the channel
1996  * @first_property_name: %NULL, or the name of the first fixed property,
1997  * followed optionally by more names, followed by %NULL.
1998  *
1999  * Returns all the channel classes that a client can request for the connection
2000  * @connection, of the type identified by @channel_type, @handle_type and the
2001  * fixed properties list.
2002  * The classes which are compatible with a fixed properties list (i.e. those
2003  * that will be returned by this function) are intended as those that do not
2004  * contain any fixed property other than those in the list; note that this
2005  * doesn't guarantee that all the classes compatible with the list will contain
2006  * all the requested fixed properties, so the clients will have to filter
2007  * the returned list themselves.
2008  * If @first_property_name is %NULL, only the classes with no other fixed
2009  * properties than ChannelType and TargetHandleType will be returned.
2010  * Note that this function may return %NULL without performing any lookup if
2011  * @connection is not ready. To ensure that @connection is always ready,
2012  * use the empathy_dispatcher_find_requestable_channel_classes_async() variant.
2013  *
2014  * Return value: a #GList of #GValueArray objects, where the first element in
2015  * the array is a #GHashTable of the fixed properties, and the second is
2016  * a #GStrv of the allowed properties for the class. The list should be free'd
2017  * with g_list_free() when done, but the objects inside the list are owned
2018  * by the #EmpathyDispatcher and must not be modified.
2019  */
2020 GList *
2021 empathy_dispatcher_find_requestable_channel_classes
2022                                  (EmpathyDispatcher *self,
2023                                   TpConnection *connection,
2024                                   const gchar *channel_type,
2025                                   guint handle_type,
2026                                   const char *first_property_name,
2027                                   ...)
2028 {
2029   va_list var_args;
2030   GArray *properties;
2031   EmpathyDispatcherPriv *priv;
2032   GList *retval;
2033   guint idx;
2034   char *str;
2035
2036   g_return_val_if_fail (EMPATHY_IS_DISPATCHER (self), NULL);
2037   g_return_val_if_fail (TP_IS_CONNECTION (connection), NULL);
2038   g_return_val_if_fail (channel_type != NULL, NULL);
2039   g_return_val_if_fail (handle_type != 0, NULL);
2040
2041   priv = GET_PRIV (self);
2042
2043   va_start (var_args, first_property_name);
2044
2045   properties = setup_varargs (var_args, channel_type, first_property_name);
2046
2047   va_end (var_args);
2048
2049   retval = empathy_dispatcher_find_channel_classes (self, connection,
2050     channel_type, handle_type, properties);
2051
2052   if (properties != NULL)
2053     {
2054       /* free the properties array */
2055       for (idx = 0; idx < properties->len ; idx++)
2056         {
2057           str = g_array_index (properties, char *, idx);
2058           g_free (str);
2059         }
2060
2061       g_array_free (properties, TRUE);
2062     }
2063
2064   return retval;
2065 }
2066
2067 /**
2068  * empathy_dispatcher_find_requestable_channel_classes_async:
2069  * @dispatcher: an #EmpathyDispatcher
2070  * @connection: a #TpConnection
2071  * @channel_type: a string identifying the type of the channel to lookup
2072  * @handle_type: the handle type for the channel
2073  * @callback: the callback to call when @connection is ready
2074  * @user_data: the user data to pass to @callback
2075  * @first_property_name: %NULL, or the name of the first fixed property,
2076  * followed optionally by more names, followed by %NULL.
2077  *
2078  * Please see the documentation of
2079  * empathy_dispatcher_find_requestable_channel_classes() for a detailed
2080  * description of this function.
2081  */
2082 void
2083 empathy_dispatcher_find_requestable_channel_classes_async
2084                                  (EmpathyDispatcher *self,
2085                                   TpConnection *connection,
2086                                   const gchar *channel_type,
2087                                   guint handle_type,
2088                                   EmpathyDispatcherFindChannelClassCb callback,
2089                                   gpointer user_data,
2090                                   const char *first_property_name,
2091                                   ...)
2092 {
2093   va_list var_args;
2094   GArray *properties;
2095   FindChannelRequest *request;
2096   EmpathyDispatcherPriv *priv;
2097   guint source_id;
2098
2099   g_return_if_fail (EMPATHY_IS_DISPATCHER (self));
2100   g_return_if_fail (TP_IS_CONNECTION (connection));
2101   g_return_if_fail (channel_type != NULL);
2102   g_return_if_fail (handle_type != 0);
2103
2104   priv = GET_PRIV (self);
2105
2106   va_start (var_args, first_property_name);
2107
2108   properties = setup_varargs (var_args, channel_type, first_property_name);
2109
2110   va_end (var_args);
2111
2112   /* append another request for this connection */
2113   request = g_slice_new0 (FindChannelRequest);
2114   request->dispatcher = g_object_ref (self);
2115   request->channel_type = g_strdup (channel_type);
2116   request->handle_type = handle_type;
2117   request->connection = connection;
2118   request->callback = callback;
2119   request->user_data = user_data;
2120   request->properties = properties;
2121
2122   source_id = g_idle_add (find_channel_class_idle_cb, request);
2123
2124   g_hash_table_insert (priv->request_channel_class_async_ids,
2125     request, GUINT_TO_POINTER (source_id));
2126 }
2127
2128 static GList *
2129 empathy_dispatcher_get_channels (EmpathyHandler *handler,
2130   gpointer user_data)
2131 {
2132   EmpathyDispatcher *self = EMPATHY_DISPATCHER (user_data);
2133   EmpathyDispatcherPriv *priv = GET_PRIV (self);
2134
2135   return priv->channels;
2136 }
2137
2138 static gboolean
2139 empathy_dispatcher_handle_channels (EmpathyHandler *handler,
2140     const gchar *account_path,
2141     const gchar *connection_path,
2142     const GPtrArray *channels,
2143     const GPtrArray *requests_satisfied,
2144     guint64 timestamp,
2145     GHashTable *handler_info,
2146     gpointer user_data,
2147     GError **error)
2148 {
2149   EmpathyDispatcher *self = EMPATHY_DISPATCHER (user_data);
2150   EmpathyDispatcherPriv *priv = GET_PRIV (self);
2151   guint i;
2152   TpAccount *account;
2153   TpConnection *connection;
2154
2155   /* FIXME: should probably find out whether the account manager is prepared
2156    * before ensuring. See bug #600111. */
2157   account = tp_account_manager_ensure_account (priv->account_manager,
2158     account_path);
2159   g_assert (account != NULL);
2160
2161   connection = tp_account_ensure_connection (account, connection_path);
2162   if (connection == NULL)
2163     {
2164       g_set_error_literal (error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
2165         "Invalid connection argument");
2166       return FALSE;
2167     }
2168
2169   for (i = 0; i < channels->len ; i++)
2170     {
2171       GValueArray *arr = g_ptr_array_index (channels, i);
2172       const gchar *object_path;
2173       GHashTable *properties;
2174
2175       object_path = g_value_get_boxed (g_value_array_get_nth (arr, 0));
2176       properties = g_value_get_boxed (g_value_array_get_nth (arr, 1));
2177
2178       dispatcher_connection_new_channel_with_properties (self,
2179         connection, object_path, properties, requests_satisfied);
2180     }
2181
2182   return TRUE;
2183 }
2184
2185
2186 EmpathyHandler *
2187 empathy_dispatcher_add_handler (EmpathyDispatcher *self,
2188     const gchar *name,
2189     GPtrArray *filters,
2190     GStrv capabilities)
2191 {
2192   EmpathyDispatcherPriv *priv = GET_PRIV (self);
2193   EmpathyHandler *handler;
2194
2195   handler = empathy_handler_new (name, filters, capabilities);
2196   priv->handlers = g_list_prepend (priv->handlers, handler);
2197
2198   /* Only set the handle_channels function, the Channel property on the main
2199    * handler will always report all dispatched channels even if they came from
2200    * a different Handler */
2201   empathy_handler_set_handle_channels_func (handler,
2202     empathy_dispatcher_handle_channels, self);
2203
2204   return handler;
2205 }
2206
2207 void
2208 empathy_dispatcher_remove_handler (EmpathyDispatcher *self,
2209   EmpathyHandler *handler)
2210 {
2211   EmpathyDispatcherPriv *priv = GET_PRIV (self);
2212   GList *h;
2213
2214   h = g_list_find (priv->handlers, handler);
2215   g_return_if_fail (h != NULL);
2216
2217   priv->handlers = g_list_delete_link (priv->handlers, h);
2218
2219   g_object_unref (handler);
2220 }