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