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