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