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