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