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