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