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