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