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