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