]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
Merge branch 'ft_rework'
[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 #include <config.h>
23
24 #include <string.h>
25
26 #include <glib/gi18n-lib.h>
27
28 #include <telepathy-glib/enums.h>
29 #include <telepathy-glib/connection.h>
30 #include <telepathy-glib/util.h>
31 #include <telepathy-glib/dbus.h>
32 #include <telepathy-glib/proxy-subclass.h>
33 #include <telepathy-glib/gtypes.h>
34
35 #include <libmissioncontrol/mission-control.h>
36
37 #include <extensions/extensions.h>
38
39 #include "empathy-dispatcher.h"
40 #include "empathy-utils.h"
41 #include "empathy-tube-handler.h"
42 #include "empathy-account-manager.h"
43 #include "empathy-tp-contact-factory.h"
44 #include "empathy-chatroom-manager.h"
45 #include "empathy-utils.h"
46
47 #define DEBUG_FLAG EMPATHY_DEBUG_DISPATCHER
48 #include <libempathy/empathy-debug.h>
49
50 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyDispatcher)
51 typedef struct
52 {
53   EmpathyAccountManager *account_manager;
54   MissionControl *mc;
55   /* connection to connection data mapping */
56   GHashTable *connections;
57   GHashTable *outstanding_classes_requests;
58   gpointer token;
59   GSList *tubes;
60
61   /* channels which the dispatcher is listening "invalidated" */
62   GList *channels;
63
64   GHashTable *request_channel_class_async_ids;
65 } EmpathyDispatcherPriv;
66
67 G_DEFINE_TYPE (EmpathyDispatcher, empathy_dispatcher, G_TYPE_OBJECT);
68
69 enum
70 {
71   OBSERVE,
72   APPROVE,
73   DISPATCH,
74   LAST_SIGNAL
75 };
76
77 static guint signals[LAST_SIGNAL];
78 static EmpathyDispatcher *dispatcher = NULL;
79
80 static GList * empathy_dispatcher_find_channel_classes
81   (EmpathyDispatcher *dispatcher, TpConnection *connection,
82    const gchar *channel_type, guint handle_type, GArray *fixed_properties);
83
84
85 typedef struct
86 {
87   EmpathyDispatcher *dispatcher;
88   EmpathyDispatchOperation *operation;
89   TpConnection *connection;
90   gchar *channel_type;
91   guint handle_type;
92   guint handle;
93   EmpathyContact *contact;
94
95   /* Properties to pass to the channel when requesting it */
96   GHashTable *request;
97   EmpathyDispatcherRequestCb *cb;
98   gpointer user_data;
99   gpointer *request_data;
100 } DispatcherRequestData;
101
102 typedef struct
103 {
104   TpChannel *channel;
105   /* Channel type specific wrapper object */
106   GObject *channel_wrapper;
107 } DispatchData;
108
109 typedef struct
110 {
111   /* ObjectPath => DispatchData.. */
112   GHashTable *dispatched_channels;
113   /* ObjectPath -> EmpathyDispatchOperations */
114   GHashTable *dispatching_channels;
115   /* ObjectPath -> EmpathyDispatchOperations */
116   GHashTable *outstanding_channels;
117   /* List of DispatcherRequestData */
118   GList *outstanding_requests;
119   /* List of requestable channel classes */
120   GPtrArray *requestable_channels;
121 } ConnectionData;
122
123 typedef struct
124 {
125   EmpathyDispatcher *dispatcher;
126   TpConnection *connection;
127   char *channel_type;
128   guint handle_type;
129   GArray *properties;
130   EmpathyDispatcherFindChannelClassCb *callback;
131   gpointer user_data;
132 } FindChannelRequest;
133
134 static DispatchData *
135 new_dispatch_data (TpChannel *channel,
136                    GObject *channel_wrapper)
137 {
138   DispatchData *d = g_slice_new0 (DispatchData);
139   d->channel = g_object_ref (channel);
140   if (channel_wrapper != NULL)
141     d->channel_wrapper = g_object_ref (channel_wrapper);
142
143   return d;
144 }
145
146 static void
147 free_dispatch_data (DispatchData *data)
148 {
149   g_object_unref (data->channel);
150   if (data->channel_wrapper != NULL)
151     g_object_unref (data->channel_wrapper);
152
153   g_slice_free (DispatchData, data);
154 }
155
156 static DispatcherRequestData *
157 new_dispatcher_request_data (EmpathyDispatcher *dispatcher,
158                              TpConnection *connection,
159                              const gchar *channel_type,
160                              guint handle_type,
161                              guint handle,
162                              GHashTable *request,
163                              EmpathyContact *contact,
164                              EmpathyDispatcherRequestCb *cb,
165                              gpointer user_data)
166 {
167   DispatcherRequestData *result = g_slice_new0 (DispatcherRequestData);
168
169   result->dispatcher = g_object_ref (dispatcher);
170   result->connection = connection;
171
172   result->channel_type = g_strdup (channel_type);
173   result->handle_type = handle_type;
174   result->handle = handle;
175   result->request = request;
176
177   if (contact != NULL)
178     result->contact = g_object_ref (contact);
179
180   result->cb = cb;
181   result->user_data = user_data;
182
183   return result;
184 }
185
186 static void
187 free_dispatcher_request_data (DispatcherRequestData *r)
188 {
189   g_free (r->channel_type);
190
191   if (r->dispatcher != NULL)
192     g_object_unref (r->dispatcher);
193
194   if (r->contact != NULL)
195     g_object_unref (r->contact);
196
197   if (r->request != NULL)
198     g_hash_table_unref (r->request);
199
200   g_slice_free (DispatcherRequestData, r);
201 }
202
203 static ConnectionData *
204 new_connection_data (void)
205 {
206   ConnectionData *cd = g_slice_new0 (ConnectionData);
207
208   cd->dispatched_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
209       g_free, (GDestroyNotify) free_dispatch_data);
210
211   cd->dispatching_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
212       g_free, g_object_unref);
213
214   cd->outstanding_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
215       g_free, NULL);
216
217   return cd;
218 }
219
220 static void
221 free_connection_data (ConnectionData *cd)
222 {
223   GList *l;
224
225   g_hash_table_destroy (cd->dispatched_channels);
226   g_hash_table_destroy (cd->dispatching_channels);
227   int i;
228
229   for (l = cd->outstanding_requests ; l != NULL; l = g_list_delete_link (l,l))
230     {
231       free_dispatcher_request_data (l->data);
232     }
233
234   if (cd->requestable_channels  != NULL)
235     {
236       for (i = 0 ; i < cd->requestable_channels->len ; i++)
237           g_value_array_free (
238             g_ptr_array_index (cd->requestable_channels, i));
239       g_ptr_array_free (cd->requestable_channels, TRUE);
240     }
241 }
242
243 static void
244 free_find_channel_request (FindChannelRequest *r)
245 {
246   int idx;
247   char *str;
248
249   g_object_unref (r->dispatcher);
250   g_free (r->channel_type);
251
252   if (r->properties != NULL)
253     {
254       for (idx = 0; idx < r->properties->len ; idx++)
255         {
256           str = g_array_index (r->properties, char *, idx);
257           g_free (str);
258         }
259
260       g_array_free (r->properties, TRUE);
261     }
262
263   g_slice_free (FindChannelRequest, r);
264 }
265
266 static void
267 dispatcher_connection_invalidated_cb (TpConnection *connection,
268                                       guint domain,
269                                       gint code,
270                                       gchar *message,
271                                       EmpathyDispatcher *dispatcher)
272 {
273   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
274
275   DEBUG ("Error: %s", message);
276   g_hash_table_remove (priv->connections, connection);
277 }
278
279 static gboolean
280 dispatcher_operation_can_start (EmpathyDispatcher *self,
281                                 EmpathyDispatchOperation *operation,
282                                 ConnectionData *cd)
283 {
284   GList *l;
285   const gchar *channel_type =
286     empathy_dispatch_operation_get_channel_type (operation);
287
288   for (l = cd->outstanding_requests; l != NULL; l = g_list_next (l))
289     {
290       DispatcherRequestData *d = (DispatcherRequestData *) l->data;
291
292       if (d->operation == NULL && !tp_strdiff (d->channel_type, channel_type))
293         {
294           return FALSE;
295         }
296     }
297
298   return TRUE;
299 }
300
301 static void
302 dispatch_operation_flush_requests (EmpathyDispatcher *dispatcher,
303                                    EmpathyDispatchOperation *operation,
304                                    GError *error,
305                                    ConnectionData *cd)
306 {
307   GList *l;
308
309   l = cd->outstanding_requests;
310   while (l != NULL)
311     {
312       DispatcherRequestData *d = (DispatcherRequestData *) l->data;
313       GList *lt = l;
314
315       l = g_list_next (l);
316
317       if (d->operation == operation)
318         {
319           if (d->cb != NULL)
320             {
321               if (error != NULL)
322                 d->cb (NULL, error, d->user_data);
323               else
324                 d->cb (operation, NULL, d->user_data);
325             }
326
327           cd->outstanding_requests = g_list_delete_link
328             (cd->outstanding_requests, lt);
329
330           free_dispatcher_request_data (d);
331         }
332     }
333 }
334
335 static void
336 dispatcher_channel_invalidated_cb (TpProxy *proxy,
337                                    guint domain,
338                                    gint code,
339                                    gchar *message,
340                                    EmpathyDispatcher *dispatcher)
341 {
342   /* Channel went away... */
343   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
344   TpConnection *connection;
345   EmpathyDispatchOperation *operation;
346   ConnectionData *cd;
347   const gchar *object_path;
348
349   connection = tp_channel_borrow_connection (TP_CHANNEL (proxy));
350
351   cd = g_hash_table_lookup (priv->connections, connection);
352   /* Connection itself invalidated? */
353   if (cd == NULL)
354     return;
355
356   object_path = tp_proxy_get_object_path (proxy);
357
358   DEBUG ("Channel %s invalidated", object_path);
359
360   g_hash_table_remove (cd->dispatched_channels, object_path);
361   g_hash_table_remove (cd->dispatching_channels, object_path);
362
363   priv->channels = g_list_remove (priv->channels, proxy);
364
365   operation = g_hash_table_lookup (cd->outstanding_channels, object_path);
366   if (operation != NULL)
367     {
368       GError error = { domain, code, message };
369       dispatch_operation_flush_requests (dispatcher, operation, &error, cd);
370       g_hash_table_remove (cd->outstanding_channels, object_path);
371       g_object_unref (operation);
372     }
373 }
374
375 static void
376 dispatch_operation_approved_cb (EmpathyDispatchOperation *operation,
377                                 EmpathyDispatcher *dispatcher)
378 {
379   g_assert (empathy_dispatch_operation_is_incoming (operation));
380   DEBUG ("Send of for dispatching: %s",
381     empathy_dispatch_operation_get_object_path (operation));
382   g_signal_emit (dispatcher, signals[DISPATCH], 0, operation);
383 }
384
385 static void
386 dispatch_operation_claimed_cb (EmpathyDispatchOperation *operation,
387                                EmpathyDispatcher *dispatcher)
388 {
389   /* Our job is done, remove the dispatch operation and mark the channel as
390    * dispatched */
391   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
392   TpConnection *connection;
393   ConnectionData *cd;
394   const gchar *object_path;
395
396   connection = empathy_dispatch_operation_get_tp_connection (operation);
397   cd = g_hash_table_lookup (priv->connections, connection);
398   g_assert (cd != NULL);
399
400   object_path = empathy_dispatch_operation_get_object_path (operation);
401
402   if (g_hash_table_lookup (cd->dispatched_channels, object_path) == NULL)
403     {
404       DispatchData *d;
405       d = new_dispatch_data (
406         empathy_dispatch_operation_get_channel (operation),
407         empathy_dispatch_operation_get_channel_wrapper (operation));
408       g_hash_table_insert (cd->dispatched_channels,
409         g_strdup (object_path), d);
410     }
411   g_hash_table_remove (cd->dispatching_channels, object_path);
412
413   DEBUG ("Channel claimed: %s", object_path);
414 }
415
416 static void
417 dispatch_operation_ready_cb (EmpathyDispatchOperation *operation,
418                              EmpathyDispatcher *dispatcher)
419 {
420   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
421   TpConnection *connection;
422   ConnectionData *cd;
423   EmpathyDispatchOperationState status;
424
425   g_signal_connect (operation, "approved",
426     G_CALLBACK (dispatch_operation_approved_cb), dispatcher);
427
428   g_signal_connect (operation, "claimed",
429     G_CALLBACK (dispatch_operation_claimed_cb), dispatcher);
430
431   /* Signal the observers */
432   DEBUG ("Send to observers: %s",
433     empathy_dispatch_operation_get_object_path (operation));
434   g_signal_emit (dispatcher, signals[OBSERVE], 0, operation);
435
436   empathy_dispatch_operation_start (operation);
437
438   /* Signal potential requestors */
439   connection =  empathy_dispatch_operation_get_tp_connection (operation);
440   cd = g_hash_table_lookup (priv->connections, connection);
441   g_assert (cd != NULL);
442
443   g_object_ref (operation);
444   g_object_ref (dispatcher);
445
446   dispatch_operation_flush_requests (dispatcher, operation, NULL, cd);
447   status = empathy_dispatch_operation_get_status (operation);
448   g_object_unref (operation);
449
450   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_CLAIMED)
451     return;
452
453   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
454     {
455       DEBUG ("Send to approvers: %s",
456         empathy_dispatch_operation_get_object_path (operation));
457       g_signal_emit (dispatcher, signals[APPROVE], 0, operation);
458     }
459   else
460     {
461       g_assert (status == EMPATHY_DISPATCHER_OPERATION_STATE_DISPATCHING);
462       DEBUG ("Send of for dispatching: %s",
463         empathy_dispatch_operation_get_object_path (operation));
464       g_signal_emit (dispatcher, signals[DISPATCH], 0, operation);
465     }
466
467   g_object_unref (dispatcher);
468 }
469
470 static void
471 dispatcher_start_dispatching (EmpathyDispatcher *self,
472                               EmpathyDispatchOperation *operation,
473                               ConnectionData *cd)
474 {
475   const gchar *object_path =
476     empathy_dispatch_operation_get_object_path (operation);
477
478   DEBUG ("Dispatching process started for %s", object_path);
479
480   if (g_hash_table_lookup (cd->dispatching_channels, object_path) == NULL)
481     {
482       g_assert (g_hash_table_lookup (cd->outstanding_channels,
483         object_path) == NULL);
484
485       g_hash_table_insert (cd->dispatching_channels,
486         g_strdup (object_path), operation);
487
488       switch (empathy_dispatch_operation_get_status (operation))
489         {
490           case EMPATHY_DISPATCHER_OPERATION_STATE_PREPARING:
491             g_signal_connect (operation, "ready",
492               G_CALLBACK (dispatch_operation_ready_cb), dispatcher);
493             break;
494           case EMPATHY_DISPATCHER_OPERATION_STATE_PENDING:
495             dispatch_operation_ready_cb (operation, dispatcher);
496             break;
497           default:
498             g_assert_not_reached ();
499         }
500
501     }
502   else if (empathy_dispatch_operation_get_status (operation) >=
503       EMPATHY_DISPATCHER_OPERATION_STATE_PENDING)
504     {
505       /* Already dispatching and the operation is pending, thus the observers
506        * have seen it (if applicable), so we can flush the request right away.
507        */
508       dispatch_operation_flush_requests (self, operation, NULL, cd);
509     }
510 }
511
512 static void
513 dispatcher_flush_outstanding_operations (EmpathyDispatcher *self,
514                                          ConnectionData *cd)
515 {
516   GHashTableIter iter;
517   gpointer value;
518
519   g_hash_table_iter_init (&iter, cd->outstanding_channels);
520   while (g_hash_table_iter_next (&iter, NULL, &value))
521     {
522       EmpathyDispatchOperation *operation = EMPATHY_DISPATCH_OPERATION (value);
523
524       if (dispatcher_operation_can_start (self, operation, cd))
525         {
526           dispatcher_start_dispatching (dispatcher, operation, cd);
527           g_hash_table_iter_remove (&iter);
528         }
529     }
530 }
531
532 static void
533 dispatcher_connection_new_channel (EmpathyDispatcher *dispatcher,
534                                    TpConnection *connection,
535                                    const gchar *object_path,
536                                    const gchar *channel_type,
537                                    guint handle_type,
538                                    guint handle,
539                                    GHashTable *properties,
540                                    gboolean incoming)
541 {
542   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
543   TpChannel         *channel;
544   ConnectionData *cd;
545   EmpathyDispatchOperation *operation;
546   int i;
547   /* Channel types we never want to dispatch because they're either deprecated
548    * or can't sensibly be dispatch (e.g. channels that should always be
549    * requested) */
550   const char *blacklist[] = {
551     TP_IFACE_CHANNEL_TYPE_CONTACT_LIST,
552     TP_IFACE_CHANNEL_TYPE_TUBES,
553     TP_IFACE_CHANNEL_TYPE_ROOM_LIST,
554     NULL
555   };
556
557   cd = g_hash_table_lookup (priv->connections, connection);
558
559   /* Don't bother with channels we have already dispatched or are dispatching
560    * currently. This can happen when NewChannel(s) is fired after
561    * RequestChannel/CreateChannel/EnsureChannel */
562   if (g_hash_table_lookup (cd->dispatched_channels, object_path) != NULL)
563     return;
564
565   if (g_hash_table_lookup (cd->dispatching_channels, object_path) != NULL)
566     return;
567
568   /* Should never occur, but just in case a CM fires spurious NewChannel(s)
569    * signals */
570   if (g_hash_table_lookup (cd->outstanding_channels, object_path) != NULL)
571     return;
572
573   /* Only pick up non-requested text and file channels. For all other it
574    * doesn't make sense to handle it if we didn't request it. The same goes
575    * for channels we discovered by the Channels property or ListChannels */
576   if (!incoming && tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TEXT)
577         && tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER))
578     {
579       DEBUG ("Ignoring incoming channel of type %s on %s",
580         channel_type, object_path);
581       return;
582     }
583
584   for (i = 0 ; blacklist[i] != NULL; i++)
585     {
586       if (!tp_strdiff (channel_type, blacklist[i]))
587         {
588           DEBUG ("Ignoring blacklisted channel type %s on %s",
589             channel_type, object_path);
590           return;
591         }
592     }
593
594   DEBUG ("New channel of type %s on %s", channel_type, object_path);
595
596   if (properties == NULL)
597     channel = tp_channel_new (connection, object_path, channel_type,
598       handle_type, handle, NULL);
599   else
600     channel = tp_channel_new_from_properties (connection, object_path,
601       properties, NULL);
602
603   g_signal_connect (channel, "invalidated",
604     G_CALLBACK (dispatcher_channel_invalidated_cb),
605     dispatcher);
606
607   priv->channels = g_list_prepend (priv->channels, channel);
608
609   operation = empathy_dispatch_operation_new (connection, channel, NULL,
610     incoming);
611
612   g_object_unref (channel);
613
614   if (incoming)
615     {
616       /* Request could either be by us or by a remote party. If there are no
617        * outstanding requests for this channel type we can assume it's remote.
618        * Otherwise we wait untill they are all satisfied */
619       if (dispatcher_operation_can_start (dispatcher, operation, cd))
620         dispatcher_start_dispatching (dispatcher, operation, cd);
621       else
622         g_hash_table_insert (cd->outstanding_channels,
623           g_strdup (object_path), operation);
624     }
625   else
626     {
627       dispatcher_start_dispatching (dispatcher, operation, cd);
628     }
629 }
630
631 static void
632 dispatcher_connection_new_channel_cb (TpConnection *connection,
633                                       const gchar *object_path,
634                                       const gchar  *channel_type,
635                                       guint handle_type,
636                                       guint handle,
637                                       gboolean suppress_handler,
638                                       gpointer user_data,
639                                       GObject *object)
640 {
641   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
642
643   /* Empathy heavily abuses surpress handler (don't try this at home), if
644    * surpress handler is true then it is an outgoing channel, which is
645    * requested either by us or some other party (like the megaphone applet).
646    * Otherwise it's an incoming channel */
647   dispatcher_connection_new_channel (dispatcher, connection,
648     object_path, channel_type, handle_type, handle, NULL, !suppress_handler);
649 }
650
651 static void
652 dispatcher_connection_new_channel_with_properties (EmpathyDispatcher *dispatcher,
653                                                    TpConnection *connection,
654                                                    const gchar *object_path,
655                                                    GHashTable *properties)
656 {
657   const gchar *channel_type;
658   guint handle_type;
659   guint handle;
660   gboolean requested;
661   gboolean valid;
662
663
664   channel_type = tp_asv_get_string (properties,
665     TP_IFACE_CHANNEL ".ChannelType");
666   if (channel_type == NULL)
667     {
668       g_message ("%s had an invalid ChannelType property", object_path);
669       return;
670     }
671
672   handle_type = tp_asv_get_uint32 (properties,
673     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
674   if (!valid)
675     {
676       g_message ("%s had an invalid TargetHandleType property", object_path);
677       return;
678     }
679
680   handle = tp_asv_get_uint32 (properties,
681     TP_IFACE_CHANNEL ".TargetHandle", &valid);
682   if (!valid)
683     {
684       g_message ("%s had an invalid TargetHandle property", object_path);
685       return;
686     }
687
688   /* We assume there is no channel dispather, so we're the only one dispatching
689    * it. Which means that a requested channel it is outgoing one */
690   requested = tp_asv_get_boolean (properties,
691     TP_IFACE_CHANNEL ".Requested", &valid);
692   if (!valid)
693     {
694       g_message ("%s had an invalid Requested property", object_path);
695       return;
696     }
697
698   dispatcher_connection_new_channel (dispatcher, connection,
699     object_path, channel_type, handle_type, handle, properties, !requested);
700 }
701
702 static void
703 dispatcher_connection_new_channels_cb (TpConnection *connection,
704                                        const GPtrArray *channels,
705                                        gpointer user_data,
706                                        GObject *object)
707 {
708   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
709   int i;
710
711   for (i = 0; i < channels->len ; i++)
712     {
713       GValueArray *arr = g_ptr_array_index (channels, i);
714       const gchar *object_path;
715       GHashTable *properties;
716
717       object_path = g_value_get_boxed (g_value_array_get_nth (arr, 0));
718       properties = g_value_get_boxed (g_value_array_get_nth (arr, 1));
719
720       dispatcher_connection_new_channel_with_properties (dispatcher,
721         connection, object_path, properties);
722     }
723 }
724
725 static void
726 dispatcher_connection_got_all (TpProxy *proxy,
727                                GHashTable *properties,
728                                const GError *error,
729                                gpointer user_data,
730                                GObject *object)
731 {
732   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
733   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
734   GPtrArray *channels;
735   GPtrArray *requestable_channels;
736
737   if (error) {
738     DEBUG ("Error: %s", error->message);
739     return;
740   }
741
742   channels = tp_asv_get_boxed (properties, "Channels",
743     TP_ARRAY_TYPE_CHANNEL_DETAILS_LIST);
744
745   if (channels == NULL)
746     DEBUG ("No Channels property !?! on connection");
747   else
748     dispatcher_connection_new_channels_cb (TP_CONNECTION (proxy),
749       channels, NULL, object);
750
751   requestable_channels = tp_asv_get_boxed (properties,
752     "RequestableChannelClasses", TP_ARRAY_TYPE_REQUESTABLE_CHANNEL_CLASS_LIST);
753
754   if (requestable_channels == NULL)
755     DEBUG ("No RequestableChannelClasses property !?! on connection");
756   else
757     {
758       ConnectionData *cd;
759       GList *requests, *l;
760       FindChannelRequest *request;
761       GList *retval;
762
763       cd = g_hash_table_lookup (priv->connections, proxy);
764       g_assert (cd != NULL);
765
766       cd->requestable_channels = g_boxed_copy (
767         TP_ARRAY_TYPE_REQUESTABLE_CHANNEL_CLASS_LIST, requestable_channels);
768
769       requests = g_hash_table_lookup (priv->outstanding_classes_requests,
770           proxy);
771
772       for (l = requests; l != NULL; l = l->next)
773         {
774           request = l->data;
775
776           retval = empathy_dispatcher_find_channel_classes (dispatcher,
777               TP_CONNECTION (proxy), request->channel_type,
778               request->handle_type, request->properties);
779           request->callback (retval, request->user_data);
780
781           free_find_channel_request (request);
782           g_list_free (retval);
783         }
784
785       g_list_free (requests);
786
787       g_hash_table_remove (priv->outstanding_classes_requests, proxy);
788     }
789 }
790
791 static void
792 dispatcher_connection_list_channels_cb (TpConnection    *connection,
793                                         const GPtrArray *channels,
794                                         const GError    *error,
795                                         gpointer         user_data,
796                                         GObject         *dispatcher)
797 {
798   int i;
799
800   if (error)
801     {
802       DEBUG ("Error: %s", error->message);
803       return;
804     }
805
806   for (i = 0; i < channels->len; i++)
807     {
808       GValueArray *values;
809
810       values = g_ptr_array_index (channels, i);
811       /* We don't have any extra info, so assume already existing channels are
812        * incoming... */
813       dispatcher_connection_new_channel (EMPATHY_DISPATCHER (dispatcher),
814         connection,
815         g_value_get_boxed (g_value_array_get_nth (values, 0)),
816         g_value_get_string (g_value_array_get_nth (values, 1)),
817         g_value_get_uint (g_value_array_get_nth (values, 2)),
818         g_value_get_uint (g_value_array_get_nth (values, 3)),
819         NULL, TRUE);
820     }
821 }
822
823 static void
824 dispatcher_connection_advertise_capabilities_cb (TpConnection    *connection,
825                                                  const GPtrArray *capabilities,
826                                                  const GError    *error,
827                                                  gpointer         user_data,
828                                                  GObject         *dispatcher)
829 {
830   if (error)
831     DEBUG ("Error: %s", error->message);
832 }
833
834 static void
835 dispatcher_new_connection_cb (EmpathyAccountManager *manager,
836                               TpConnection *connection,
837                               EmpathyDispatcher *dispatcher)
838 {
839   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
840   GPtrArray   *capabilities;
841   GType        cap_type;
842   GValue       cap = {0, };
843   const gchar *remove = NULL;
844
845   if (g_hash_table_lookup (priv->connections, connection) != NULL)
846     return;
847
848   g_hash_table_insert (priv->connections, g_object_ref (connection),
849     new_connection_data ());
850
851   g_signal_connect (connection, "invalidated",
852     G_CALLBACK (dispatcher_connection_invalidated_cb), dispatcher);
853
854   if (tp_proxy_has_interface_by_id (TP_PROXY (connection),
855       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
856     {
857       tp_cli_connection_interface_requests_connect_to_new_channels (connection,
858         dispatcher_connection_new_channels_cb,
859         NULL, NULL, G_OBJECT (dispatcher), NULL);
860
861       tp_cli_dbus_properties_call_get_all (connection, -1,
862         TP_IFACE_CONNECTION_INTERFACE_REQUESTS,
863         dispatcher_connection_got_all,
864         NULL, NULL, G_OBJECT (dispatcher));
865     }
866   else
867     {
868       tp_cli_connection_connect_to_new_channel (connection,
869         dispatcher_connection_new_channel_cb,
870         NULL, NULL, G_OBJECT (dispatcher), NULL);
871
872       tp_cli_connection_call_list_channels (connection, -1,
873         dispatcher_connection_list_channels_cb, NULL, NULL,
874         G_OBJECT (dispatcher));
875
876     }
877
878   /* Advertise VoIP capabilities */
879   capabilities = g_ptr_array_sized_new (1);
880   cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
881     G_TYPE_UINT, G_TYPE_INVALID);
882   g_value_init (&cap, cap_type);
883   g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
884   dbus_g_type_struct_set (&cap,
885         0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
886         1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
887            TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
888            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
889            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P, G_MAXUINT);
890   g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
891
892   tp_cli_connection_interface_capabilities_call_advertise_capabilities (
893     connection, -1, capabilities, &remove,
894     dispatcher_connection_advertise_capabilities_cb,
895     NULL, NULL, G_OBJECT (dispatcher));
896
897   g_value_unset (&cap);
898   g_ptr_array_free (capabilities, TRUE);
899 }
900
901 static void
902 remove_idle_handlers (gpointer key,
903                       gpointer value,
904                       gpointer user_data)
905 {
906   guint source_id;
907
908   source_id = GPOINTER_TO_UINT (value);
909   g_source_remove (source_id);
910 }
911
912 static GObject *
913 dispatcher_constructor (GType type,
914                         guint n_construct_params,
915                         GObjectConstructParam *construct_params)
916 {
917   GObject *retval;
918
919   if (dispatcher == NULL)
920     {
921       retval = G_OBJECT_CLASS (empathy_dispatcher_parent_class)->constructor
922           (type, n_construct_params, construct_params);
923
924       dispatcher = EMPATHY_DISPATCHER (retval);
925       g_object_add_weak_pointer (retval, (gpointer) &dispatcher);
926     }
927   else
928     {
929       retval = g_object_ref (dispatcher);
930     }
931
932   return retval;
933 }
934
935 static void
936 dispatcher_finalize (GObject *object)
937 {
938   EmpathyDispatcherPriv *priv = GET_PRIV (object);
939   GList *l;
940   GHashTableIter iter;
941   gpointer connection;
942   GList *list;
943
944   if (priv->request_channel_class_async_ids != NULL)
945     {
946       g_hash_table_foreach (priv->request_channel_class_async_ids,
947         remove_idle_handlers, NULL);
948       g_hash_table_destroy (priv->request_channel_class_async_ids);
949     }
950
951   g_signal_handlers_disconnect_by_func (priv->account_manager,
952       dispatcher_new_connection_cb, object);
953
954   for (l = priv->channels; l; l = l->next)
955     {
956       g_signal_handlers_disconnect_by_func (l->data,
957           dispatcher_channel_invalidated_cb, object);
958     }
959
960   g_list_free (priv->channels);
961
962   g_hash_table_iter_init (&iter, priv->connections);
963   while (g_hash_table_iter_next (&iter, &connection, NULL))
964     {
965       g_signal_handlers_disconnect_by_func (connection,
966           dispatcher_connection_invalidated_cb, object);
967     }
968
969   g_hash_table_iter_init (&iter, priv->outstanding_classes_requests);
970   while (g_hash_table_iter_next (&iter, &connection, (gpointer *) &list))
971     {
972       g_list_foreach (list, (GFunc) free_find_channel_request, NULL);
973       g_list_free (list);
974     }
975
976   g_object_unref (priv->account_manager);
977   g_object_unref (priv->mc);
978
979   g_hash_table_destroy (priv->connections);
980   g_hash_table_destroy (priv->outstanding_classes_requests);
981 }
982
983 static void
984 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
985 {
986   GObjectClass *object_class = G_OBJECT_CLASS (klass);
987
988   object_class->finalize = dispatcher_finalize;
989   object_class->constructor = dispatcher_constructor;
990
991   signals[OBSERVE] =
992     g_signal_new ("observe",
993       G_TYPE_FROM_CLASS (klass),
994       G_SIGNAL_RUN_LAST,
995       0,
996       NULL, NULL,
997       g_cclosure_marshal_VOID__OBJECT,
998       G_TYPE_NONE,
999       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1000
1001   signals[APPROVE] =
1002     g_signal_new ("approve",
1003       G_TYPE_FROM_CLASS (klass),
1004       G_SIGNAL_RUN_LAST,
1005       0,
1006       NULL, NULL,
1007       g_cclosure_marshal_VOID__OBJECT,
1008       G_TYPE_NONE,
1009       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1010
1011   signals[DISPATCH] =
1012     g_signal_new ("dispatch",
1013       G_TYPE_FROM_CLASS (klass),
1014       G_SIGNAL_RUN_LAST,
1015       0,
1016       NULL, NULL,
1017       g_cclosure_marshal_VOID__OBJECT,
1018       G_TYPE_NONE,
1019       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1020
1021   g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
1022
1023 }
1024
1025 static void
1026 empathy_dispatcher_init (EmpathyDispatcher *dispatcher)
1027 {
1028   GList *connections, *l;
1029   EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (dispatcher,
1030     EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
1031
1032   dispatcher->priv = priv;
1033   priv->mc = empathy_mission_control_dup_singleton ();
1034   priv->account_manager = empathy_account_manager_dup_singleton ();
1035
1036   g_signal_connect (priv->account_manager, "new-connection",
1037     G_CALLBACK (dispatcher_new_connection_cb),
1038     dispatcher);
1039
1040   priv->connections = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1041     g_object_unref, (GDestroyNotify) free_connection_data);
1042
1043   priv->outstanding_classes_requests = g_hash_table_new_full (g_direct_hash,
1044     g_direct_equal, g_object_unref, NULL);
1045
1046   priv->channels = NULL;
1047
1048   connections = empathy_account_manager_dup_connections (priv->account_manager);
1049   for (l = connections; l; l = l->next)
1050     {
1051       dispatcher_new_connection_cb (priv->account_manager, l->data, dispatcher);
1052       g_object_unref (l->data);
1053     }
1054   g_list_free (connections);
1055
1056   priv->request_channel_class_async_ids = g_hash_table_new (g_direct_hash,
1057     g_direct_equal);
1058 }
1059
1060 EmpathyDispatcher *
1061 empathy_dispatcher_dup_singleton (void)
1062 {
1063   return EMPATHY_DISPATCHER (g_object_new (EMPATHY_TYPE_DISPATCHER, NULL));
1064 }
1065
1066 static void
1067 dispatcher_request_failed (EmpathyDispatcher *dispatcher,
1068                            DispatcherRequestData *request_data,
1069                            const GError *error)
1070 {
1071   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1072   ConnectionData *conn_data;
1073
1074   conn_data = g_hash_table_lookup (priv->connections, request_data->connection);
1075   if (request_data->cb != NULL)
1076     request_data->cb (NULL, error, request_data->user_data);
1077
1078   conn_data->outstanding_requests =
1079       g_list_remove (conn_data->outstanding_requests, request_data);
1080   free_dispatcher_request_data (request_data);
1081 }
1082
1083 static void
1084 dispatcher_connection_new_requested_channel (EmpathyDispatcher *dispatcher,
1085                                              DispatcherRequestData *request_data,
1086                                              const gchar *object_path,
1087                                              GHashTable *properties,
1088                                              const GError *error)
1089 {
1090   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1091   EmpathyDispatchOperation *operation = NULL;
1092   ConnectionData *conn_data;
1093
1094   conn_data = g_hash_table_lookup (priv->connections,
1095     request_data->connection);
1096
1097   if (error)
1098     {
1099       DEBUG ("Channel request failed: %s", error->message);
1100
1101       dispatcher_request_failed (dispatcher, request_data, error);
1102
1103       goto out;
1104     }
1105
1106   operation = g_hash_table_lookup (conn_data->outstanding_channels,
1107     object_path);
1108
1109   if (operation != NULL)
1110     g_hash_table_remove (conn_data->outstanding_channels, object_path);
1111   else
1112     operation = g_hash_table_lookup (conn_data->dispatching_channels,
1113         object_path);
1114
1115   if (operation == NULL)
1116     {
1117       DispatchData *data = g_hash_table_lookup (conn_data->dispatched_channels,
1118         object_path);
1119
1120       if (data != NULL)
1121         {
1122           operation = empathy_dispatch_operation_new_with_wrapper (
1123             request_data->connection,
1124             data->channel, request_data->contact, FALSE,
1125             data->channel_wrapper);
1126         }
1127       else
1128         {
1129           TpChannel *channel;
1130
1131           if (properties != NULL)
1132             channel = tp_channel_new_from_properties (request_data->connection,
1133               object_path, properties, NULL);
1134           else
1135             channel = tp_channel_new (request_data->connection, object_path,
1136               request_data->channel_type, request_data->handle_type,
1137               request_data->handle, NULL);
1138
1139           g_signal_connect (channel, "invalidated",
1140             G_CALLBACK (dispatcher_channel_invalidated_cb),
1141             request_data->dispatcher);
1142
1143           priv->channels = g_list_prepend (priv->channels, channel);
1144
1145           operation = empathy_dispatch_operation_new (request_data->connection,
1146              channel, request_data->contact, FALSE);
1147           g_object_unref (channel);
1148         }
1149     }
1150   else
1151     {
1152       /* Already existed set potential extra information */
1153       g_object_set (G_OBJECT (operation),
1154         "contact", request_data->contact,
1155         NULL);
1156     }
1157
1158   request_data->operation = operation;
1159
1160   /* (pre)-approve this right away as we requested it
1161    * This might cause the channel to be claimed, in which case the operation
1162    * will disappear. So ref it, and check the status before starting the
1163    * dispatching */
1164
1165   g_object_ref (operation);
1166   empathy_dispatch_operation_approve (operation);
1167
1168    if (empathy_dispatch_operation_get_status (operation) <
1169      EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
1170       dispatcher_start_dispatching (request_data->dispatcher, operation,
1171           conn_data);
1172
1173   g_object_unref (operation);
1174
1175 out:
1176   dispatcher_flush_outstanding_operations (request_data->dispatcher,
1177     conn_data);
1178 }
1179
1180 static void
1181 dispatcher_request_channel_cb (TpConnection *connection,
1182                                const gchar  *object_path,
1183                                const GError *error,
1184                                gpointer user_data,
1185                                GObject *weak_object)
1186 {
1187   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1188   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1189
1190   dispatcher_connection_new_requested_channel (dispatcher,
1191     request_data, object_path, NULL, error);
1192 }
1193
1194 static void
1195 dispatcher_request_channel (DispatcherRequestData *request_data)
1196 {
1197   tp_cli_connection_call_request_channel (request_data->connection, -1,
1198     request_data->channel_type,
1199     request_data->handle_type,
1200     request_data->handle,
1201     TRUE, dispatcher_request_channel_cb,
1202     request_data, NULL, G_OBJECT (request_data->dispatcher));
1203 }
1204
1205 void
1206 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1207                                       EmpathyDispatcherRequestCb *callback,
1208                                       gpointer user_data)
1209 {
1210   EmpathyDispatcher *dispatcher;
1211   EmpathyDispatcherPriv *priv;
1212   TpConnection *connection;
1213   ConnectionData *connection_data;
1214   DispatcherRequestData *request_data;
1215
1216   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1217
1218   dispatcher = empathy_dispatcher_dup_singleton ();
1219   priv = GET_PRIV (dispatcher);
1220
1221   connection = empathy_contact_get_connection (contact);
1222   connection_data = g_hash_table_lookup (priv->connections, connection);
1223
1224   /* The contact handle might not be known yet */
1225   request_data  = new_dispatcher_request_data (dispatcher, connection,
1226     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT,
1227     empathy_contact_get_handle (contact), NULL, contact, callback, user_data);
1228
1229   connection_data->outstanding_requests = g_list_prepend
1230     (connection_data->outstanding_requests, request_data);
1231
1232   dispatcher_request_channel (request_data);
1233
1234   g_object_unref (dispatcher);
1235 }
1236
1237 typedef struct
1238 {
1239   EmpathyDispatcher *dispatcher;
1240   EmpathyDispatcherRequestCb *callback;
1241   gpointer user_data;
1242 } ChatWithContactIdData;
1243
1244 static void
1245 dispatcher_chat_with_contact_id_cb (EmpathyTpContactFactory *factory,
1246                                     EmpathyContact          *contact,
1247                                     const GError            *error,
1248                                     gpointer                 user_data,
1249                                     GObject                 *weak_object)
1250 {
1251   ChatWithContactIdData *data = user_data;
1252
1253   if (error)
1254     {
1255       /* FIXME: Should call data->callback with the error */
1256       DEBUG ("Error: %s", error->message);
1257     }
1258   else
1259     {
1260       empathy_dispatcher_chat_with_contact (contact, data->callback, data->user_data);
1261     }
1262
1263   g_object_unref (data->dispatcher);
1264   g_slice_free (ChatWithContactIdData, data);
1265 }
1266
1267 void
1268 empathy_dispatcher_chat_with_contact_id (TpConnection *connection,
1269                                          const gchar *contact_id,
1270                                          EmpathyDispatcherRequestCb *callback,
1271                                          gpointer user_data)
1272 {
1273   EmpathyDispatcher *dispatcher;
1274   EmpathyTpContactFactory *factory;
1275   ChatWithContactIdData *data;
1276
1277   g_return_if_fail (TP_IS_CONNECTION (connection));
1278   g_return_if_fail (!EMP_STR_EMPTY (contact_id));
1279
1280   dispatcher = empathy_dispatcher_dup_singleton ();
1281   factory = empathy_tp_contact_factory_dup_singleton (connection);
1282   data = g_slice_new0 (ChatWithContactIdData);
1283   data->dispatcher = dispatcher;
1284   data->callback = callback;
1285   data->user_data = user_data;
1286   empathy_tp_contact_factory_get_from_id (factory, contact_id,
1287       dispatcher_chat_with_contact_id_cb, data, NULL, NULL);
1288
1289   g_object_unref (factory);
1290 }
1291
1292 static void
1293 dispatcher_request_handles_cb (TpConnection *connection,
1294                                const GArray *handles,
1295                                const GError *error,
1296                                gpointer user_data,
1297                                GObject *object)
1298 {
1299   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1300
1301   if (error != NULL)
1302     {
1303       EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
1304       EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1305       ConnectionData *cd;
1306
1307       cd = g_hash_table_lookup (priv->connections, request_data->connection);
1308
1309       if (request_data->cb)
1310         request_data->cb (NULL, error, request_data->user_data);
1311
1312       cd->outstanding_requests = g_list_remove (cd->outstanding_requests,
1313         request_data);
1314
1315       free_dispatcher_request_data (request_data);
1316
1317       dispatcher_flush_outstanding_operations (dispatcher, cd);
1318       return;
1319     }
1320
1321   request_data->handle = g_array_index (handles, guint, 0);
1322   dispatcher_request_channel (request_data);
1323 }
1324
1325 void
1326 empathy_dispatcher_join_muc (TpConnection *connection,
1327                              const gchar *roomname,
1328                              EmpathyDispatcherRequestCb *callback,
1329                              gpointer user_data)
1330 {
1331   EmpathyDispatcher *dispatcher;
1332   EmpathyDispatcherPriv *priv;
1333   DispatcherRequestData *request_data;
1334   ConnectionData *connection_data;
1335   const gchar *names[] = { roomname, NULL };
1336
1337   g_return_if_fail (TP_IS_CONNECTION (connection));
1338   g_return_if_fail (!EMP_STR_EMPTY (roomname));
1339
1340   dispatcher = empathy_dispatcher_dup_singleton ();
1341   priv = GET_PRIV (dispatcher);
1342
1343   connection_data = g_hash_table_lookup (priv->connections, connection);
1344
1345   /* Don't know the room handle yet */
1346   request_data  = new_dispatcher_request_data (dispatcher, connection,
1347     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_ROOM, 0, NULL,
1348     NULL, callback, user_data);
1349
1350   connection_data->outstanding_requests = g_list_prepend
1351     (connection_data->outstanding_requests, request_data);
1352
1353   tp_cli_connection_call_request_handles (connection, -1,
1354     TP_HANDLE_TYPE_ROOM, names,
1355     dispatcher_request_handles_cb, request_data, NULL,
1356     G_OBJECT (dispatcher));
1357
1358   g_object_unref (dispatcher);
1359 }
1360
1361 static void
1362 dispatcher_create_channel_cb (TpConnection *connect,
1363                               const gchar *object_path,
1364                               GHashTable *properties,
1365                               const GError *error,
1366                               gpointer user_data,
1367                               GObject *weak_object)
1368 {
1369   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1370   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1371
1372   dispatcher_connection_new_requested_channel (dispatcher,
1373     request_data, object_path, properties, error);
1374 }
1375
1376 void
1377 empathy_dispatcher_create_channel (EmpathyDispatcher *dispatcher,
1378                                    TpConnection *connection,
1379                                    GHashTable *request,
1380                                    EmpathyDispatcherRequestCb *callback,
1381                                    gpointer user_data)
1382 {
1383   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1384   ConnectionData *connection_data;
1385   DispatcherRequestData *request_data;
1386   const gchar *channel_type;
1387   guint handle_type;
1388   guint handle;
1389   gboolean valid;
1390
1391   g_return_if_fail (EMPATHY_IS_DISPATCHER (dispatcher));
1392   g_return_if_fail (TP_IS_CONNECTION (connection));
1393   g_return_if_fail (request != NULL);
1394
1395   connection_data = g_hash_table_lookup (priv->connections, connection);
1396   g_assert (connection_data != NULL);
1397
1398   channel_type = tp_asv_get_string (request, TP_IFACE_CHANNEL ".ChannelType");
1399
1400   handle_type = tp_asv_get_uint32 (request,
1401     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1402   if (!valid)
1403     handle_type = TP_UNKNOWN_HANDLE_TYPE;
1404
1405   handle = tp_asv_get_uint32 (request, TP_IFACE_CHANNEL ".TargetHandle", NULL);
1406
1407   request_data  = new_dispatcher_request_data (dispatcher, connection,
1408     channel_type, handle_type, handle, request,
1409     NULL, callback, user_data);
1410
1411   connection_data->outstanding_requests = g_list_prepend
1412     (connection_data->outstanding_requests, request_data);
1413
1414   tp_cli_connection_interface_requests_call_create_channel (
1415     request_data->connection, -1,
1416     request_data->request, dispatcher_create_channel_cb, request_data, NULL,
1417     G_OBJECT (request_data->dispatcher));
1418 }
1419
1420 static gboolean
1421 channel_class_matches (GValueArray *class,
1422                        const char *channel_type,
1423                        guint handle_type,
1424                        GArray *fixed_properties)
1425 {
1426   GHashTable *fprops;
1427   GValue *v;
1428   const char *c_type;
1429   guint h_type;
1430   gboolean valid;
1431
1432   v = g_value_array_get_nth (class, 0);
1433
1434   /* if the class doesn't match channel type discard it. */
1435   fprops = g_value_get_boxed (v);
1436   c_type = tp_asv_get_string (fprops, TP_IFACE_CHANNEL ".ChannelType");
1437
1438   if (tp_strdiff (channel_type, c_type))
1439     return FALSE;
1440
1441   /* we have the right channel type, see if the handle type matches */
1442   h_type = tp_asv_get_uint32 (fprops,
1443                               TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1444
1445   if (!valid || handle_type != h_type)
1446     return FALSE;
1447
1448   if (fixed_properties != NULL)
1449     {
1450       gpointer h_key, h_val;
1451       int idx;
1452       GHashTableIter iter;
1453       gboolean found;
1454
1455       g_hash_table_iter_init (&iter, fprops);
1456
1457       while (g_hash_table_iter_next (&iter, &h_key, &h_val))
1458         {
1459           /* discard ChannelType and TargetHandleType, as we already
1460            * checked them.
1461            */
1462           if (!tp_strdiff ((char *) h_key, TP_IFACE_CHANNEL ".ChannelType") ||
1463               !tp_strdiff
1464                 ((char *) h_key, TP_IFACE_CHANNEL ".TargetHandleType"))
1465             continue;
1466
1467           found = FALSE;
1468
1469           for (idx = 0; idx < fixed_properties->len; idx++)
1470             {
1471               /* if |key| doesn't exist in |fixed_properties|, discard
1472                * the class.
1473                */
1474               if (!tp_strdiff
1475                     ((char *) h_key,
1476                      g_array_index (fixed_properties, char *, idx)))
1477                 {
1478                   found = TRUE;
1479                   /* exit the for() loop */
1480                   break;
1481                 }
1482             }
1483
1484           if (!found)
1485             return FALSE;
1486         }
1487     }
1488   else
1489     {
1490       /* if no fixed_properties are specified, discard the classes
1491        * with some fixed properties other than the two we already
1492        * checked.
1493        */
1494       if (g_hash_table_size (fprops) > 2)
1495         return FALSE;
1496     }
1497
1498   return TRUE;
1499 }
1500
1501 static GList *
1502 empathy_dispatcher_find_channel_classes (EmpathyDispatcher *dispatcher,
1503                                          TpConnection *connection,
1504                                          const gchar *channel_type,
1505                                          guint handle_type,
1506                                          GArray *fixed_properties)
1507 {
1508   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1509   GValueArray *class;
1510   GPtrArray *classes;
1511   GList *matching_classes;
1512   int i;
1513   ConnectionData *cd;
1514
1515   g_return_val_if_fail (channel_type != NULL, NULL);
1516   g_return_val_if_fail (handle_type != 0, NULL);
1517
1518   cd = g_hash_table_lookup (priv->connections, connection);
1519
1520   if (cd == NULL)
1521     return NULL;
1522
1523   classes = cd->requestable_channels;
1524   if (classes == NULL)
1525     return NULL;
1526
1527   matching_classes = NULL;
1528
1529   for (i = 0; i < classes->len; i++)
1530     {
1531       class = g_ptr_array_index (classes, i);
1532
1533       if (!channel_class_matches
1534           (class, channel_type, handle_type, fixed_properties))
1535         continue;
1536       
1537       matching_classes = g_list_prepend (matching_classes, class);
1538     }
1539
1540   return matching_classes;
1541 }
1542
1543 static gboolean
1544 find_channel_class_idle_cb (gpointer user_data)
1545 {
1546   GList *retval;
1547   GList *requests;
1548   FindChannelRequest *request = user_data;
1549   ConnectionData *cd;
1550   gboolean is_ready = TRUE;
1551   EmpathyDispatcherPriv *priv = GET_PRIV (request->dispatcher);
1552
1553   g_hash_table_remove (priv->request_channel_class_async_ids, request);
1554
1555   cd = g_hash_table_lookup (priv->connections, request->connection);
1556
1557   if (cd == NULL)
1558     is_ready = FALSE;
1559   else if (cd->requestable_channels == NULL)
1560     is_ready = FALSE;
1561
1562   if (is_ready)
1563     {
1564       retval = empathy_dispatcher_find_channel_classes (request->dispatcher,
1565           request->connection, request->channel_type, request->handle_type,
1566           request->properties);
1567
1568       request->callback (retval, request->user_data);
1569       free_find_channel_request (request);
1570       g_list_free (retval);
1571
1572       return FALSE;
1573     }
1574
1575   requests = g_hash_table_lookup (priv->outstanding_classes_requests,
1576       request->connection);
1577   requests = g_list_prepend (requests, request);
1578
1579   g_hash_table_insert (priv->outstanding_classes_requests,
1580       request->connection, requests);
1581
1582   return FALSE;
1583 }
1584
1585 static GArray *
1586 setup_varargs (va_list var_args,
1587                const char *channel_namespace,
1588                const char *first_property_name)
1589 {
1590   const char *name;
1591   char *name_full;
1592   GArray *properties;
1593
1594   if (first_property_name == NULL)
1595     return NULL;
1596
1597   name = first_property_name;
1598   properties = g_array_new (TRUE, TRUE, sizeof (char *));
1599
1600   while (name != NULL)
1601     {
1602       name_full = g_strdup (name);
1603       properties = g_array_append_val (properties, name_full);
1604       name = va_arg (var_args, char *);
1605     }
1606
1607   return properties;
1608 }
1609
1610 /**
1611  * empathy_dispatcher_find_requestable_channel_classes:
1612  * @dispatcher: an #EmpathyDispatcher
1613  * @connection: a #TpConnection
1614  * @channel_type: a string identifying the type of the channel to lookup
1615  * @handle_type: the handle type for the channel
1616  * @first_property_name: %NULL, or the name of the first fixed property,
1617  * followed optionally by more names, followed by %NULL.
1618  *
1619  * Returns all the channel classes that a client can request for the connection
1620  * @connection, of the type identified by @channel_type, @handle_type and the
1621  * fixed properties list.
1622  * The classes which are compatible with a fixed properties list (i.e. those
1623  * that will be returned by this function) are intended as those that do not
1624  * contain any fixed property other than those in the list; note that this
1625  * doesn't guarantee that all the classes compatible with the list will contain
1626  * all the requested fixed properties, so the clients will have to filter
1627  * the returned list themselves.
1628  * If @first_property_name is %NULL, only the classes with no other fixed
1629  * properties than ChannelType and TargetHandleType will be returned.
1630  * Note that this function may return %NULL without performing any lookup if
1631  * @connection is not ready. To ensure that @connection is always ready,
1632  * use the empathy_dispatcher_find_requestable_channel_classes_async() variant.
1633  *
1634  * Return value: a #GList of #GValueArray objects, where the first element in
1635  * the array is a #GHashTable of the fixed properties, and the second is
1636  * a #GStrv of the allowed properties for the class. The list should be free'd
1637  * with g_list_free() when done, but the objects inside the list are owned
1638  * by the #EmpathyDispatcher and must not be modified.
1639  */
1640 GList *
1641 empathy_dispatcher_find_requestable_channel_classes
1642                                  (EmpathyDispatcher *dispatcher,
1643                                   TpConnection *connection,
1644                                   const gchar *channel_type,
1645                                   guint handle_type,
1646                                   const char *first_property_name,
1647                                   ...)
1648 {
1649   va_list var_args;
1650   GArray *properties;
1651   EmpathyDispatcherPriv *priv;
1652   GList *retval;
1653   int idx;
1654   char *str;
1655
1656   g_return_val_if_fail (EMPATHY_IS_DISPATCHER (dispatcher), NULL);
1657   g_return_val_if_fail (TP_IS_CONNECTION (connection), NULL);
1658   g_return_val_if_fail (channel_type != NULL, NULL);
1659   g_return_val_if_fail (handle_type != 0, NULL);
1660
1661   priv = GET_PRIV (dispatcher);
1662
1663   va_start (var_args, first_property_name);
1664
1665   properties = setup_varargs (var_args, channel_type, first_property_name);
1666
1667   va_end (var_args);
1668
1669   retval = empathy_dispatcher_find_channel_classes (dispatcher, connection,
1670     channel_type, handle_type, properties);
1671
1672   if (properties != NULL)
1673     {
1674       /* free the properties array */
1675       for (idx = 0; idx < properties->len ; idx++)
1676         {
1677           str = g_array_index (properties, char *, idx);
1678           g_free (str);
1679         }
1680
1681       g_array_free (properties, TRUE);
1682     }
1683
1684   return retval;
1685 }
1686
1687 /**
1688  * empathy_dispatcher_find_requestable_channel_classes_async:
1689  * @dispatcher: an #EmpathyDispatcher
1690  * @connection: a #TpConnection
1691  * @channel_type: a string identifying the type of the channel to lookup
1692  * @handle_type: the handle type for the channel
1693  * @callback: the callback to call when @connection is ready
1694  * @user_data: the user data to pass to @callback
1695  * @first_property_name: %NULL, or the name of the first fixed property,
1696  * followed optionally by more names, followed by %NULL.
1697  *
1698  * Please see the documentation of
1699  * empathy_dispatcher_find_requestable_channel_classes() for a detailed
1700  * description of this function.
1701  */
1702 void
1703 empathy_dispatcher_find_requestable_channel_classes_async
1704                                  (EmpathyDispatcher *dispatcher,
1705                                   TpConnection *connection,
1706                                   const gchar *channel_type,
1707                                   guint handle_type,
1708                                   EmpathyDispatcherFindChannelClassCb callback,
1709                                   gpointer user_data,
1710                                   const char *first_property_name,
1711                                   ...)
1712 {
1713   va_list var_args;
1714   GArray *properties;
1715   FindChannelRequest *request;
1716   EmpathyDispatcherPriv *priv;
1717   guint source_id;
1718
1719   g_return_if_fail (EMPATHY_IS_DISPATCHER (dispatcher));
1720   g_return_if_fail (TP_IS_CONNECTION (connection));
1721   g_return_if_fail (channel_type != NULL);
1722   g_return_if_fail (handle_type != 0);
1723
1724   priv = GET_PRIV (dispatcher);
1725
1726   va_start (var_args, first_property_name);
1727
1728   properties = setup_varargs (var_args, channel_type, first_property_name);
1729
1730   va_end (var_args);
1731
1732   /* append another request for this connection */
1733   request = g_slice_new0 (FindChannelRequest);
1734   request->dispatcher = dispatcher;
1735   request->channel_type = g_strdup (channel_type);
1736   request->handle_type = handle_type;
1737   request->connection = connection;
1738   request->callback = callback;
1739   request->user_data = user_data;
1740   request->properties = properties;
1741
1742   source_id = g_idle_add (find_channel_class_idle_cb, request);
1743
1744   g_hash_table_insert (priv->request_channel_class_async_ids,
1745     request, GUINT_TO_POINTER (source_id));
1746 }