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