]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
maithili update
[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
813           if (tp_strdiff (tp_asv_get_string (properties,
814                       TP_IFACE_CHANNEL ".ChannelType"),
815                   TP_IFACE_CHANNEL_TYPE_TEXT))
816             continue;
817
818           dispatcher_connection_new_channel_with_properties (dispatcher,
819               TP_CONNECTION (proxy), object_path, properties);
820         }
821     }
822 }
823
824 static void
825 dispatcher_connection_advertise_capabilities_cb (TpConnection    *connection,
826                                                  const GPtrArray *capabilities,
827                                                  const GError    *error,
828                                                  gpointer         user_data,
829                                                  GObject         *dispatcher)
830 {
831   if (error)
832     DEBUG ("Error: %s", error->message);
833 }
834
835 static void
836 dispatcher_init_connection_if_needed (EmpathyDispatcher *dispatcher,
837     TpConnection *connection)
838 {
839   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
840   GPtrArray   *capabilities;
841   GType        cap_type;
842   GValue       cap = {0, };
843   const gchar *remove = NULL;
844
845   if (g_hash_table_lookup (priv->connections, connection) != NULL)
846     return;
847
848   g_hash_table_insert (priv->connections, g_object_ref (connection),
849     new_connection_data ());
850
851   g_signal_connect (connection, "invalidated",
852     G_CALLBACK (dispatcher_connection_invalidated_cb), dispatcher);
853
854   if (tp_proxy_has_interface_by_id (TP_PROXY (connection),
855       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
856     {
857       tp_cli_dbus_properties_call_get_all (connection, -1,
858         TP_IFACE_CONNECTION_INTERFACE_REQUESTS,
859         dispatcher_connection_got_all,
860         NULL, NULL, G_OBJECT (dispatcher));
861     }
862
863   /* Advertise VoIP capabilities */
864   capabilities = g_ptr_array_sized_new (1);
865   cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
866     G_TYPE_UINT, G_TYPE_INVALID);
867   g_value_init (&cap, cap_type);
868   g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
869   dbus_g_type_struct_set (&cap,
870         0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
871         1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
872            TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
873            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
874            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P, G_MAXUINT);
875   g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
876
877   tp_cli_connection_interface_capabilities_call_advertise_capabilities (
878     connection, -1, capabilities, &remove,
879     dispatcher_connection_advertise_capabilities_cb,
880     NULL, NULL, G_OBJECT (dispatcher));
881
882   g_value_unset (&cap);
883   g_ptr_array_free (capabilities, TRUE);
884 }
885
886 static void
887 dispatcher_new_connection_cb (EmpathyAccountManager *manager,
888                               TpConnection *connection,
889                               EmpathyDispatcher *dispatcher)
890 {
891   dispatcher_init_connection_if_needed (dispatcher, connection);
892 }
893
894 static void
895 remove_idle_handlers (gpointer key,
896                       gpointer value,
897                       gpointer user_data)
898 {
899   guint source_id;
900
901   source_id = GPOINTER_TO_UINT (value);
902   g_source_remove (source_id);
903 }
904
905 static GObject *
906 dispatcher_constructor (GType type,
907                         guint n_construct_params,
908                         GObjectConstructParam *construct_params)
909 {
910   GObject *retval;
911   EmpathyDispatcherPriv *priv;
912
913   if (dispatcher != NULL)
914     return g_object_ref (dispatcher);
915
916   retval = G_OBJECT_CLASS (empathy_dispatcher_parent_class)->constructor
917     (type, n_construct_params, construct_params);
918
919   dispatcher = EMPATHY_DISPATCHER (retval);
920   g_object_add_weak_pointer (retval, (gpointer) &dispatcher);
921
922   priv = GET_PRIV (dispatcher);
923
924   if (priv->handler == NULL)
925     priv->handler = empathy_handler_new (NULL, NULL, NULL);
926
927   empathy_handler_set_handle_channels_func (priv->handler,
928     empathy_dispatcher_handle_channels,
929     dispatcher);
930
931   empathy_handler_set_channels_func (priv->handler,
932     empathy_dispatcher_get_channels,
933     dispatcher);
934
935   return retval;
936 }
937
938 static void
939 dispatcher_dispose (GObject *object)
940 {
941   EmpathyDispatcherPriv *priv = GET_PRIV (object);
942   GList *l;
943
944   if (priv->dispose_has_run)
945     return;
946
947   priv->dispose_has_run = TRUE;
948
949   for (l = priv->handlers ; l != NULL; l = g_list_next (l))
950     g_object_unref (G_OBJECT (l->data));
951
952   g_list_free (priv->handlers);
953   priv->handlers = NULL;
954
955   if (priv->handler != NULL)
956     g_object_unref (priv->handler);
957   priv->handler = NULL;
958
959   G_OBJECT_CLASS (empathy_dispatcher_parent_class)->dispose (object);
960 }
961
962 static void
963 dispatcher_finalize (GObject *object)
964 {
965   EmpathyDispatcherPriv *priv = GET_PRIV (object);
966   GList *l;
967   GHashTableIter iter;
968   gpointer connection;
969   GList *list;
970
971   if (priv->request_channel_class_async_ids != NULL)
972     {
973       g_hash_table_foreach (priv->request_channel_class_async_ids,
974         remove_idle_handlers, NULL);
975       g_hash_table_destroy (priv->request_channel_class_async_ids);
976     }
977
978   g_signal_handlers_disconnect_by_func (priv->account_manager,
979       dispatcher_new_connection_cb, object);
980
981   for (l = priv->channels; l; l = l->next)
982     {
983       g_signal_handlers_disconnect_by_func (l->data,
984           dispatcher_channel_invalidated_cb, object);
985     }
986
987   g_list_free (priv->channels);
988
989   g_hash_table_iter_init (&iter, priv->connections);
990   while (g_hash_table_iter_next (&iter, &connection, NULL))
991     {
992       g_signal_handlers_disconnect_by_func (connection,
993           dispatcher_connection_invalidated_cb, object);
994     }
995
996   g_hash_table_iter_init (&iter, priv->outstanding_classes_requests);
997   while (g_hash_table_iter_next (&iter, &connection, (gpointer *) &list))
998     {
999       g_list_foreach (list, (GFunc) free_find_channel_request, NULL);
1000       g_list_free (list);
1001     }
1002
1003   g_object_unref (priv->account_manager);
1004
1005   g_hash_table_destroy (priv->connections);
1006   g_hash_table_destroy (priv->outstanding_classes_requests);
1007 }
1008
1009 static void
1010 dispatcher_set_property (GObject *object,
1011   guint property_id,
1012   const GValue *value,
1013   GParamSpec *pspec)
1014 {
1015   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
1016   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1017
1018   switch (property_id)
1019     {
1020       case PROP_HANDLER:
1021         priv->handler = g_value_dup_object (value);
1022         break;
1023       default:
1024         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1025         break;
1026     }
1027 }
1028
1029 static void
1030 dispatcher_get_property (GObject *object,
1031   guint property_id,
1032   GValue *value,
1033   GParamSpec *pspec)
1034 {
1035   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
1036   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1037
1038   switch (property_id)
1039     {
1040       case PROP_HANDLER:
1041         g_value_set_object (value, priv->handler);
1042         break;
1043       default:
1044         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1045         break;
1046     }
1047 }
1048
1049 static void
1050 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
1051 {
1052   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1053   GParamSpec *param_spec;
1054
1055   object_class->dispose = dispatcher_dispose;
1056   object_class->finalize = dispatcher_finalize;
1057   object_class->constructor = dispatcher_constructor;
1058
1059   object_class->get_property = dispatcher_get_property;
1060   object_class->set_property = dispatcher_set_property;
1061
1062   param_spec = g_param_spec_object ("handler", "handler",
1063     "The main Telepathy Client Hander object",
1064     EMPATHY_TYPE_HANDLER,
1065     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT_ONLY);
1066   g_object_class_install_property (object_class,
1067     PROP_HANDLER, param_spec);
1068
1069   signals[OBSERVE] =
1070     g_signal_new ("observe",
1071       G_TYPE_FROM_CLASS (klass),
1072       G_SIGNAL_RUN_LAST,
1073       0,
1074       NULL, NULL,
1075       g_cclosure_marshal_VOID__OBJECT,
1076       G_TYPE_NONE,
1077       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1078
1079   signals[APPROVE] =
1080     g_signal_new ("approve",
1081       G_TYPE_FROM_CLASS (klass),
1082       G_SIGNAL_RUN_LAST,
1083       0,
1084       NULL, NULL,
1085       g_cclosure_marshal_VOID__OBJECT,
1086       G_TYPE_NONE,
1087       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1088
1089   signals[DISPATCH] =
1090     g_signal_new ("dispatch",
1091       G_TYPE_FROM_CLASS (klass),
1092       G_SIGNAL_RUN_LAST,
1093       0,
1094       NULL, NULL,
1095       g_cclosure_marshal_VOID__OBJECT,
1096       G_TYPE_NONE,
1097       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1098
1099
1100   g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
1101 }
1102
1103 static void
1104 empathy_dispatcher_init (EmpathyDispatcher *dispatcher)
1105 {
1106   GList *connections, *l;
1107   EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (dispatcher,
1108     EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
1109
1110   dispatcher->priv = priv;
1111   priv->account_manager = empathy_account_manager_dup_singleton ();
1112
1113   g_signal_connect (priv->account_manager, "new-connection",
1114     G_CALLBACK (dispatcher_new_connection_cb),
1115     dispatcher);
1116
1117   priv->connections = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1118     g_object_unref, (GDestroyNotify) free_connection_data);
1119
1120   priv->outstanding_classes_requests = g_hash_table_new_full (g_direct_hash,
1121     g_direct_equal, g_object_unref, NULL);
1122
1123   priv->channels = NULL;
1124
1125   connections = empathy_account_manager_dup_connections (
1126       priv->account_manager);
1127   for (l = connections; l; l = l->next)
1128     {
1129       dispatcher_new_connection_cb (priv->account_manager, l->data,
1130           dispatcher);
1131       g_object_unref (l->data);
1132     }
1133   g_list_free (connections);
1134
1135   priv->request_channel_class_async_ids = g_hash_table_new (g_direct_hash,
1136     g_direct_equal);
1137 }
1138
1139 EmpathyDispatcher *
1140 empathy_dispatcher_new (const gchar *name,
1141   GPtrArray *filters,
1142   GStrv capabilities)
1143 {
1144   g_assert (dispatcher == NULL);
1145   EmpathyHandler *handler;
1146   EmpathyDispatcher *ret;
1147
1148   handler = empathy_handler_new (name, filters, capabilities);
1149
1150   ret = EMPATHY_DISPATCHER (
1151     g_object_new (EMPATHY_TYPE_DISPATCHER,
1152       "handler", handler,
1153       NULL));
1154   g_object_unref (handler);
1155
1156   return ret;
1157 }
1158
1159 EmpathyDispatcher *
1160 empathy_dispatcher_dup_singleton (void)
1161 {
1162   return EMPATHY_DISPATCHER (g_object_new (EMPATHY_TYPE_DISPATCHER, NULL));
1163 }
1164
1165 static void
1166 dispatcher_request_failed (EmpathyDispatcher *dispatcher,
1167                            DispatcherRequestData *request_data,
1168                            const GError *error)
1169 {
1170   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1171   ConnectionData *conn_data;
1172
1173   conn_data = g_hash_table_lookup (priv->connections,
1174       request_data->connection);
1175   if (request_data->cb != NULL)
1176     request_data->cb (NULL, error, request_data->user_data);
1177
1178   if (conn_data != NULL)
1179     {
1180       conn_data->outstanding_requests =
1181           g_list_remove (conn_data->outstanding_requests, request_data);
1182     }
1183   /* else Connection has been invalidated */
1184
1185   free_dispatcher_request_data (request_data);
1186 }
1187
1188 static void
1189 dispatcher_connection_new_requested_channel (EmpathyDispatcher *dispatcher,
1190   DispatcherRequestData *request_data,
1191   const gchar *object_path,
1192   GHashTable *properties,
1193   const GError *error)
1194 {
1195   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1196   EmpathyDispatchOperation *operation = NULL;
1197   ConnectionData *conn_data;
1198
1199   conn_data = g_hash_table_lookup (priv->connections,
1200     request_data->connection);
1201
1202   if (error)
1203     {
1204       DEBUG ("Channel request failed: %s", error->message);
1205
1206       dispatcher_request_failed (dispatcher, request_data, error);
1207
1208       goto out;
1209     }
1210
1211   operation = g_hash_table_lookup (conn_data->outstanding_channels,
1212     object_path);
1213
1214   if (operation != NULL)
1215     g_hash_table_remove (conn_data->outstanding_channels, object_path);
1216   else
1217     operation = g_hash_table_lookup (conn_data->dispatching_channels,
1218         object_path);
1219
1220   if (operation == NULL)
1221     {
1222       DispatchData *data = g_hash_table_lookup (conn_data->dispatched_channels,
1223         object_path);
1224
1225       if (data != NULL)
1226         {
1227           operation = empathy_dispatch_operation_new_with_wrapper (
1228             request_data->connection,
1229             data->channel, request_data->contact, FALSE,
1230             data->channel_wrapper);
1231         }
1232       else
1233         {
1234           TpChannel *channel;
1235
1236           if (properties != NULL)
1237             channel = tp_channel_new_from_properties (request_data->connection,
1238               object_path, properties, NULL);
1239           else
1240             channel = tp_channel_new (request_data->connection, object_path,
1241               request_data->channel_type, request_data->handle_type,
1242               request_data->handle, NULL);
1243
1244           g_signal_connect (channel, "invalidated",
1245             G_CALLBACK (dispatcher_channel_invalidated_cb),
1246             request_data->dispatcher);
1247
1248           priv->channels = g_list_prepend (priv->channels, channel);
1249
1250           operation = empathy_dispatch_operation_new (request_data->connection,
1251              channel, request_data->contact, FALSE);
1252           g_object_unref (channel);
1253         }
1254     }
1255   else
1256     {
1257       /* Already existed set potential extra information */
1258       g_object_set (G_OBJECT (operation),
1259         "contact", request_data->contact,
1260         NULL);
1261     }
1262
1263   request_data->operation = operation;
1264
1265   /* (pre)-approve this right away as we requested it
1266    * This might cause the channel to be claimed, in which case the operation
1267    * will disappear. So ref it, and check the status before starting the
1268    * dispatching */
1269
1270   g_object_ref (operation);
1271   empathy_dispatch_operation_approve (operation);
1272
1273    if (empathy_dispatch_operation_get_status (operation) <
1274      EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
1275       dispatcher_start_dispatching (request_data->dispatcher, operation,
1276           conn_data);
1277
1278   g_object_unref (operation);
1279
1280 out:
1281   dispatcher_flush_outstanding_operations (request_data->dispatcher,
1282     conn_data);
1283 }
1284
1285 static void
1286 dispatcher_request_channel_cb (TpConnection *connection,
1287                                const gchar  *object_path,
1288                                const GError *error,
1289                                gpointer user_data,
1290                                GObject *weak_object)
1291 {
1292   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1293   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1294
1295   dispatcher_connection_new_requested_channel (dispatcher,
1296     request_data, object_path, NULL, error);
1297 }
1298
1299 static void
1300 dispatcher_request_channel (DispatcherRequestData *request_data)
1301 {
1302   if (tp_proxy_has_interface_by_id (TP_PROXY (request_data->connection),
1303       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
1304     {
1305       /* Extend the request_data to be a valid request */
1306       g_assert (request_data->request == NULL);
1307       request_data->request = tp_asv_new (
1308         TP_IFACE_CHANNEL ".ChannelType",
1309           G_TYPE_STRING, request_data->channel_type,
1310         TP_IFACE_CHANNEL ".TargetHandleType",
1311           G_TYPE_UINT, request_data->handle_type,
1312         NULL);
1313
1314       if (request_data->handle_type != TP_HANDLE_TYPE_NONE)
1315         tp_asv_set_uint32 (request_data->request,
1316           TP_IFACE_CHANNEL ".TargetHandle", request_data->handle);
1317
1318       empathy_dispatcher_call_create_or_ensure_channel (
1319         request_data->dispatcher, request_data);
1320     }
1321   else
1322     {
1323       tp_cli_connection_call_request_channel (request_data->connection, -1,
1324         request_data->channel_type,
1325         request_data->handle_type,
1326         request_data->handle,
1327         TRUE, dispatcher_request_channel_cb,
1328         request_data, NULL, G_OBJECT (request_data->dispatcher));
1329     }
1330 }
1331
1332 void
1333 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1334                                       EmpathyDispatcherRequestCb *callback,
1335                                       gpointer user_data)
1336 {
1337   EmpathyDispatcher *dispatcher;
1338   EmpathyDispatcherPriv *priv;
1339   TpConnection *connection;
1340   ConnectionData *connection_data;
1341   DispatcherRequestData *request_data;
1342
1343   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1344
1345   dispatcher = empathy_dispatcher_dup_singleton ();
1346   priv = GET_PRIV (dispatcher);
1347
1348   connection = empathy_contact_get_connection (contact);
1349   connection_data = g_hash_table_lookup (priv->connections, connection);
1350
1351   /* The contact handle might not be known yet */
1352   request_data = new_dispatcher_request_data (dispatcher, connection,
1353     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT,
1354     empathy_contact_get_handle (contact), NULL, contact, callback, user_data);
1355   request_data->should_ensure = TRUE;
1356
1357   connection_data->outstanding_requests = g_list_prepend
1358     (connection_data->outstanding_requests, request_data);
1359
1360   dispatcher_request_channel (request_data);
1361
1362   g_object_unref (dispatcher);
1363 }
1364
1365 typedef struct
1366 {
1367   EmpathyDispatcher *dispatcher;
1368   EmpathyDispatcherRequestCb *callback;
1369   gpointer user_data;
1370 } ChatWithContactIdData;
1371
1372 static void
1373 dispatcher_chat_with_contact_id_cb (EmpathyTpContactFactory *factory,
1374                                     EmpathyContact          *contact,
1375                                     const GError            *error,
1376                                     gpointer                 user_data,
1377                                     GObject                 *weak_object)
1378 {
1379   ChatWithContactIdData *data = user_data;
1380
1381   if (error)
1382     {
1383       /* FIXME: Should call data->callback with the error */
1384       DEBUG ("Error: %s", error->message);
1385     }
1386   else
1387     {
1388       empathy_dispatcher_chat_with_contact (contact, data->callback,
1389           data->user_data);
1390     }
1391
1392   g_object_unref (data->dispatcher);
1393   g_slice_free (ChatWithContactIdData, data);
1394 }
1395
1396 void
1397 empathy_dispatcher_chat_with_contact_id (TpConnection *connection,
1398                                          const gchar *contact_id,
1399                                          EmpathyDispatcherRequestCb *callback,
1400                                          gpointer user_data)
1401 {
1402   EmpathyDispatcher *dispatcher;
1403   EmpathyTpContactFactory *factory;
1404   ChatWithContactIdData *data;
1405
1406   g_return_if_fail (TP_IS_CONNECTION (connection));
1407   g_return_if_fail (!EMP_STR_EMPTY (contact_id));
1408
1409   dispatcher = empathy_dispatcher_dup_singleton ();
1410   factory = empathy_tp_contact_factory_dup_singleton (connection);
1411   data = g_slice_new0 (ChatWithContactIdData);
1412   data->dispatcher = dispatcher;
1413   data->callback = callback;
1414   data->user_data = user_data;
1415   empathy_tp_contact_factory_get_from_id (factory, contact_id,
1416       dispatcher_chat_with_contact_id_cb, data, NULL, NULL);
1417
1418   g_object_unref (factory);
1419 }
1420
1421 static void
1422 dispatcher_request_handles_cb (TpConnection *connection,
1423                                const GArray *handles,
1424                                const GError *error,
1425                                gpointer user_data,
1426                                GObject *object)
1427 {
1428   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1429
1430   if (error != NULL)
1431     {
1432       EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
1433       EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1434       ConnectionData *cd;
1435
1436       cd = g_hash_table_lookup (priv->connections, request_data->connection);
1437
1438       if (request_data->cb)
1439         request_data->cb (NULL, error, request_data->user_data);
1440
1441       cd->outstanding_requests = g_list_remove (cd->outstanding_requests,
1442         request_data);
1443
1444       free_dispatcher_request_data (request_data);
1445
1446       dispatcher_flush_outstanding_operations (dispatcher, cd);
1447       return;
1448     }
1449
1450   request_data->handle = g_array_index (handles, guint, 0);
1451   dispatcher_request_channel (request_data);
1452 }
1453
1454 void
1455 empathy_dispatcher_join_muc (TpConnection *connection,
1456                              const gchar *roomname,
1457                              EmpathyDispatcherRequestCb *callback,
1458                              gpointer user_data)
1459 {
1460   EmpathyDispatcher *dispatcher;
1461   EmpathyDispatcherPriv *priv;
1462   DispatcherRequestData *request_data;
1463   ConnectionData *connection_data;
1464   const gchar *names[] = { roomname, NULL };
1465
1466   g_return_if_fail (TP_IS_CONNECTION (connection));
1467   g_return_if_fail (!EMP_STR_EMPTY (roomname));
1468
1469   dispatcher = empathy_dispatcher_dup_singleton ();
1470   priv = GET_PRIV (dispatcher);
1471
1472   connection_data = g_hash_table_lookup (priv->connections, connection);
1473
1474   /* Don't know the room handle yet */
1475   request_data  = new_dispatcher_request_data (dispatcher, connection,
1476     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_ROOM, 0, NULL,
1477     NULL, callback, user_data);
1478
1479   connection_data->outstanding_requests = g_list_prepend
1480     (connection_data->outstanding_requests, request_data);
1481
1482   tp_cli_connection_call_request_handles (connection, -1,
1483     TP_HANDLE_TYPE_ROOM, names,
1484     dispatcher_request_handles_cb, request_data, NULL,
1485     G_OBJECT (dispatcher));
1486
1487   g_object_unref (dispatcher);
1488 }
1489
1490 static void
1491 dispatcher_create_channel_cb (TpConnection *connect,
1492                               const gchar *object_path,
1493                               GHashTable *properties,
1494                               const GError *error,
1495                               gpointer user_data,
1496                               GObject *weak_object)
1497 {
1498   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1499   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1500
1501   dispatcher_connection_new_requested_channel (dispatcher,
1502     request_data, object_path, properties, error);
1503 }
1504
1505 static void
1506 dispatcher_ensure_channel_cb (TpConnection *connect,
1507                               gboolean is_ours,
1508                               const gchar *object_path,
1509                               GHashTable *properties,
1510                               const GError *error,
1511                               gpointer user_data,
1512                               GObject *weak_object)
1513 {
1514   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1515   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1516
1517   dispatcher_connection_new_requested_channel (dispatcher,
1518     request_data, object_path, properties, error);
1519 }
1520
1521 static void
1522 empathy_dispatcher_call_create_or_ensure_channel (
1523     EmpathyDispatcher *dispatcher,
1524     DispatcherRequestData *request_data)
1525 {
1526   if (request_data->should_ensure)
1527     {
1528       tp_cli_connection_interface_requests_call_ensure_channel (
1529           request_data->connection, -1,
1530           request_data->request, dispatcher_ensure_channel_cb,
1531           request_data, NULL, G_OBJECT (request_data->dispatcher));
1532     }
1533   else
1534     {
1535       tp_cli_connection_interface_requests_call_create_channel (
1536           request_data->connection, -1,
1537           request_data->request, dispatcher_create_channel_cb,
1538           request_data, NULL, G_OBJECT (request_data->dispatcher));
1539     }
1540 }
1541
1542 void
1543 empathy_dispatcher_create_channel (EmpathyDispatcher *dispatcher,
1544                                    TpConnection *connection,
1545                                    GHashTable *request,
1546                                    EmpathyDispatcherRequestCb *callback,
1547                                    gpointer user_data)
1548 {
1549   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1550   ConnectionData *connection_data;
1551   DispatcherRequestData *request_data;
1552   const gchar *channel_type;
1553   guint handle_type;
1554   guint handle;
1555   gboolean valid;
1556
1557   g_return_if_fail (EMPATHY_IS_DISPATCHER (dispatcher));
1558   g_return_if_fail (TP_IS_CONNECTION (connection));
1559   g_return_if_fail (request != NULL);
1560
1561   connection_data = g_hash_table_lookup (priv->connections, connection);
1562   g_assert (connection_data != NULL);
1563
1564   channel_type = tp_asv_get_string (request, TP_IFACE_CHANNEL ".ChannelType");
1565
1566   handle_type = tp_asv_get_uint32 (request,
1567     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1568   if (!valid)
1569     handle_type = TP_UNKNOWN_HANDLE_TYPE;
1570
1571   handle = tp_asv_get_uint32 (request, TP_IFACE_CHANNEL ".TargetHandle", NULL);
1572
1573   request_data  = new_dispatcher_request_data (dispatcher, connection,
1574     channel_type, handle_type, handle, request,
1575     NULL, callback, user_data);
1576
1577   connection_data->outstanding_requests = g_list_prepend
1578     (connection_data->outstanding_requests, request_data);
1579
1580   empathy_dispatcher_call_create_or_ensure_channel (dispatcher, request_data);
1581 }
1582
1583 static gboolean
1584 channel_class_matches (GValueArray *class,
1585                        const char *channel_type,
1586                        guint handle_type,
1587                        GArray *fixed_properties)
1588 {
1589   GHashTable *fprops;
1590   GValue *v;
1591   const char *c_type;
1592   guint h_type;
1593   gboolean valid;
1594
1595   v = g_value_array_get_nth (class, 0);
1596
1597   /* if the class doesn't match channel type discard it. */
1598   fprops = g_value_get_boxed (v);
1599   c_type = tp_asv_get_string (fprops, TP_IFACE_CHANNEL ".ChannelType");
1600
1601   if (tp_strdiff (channel_type, c_type))
1602     return FALSE;
1603
1604   /* we have the right channel type, see if the handle type matches */
1605   h_type = tp_asv_get_uint32 (fprops,
1606                               TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1607
1608   if (!valid || handle_type != h_type)
1609     return FALSE;
1610
1611   if (fixed_properties != NULL)
1612     {
1613       gpointer h_key, h_val;
1614       int idx;
1615       GHashTableIter iter;
1616       gboolean found;
1617
1618       g_hash_table_iter_init (&iter, fprops);
1619
1620       while (g_hash_table_iter_next (&iter, &h_key, &h_val))
1621         {
1622           /* discard ChannelType and TargetHandleType, as we already
1623            * checked them.
1624            */
1625           if (!tp_strdiff ((char *) h_key, TP_IFACE_CHANNEL ".ChannelType") ||
1626               !tp_strdiff
1627                 ((char *) h_key, TP_IFACE_CHANNEL ".TargetHandleType"))
1628             continue;
1629
1630           found = FALSE;
1631
1632           for (idx = 0; idx < fixed_properties->len; idx++)
1633             {
1634               /* if |key| doesn't exist in |fixed_properties|, discard
1635                * the class.
1636                */
1637               if (!tp_strdiff
1638                     ((char *) h_key,
1639                      g_array_index (fixed_properties, char *, idx)))
1640                 {
1641                   found = TRUE;
1642                   /* exit the for() loop */
1643                   break;
1644                 }
1645             }
1646
1647           if (!found)
1648             return FALSE;
1649         }
1650     }
1651   else
1652     {
1653       /* if no fixed_properties are specified, discard the classes
1654        * with some fixed properties other than the two we already
1655        * checked.
1656        */
1657       if (g_hash_table_size (fprops) > 2)
1658         return FALSE;
1659     }
1660
1661   return TRUE;
1662 }
1663
1664 static GList *
1665 empathy_dispatcher_find_channel_classes (EmpathyDispatcher *dispatcher,
1666                                          TpConnection *connection,
1667                                          const gchar *channel_type,
1668                                          guint handle_type,
1669                                          GArray *fixed_properties)
1670 {
1671   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1672   GValueArray *class;
1673   GPtrArray *classes;
1674   GList *matching_classes;
1675   int i;
1676   ConnectionData *cd;
1677
1678   g_return_val_if_fail (channel_type != NULL, NULL);
1679   g_return_val_if_fail (handle_type != 0, NULL);
1680
1681   cd = g_hash_table_lookup (priv->connections, connection);
1682
1683   if (cd == NULL)
1684     return NULL;
1685
1686   classes = cd->requestable_channels;
1687   if (classes == NULL)
1688     return NULL;
1689
1690   matching_classes = NULL;
1691
1692   for (i = 0; i < classes->len; i++)
1693     {
1694       class = g_ptr_array_index (classes, i);
1695
1696       if (!channel_class_matches
1697           (class, channel_type, handle_type, fixed_properties))
1698         continue;
1699
1700       matching_classes = g_list_prepend (matching_classes, class);
1701     }
1702
1703   return matching_classes;
1704 }
1705
1706 static gboolean
1707 find_channel_class_idle_cb (gpointer user_data)
1708 {
1709   GList *retval;
1710   GList *requests;
1711   FindChannelRequest *request = user_data;
1712   ConnectionData *cd;
1713   gboolean is_ready = TRUE;
1714   EmpathyDispatcherPriv *priv = GET_PRIV (request->dispatcher);
1715
1716   g_hash_table_remove (priv->request_channel_class_async_ids, request);
1717
1718   cd = g_hash_table_lookup (priv->connections, request->connection);
1719
1720   if (cd == NULL)
1721     is_ready = FALSE;
1722   else if (cd->requestable_channels == NULL)
1723     is_ready = FALSE;
1724
1725   if (is_ready)
1726     {
1727       retval = empathy_dispatcher_find_channel_classes (request->dispatcher,
1728           request->connection, request->channel_type, request->handle_type,
1729           request->properties);
1730
1731       request->callback (retval, request->user_data);
1732       free_find_channel_request (request);
1733       g_list_free (retval);
1734
1735       return FALSE;
1736     }
1737
1738   requests = g_hash_table_lookup (priv->outstanding_classes_requests,
1739       request->connection);
1740   requests = g_list_prepend (requests, request);
1741
1742   g_hash_table_insert (priv->outstanding_classes_requests,
1743       request->connection, requests);
1744
1745   return FALSE;
1746 }
1747
1748 static GArray *
1749 setup_varargs (va_list var_args,
1750                const char *channel_namespace,
1751                const char *first_property_name)
1752 {
1753   const char *name;
1754   char *name_full;
1755   GArray *properties;
1756
1757   if (first_property_name == NULL)
1758     return NULL;
1759
1760   name = first_property_name;
1761   properties = g_array_new (TRUE, TRUE, sizeof (char *));
1762
1763   while (name != NULL)
1764     {
1765       name_full = g_strdup (name);
1766       properties = g_array_append_val (properties, name_full);
1767       name = va_arg (var_args, char *);
1768     }
1769
1770   return properties;
1771 }
1772
1773 /**
1774  * empathy_dispatcher_find_requestable_channel_classes:
1775  * @dispatcher: an #EmpathyDispatcher
1776  * @connection: a #TpConnection
1777  * @channel_type: a string identifying the type of the channel to lookup
1778  * @handle_type: the handle type for the channel
1779  * @first_property_name: %NULL, or the name of the first fixed property,
1780  * followed optionally by more names, followed by %NULL.
1781  *
1782  * Returns all the channel classes that a client can request for the connection
1783  * @connection, of the type identified by @channel_type, @handle_type and the
1784  * fixed properties list.
1785  * The classes which are compatible with a fixed properties list (i.e. those
1786  * that will be returned by this function) are intended as those that do not
1787  * contain any fixed property other than those in the list; note that this
1788  * doesn't guarantee that all the classes compatible with the list will contain
1789  * all the requested fixed properties, so the clients will have to filter
1790  * the returned list themselves.
1791  * If @first_property_name is %NULL, only the classes with no other fixed
1792  * properties than ChannelType and TargetHandleType will be returned.
1793  * Note that this function may return %NULL without performing any lookup if
1794  * @connection is not ready. To ensure that @connection is always ready,
1795  * use the empathy_dispatcher_find_requestable_channel_classes_async() variant.
1796  *
1797  * Return value: a #GList of #GValueArray objects, where the first element in
1798  * the array is a #GHashTable of the fixed properties, and the second is
1799  * a #GStrv of the allowed properties for the class. The list should be free'd
1800  * with g_list_free() when done, but the objects inside the list are owned
1801  * by the #EmpathyDispatcher and must not be modified.
1802  */
1803 GList *
1804 empathy_dispatcher_find_requestable_channel_classes
1805                                  (EmpathyDispatcher *dispatcher,
1806                                   TpConnection *connection,
1807                                   const gchar *channel_type,
1808                                   guint handle_type,
1809                                   const char *first_property_name,
1810                                   ...)
1811 {
1812   va_list var_args;
1813   GArray *properties;
1814   EmpathyDispatcherPriv *priv;
1815   GList *retval;
1816   int idx;
1817   char *str;
1818
1819   g_return_val_if_fail (EMPATHY_IS_DISPATCHER (dispatcher), NULL);
1820   g_return_val_if_fail (TP_IS_CONNECTION (connection), NULL);
1821   g_return_val_if_fail (channel_type != NULL, NULL);
1822   g_return_val_if_fail (handle_type != 0, NULL);
1823
1824   priv = GET_PRIV (dispatcher);
1825
1826   va_start (var_args, first_property_name);
1827
1828   properties = setup_varargs (var_args, channel_type, first_property_name);
1829
1830   va_end (var_args);
1831
1832   retval = empathy_dispatcher_find_channel_classes (dispatcher, connection,
1833     channel_type, handle_type, properties);
1834
1835   if (properties != NULL)
1836     {
1837       /* free the properties array */
1838       for (idx = 0; idx < properties->len ; idx++)
1839         {
1840           str = g_array_index (properties, char *, idx);
1841           g_free (str);
1842         }
1843
1844       g_array_free (properties, TRUE);
1845     }
1846
1847   return retval;
1848 }
1849
1850 /**
1851  * empathy_dispatcher_find_requestable_channel_classes_async:
1852  * @dispatcher: an #EmpathyDispatcher
1853  * @connection: a #TpConnection
1854  * @channel_type: a string identifying the type of the channel to lookup
1855  * @handle_type: the handle type for the channel
1856  * @callback: the callback to call when @connection is ready
1857  * @user_data: the user data to pass to @callback
1858  * @first_property_name: %NULL, or the name of the first fixed property,
1859  * followed optionally by more names, followed by %NULL.
1860  *
1861  * Please see the documentation of
1862  * empathy_dispatcher_find_requestable_channel_classes() for a detailed
1863  * description of this function.
1864  */
1865 void
1866 empathy_dispatcher_find_requestable_channel_classes_async
1867                                  (EmpathyDispatcher *dispatcher,
1868                                   TpConnection *connection,
1869                                   const gchar *channel_type,
1870                                   guint handle_type,
1871                                   EmpathyDispatcherFindChannelClassCb callback,
1872                                   gpointer user_data,
1873                                   const char *first_property_name,
1874                                   ...)
1875 {
1876   va_list var_args;
1877   GArray *properties;
1878   FindChannelRequest *request;
1879   EmpathyDispatcherPriv *priv;
1880   guint source_id;
1881
1882   g_return_if_fail (EMPATHY_IS_DISPATCHER (dispatcher));
1883   g_return_if_fail (TP_IS_CONNECTION (connection));
1884   g_return_if_fail (channel_type != NULL);
1885   g_return_if_fail (handle_type != 0);
1886
1887   priv = GET_PRIV (dispatcher);
1888
1889   va_start (var_args, first_property_name);
1890
1891   properties = setup_varargs (var_args, channel_type, first_property_name);
1892
1893   va_end (var_args);
1894
1895   /* append another request for this connection */
1896   request = g_slice_new0 (FindChannelRequest);
1897   request->dispatcher = g_object_ref (dispatcher);
1898   request->channel_type = g_strdup (channel_type);
1899   request->handle_type = handle_type;
1900   request->connection = connection;
1901   request->callback = callback;
1902   request->user_data = user_data;
1903   request->properties = properties;
1904
1905   source_id = g_idle_add (find_channel_class_idle_cb, request);
1906
1907   g_hash_table_insert (priv->request_channel_class_async_ids,
1908     request, GUINT_TO_POINTER (source_id));
1909 }
1910
1911 static GList *
1912 empathy_dispatcher_get_channels (EmpathyHandler *handler,
1913   gpointer user_data)
1914 {
1915   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (user_data);
1916   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1917
1918   return priv->channels;
1919 }
1920
1921 static gboolean
1922 empathy_dispatcher_handle_channels (EmpathyHandler *handler,
1923     const gchar *account_path,
1924     const gchar *connection_path,
1925     const GPtrArray *channels,
1926     const GPtrArray *requests_satisfied,
1927     guint64 timestamp,
1928     GHashTable *handler_info,
1929     gpointer user_data,
1930     GError **error)
1931 {
1932   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (user_data);
1933   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1934   int i;
1935   EmpathyAccount *account;
1936   TpConnection *connection;
1937
1938   account = empathy_account_manager_ensure_account (priv->account_manager,
1939     account_path);
1940   g_assert (account != NULL);
1941
1942   connection = empathy_account_get_connection_for_path (account,
1943       connection_path);
1944   if (connection == NULL)
1945     {
1946       g_set_error_literal (error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
1947         "Invalid connection argument");
1948       return FALSE;
1949     }
1950
1951   for (i = 0; i < channels->len ; i++)
1952     {
1953       GValueArray *arr = g_ptr_array_index (channels, i);
1954       const gchar *object_path;
1955       GHashTable *properties;
1956
1957       object_path = g_value_get_boxed (g_value_array_get_nth (arr, 0));
1958       properties = g_value_get_boxed (g_value_array_get_nth (arr, 1));
1959
1960       dispatcher_connection_new_channel_with_properties (dispatcher,
1961         connection, object_path, properties);
1962     }
1963
1964   return TRUE;
1965 }
1966
1967
1968 EmpathyHandler *
1969 empathy_dispatcher_add_handler (EmpathyDispatcher *dispatcher,
1970     const gchar *name,
1971     GPtrArray *filters,
1972     GStrv capabilities)
1973 {
1974   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1975   EmpathyHandler *handler;
1976
1977   handler = empathy_handler_new (name, filters, capabilities);
1978   priv->handlers = g_list_prepend (priv->handlers, handler);
1979
1980   /* Only set the handle_channels function, the Channel property on the main
1981    * handler will always report all dispatched channels even if they came from
1982    * a different Handler */
1983   empathy_handler_set_handle_channels_func (handler,
1984     empathy_dispatcher_handle_channels,
1985     dispatcher);
1986
1987   return handler;
1988 }
1989
1990 void
1991 empathy_dispatcher_remove_handler (EmpathyDispatcher *dispatcher,
1992   EmpathyHandler *handler)
1993 {
1994   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1995   GList *h;
1996
1997   h = g_list_find (priv->handlers, handler);
1998   g_return_if_fail (h != NULL);
1999
2000   priv->handlers = g_list_delete_link (priv->handlers, h);
2001
2002   g_object_unref (handler);
2003 }