]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
empathy_dispatcher_chat_with_contact_id: use TpAccountChannelRequest
[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   /* reffed (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   priv->channels = g_list_remove (priv->channels, proxy);
418
419   cd = g_hash_table_lookup (priv->connections, connection);
420   /* Connection itself invalidated? */
421   if (cd == NULL)
422     return;
423
424   object_path = tp_proxy_get_object_path (proxy);
425
426   DEBUG ("Channel %s invalidated", object_path);
427
428   g_hash_table_remove (cd->dispatched_channels, object_path);
429   g_hash_table_remove (cd->dispatching_channels, object_path);
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           case EMPATHY_DISPATCHER_OPERATION_STATE_DISPATCHING:
530           case EMPATHY_DISPATCHER_OPERATION_STATE_CLAIMED:
531           case EMPATHY_DISPATCHER_OPERATION_STATE_INVALIDATED:
532           default:
533             g_assert_not_reached ();
534         }
535
536     }
537   else if (empathy_dispatch_operation_get_status (operation) >=
538       EMPATHY_DISPATCHER_OPERATION_STATE_PENDING)
539     {
540       /* Already dispatching and the operation is pending, thus the observers
541        * have seen it (if applicable), so we can flush the request right away.
542        */
543       dispatch_operation_flush_requests (self, operation, NULL, cd);
544     }
545 }
546
547 static void
548 dispatcher_connection_new_channel (EmpathyDispatcher *self,
549                                    TpConnection *connection,
550                                    const gchar *object_path,
551                                    const gchar *channel_type,
552                                    guint handle_type,
553                                    guint handle,
554                                    GHashTable *properties,
555                                    gboolean incoming,
556                                    const GPtrArray *requests_satisfied,
557                                    gint64 timestamp)
558 {
559   EmpathyDispatcherPriv *priv = GET_PRIV (self);
560   TpChannel         *channel;
561   ConnectionData *cd;
562   EmpathyDispatchOperation *operation;
563   int i;
564   /* Channel types we never want to dispatch because they're either deprecated
565    * or can't sensibly be dispatch (e.g. channels that should always be
566    * requested) */
567   const char *blacklist[] = {
568     TP_IFACE_CHANNEL_TYPE_CONTACT_LIST,
569     TP_IFACE_CHANNEL_TYPE_TUBES,
570     TP_IFACE_CHANNEL_TYPE_ROOM_LIST,
571     NULL
572   };
573
574   dispatcher_init_connection_if_needed (self, connection);
575
576   cd = g_hash_table_lookup (priv->connections, connection);
577
578   for (i = 0 ; blacklist[i] != NULL; i++)
579     {
580       if (!tp_strdiff (channel_type, blacklist[i]))
581         {
582           DEBUG ("Ignoring blacklisted channel type %s on %s",
583             channel_type, object_path);
584           return;
585         }
586     }
587
588   DEBUG ("%s channel of type %s on %s", incoming ? "incoming" : "outgoing",
589     channel_type, object_path);
590
591   if (properties == NULL)
592     channel = tp_channel_new (connection, object_path, channel_type,
593       handle_type, handle, NULL);
594   else
595     channel = tp_channel_new_from_properties (connection, object_path,
596       properties, NULL);
597
598   g_signal_connect (channel, "invalidated",
599     G_CALLBACK (dispatcher_channel_invalidated_cb),
600     self);
601
602   priv->channels = g_list_prepend (priv->channels, channel);
603
604   operation = empathy_dispatch_operation_new (connection, channel, NULL,
605     incoming, timestamp);
606
607   g_object_unref (channel);
608
609   if (!incoming && requests_satisfied != NULL)
610     {
611       GList *l;
612       gboolean found = FALSE;
613
614       l = cd->outstanding_requests;
615
616       while (l != NULL)
617         {
618           DispatcherRequestData *d = (DispatcherRequestData *) l->data;
619           guint n;
620           const gchar *path;
621
622           l = g_list_next (l);
623           if (d->request == NULL)
624             continue;
625
626           if (d->operation != NULL)
627             continue;
628
629           path = tp_proxy_get_object_path (d->channel_request);
630           for (n = 0; n < requests_satisfied->len ; n++)
631             {
632               const gchar *p = g_ptr_array_index (requests_satisfied, n);
633               if (!tp_strdiff (p, path))
634                 {
635                   DEBUG ("Channel satified request %s"
636                    "(already dispatched: %d)", p, found);
637                   if (!found)
638                     {
639                       d->operation = operation;
640                       found = TRUE;
641                       continue;
642                     }
643                   else
644                     {
645                       GError err = { TP_ERRORS, TP_ERROR_NOT_YOURS,
646                         "Not yours!" };
647                       dispatcher_request_failed (dispatcher, d, &err);
648                     }
649                 }
650             }
651         }
652     }
653
654   dispatcher_start_dispatching (dispatcher, operation, cd);
655 }
656
657 static void
658 dispatcher_connection_new_channel_with_properties (
659     EmpathyDispatcher *self,
660     TpConnection *connection,
661     const gchar *object_path,
662     GHashTable *properties,
663     const GPtrArray *requests_satisfied,
664     gint64 timestamp)
665 {
666   const gchar *channel_type;
667   guint handle_type;
668   guint handle;
669   gboolean requested;
670   gboolean valid;
671
672   channel_type = tp_asv_get_string (properties,
673     TP_IFACE_CHANNEL ".ChannelType");
674   if (channel_type == NULL)
675     {
676       g_message ("%s had an invalid ChannelType property", object_path);
677       return;
678     }
679
680   handle_type = tp_asv_get_uint32 (properties,
681     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
682   if (!valid)
683     {
684       g_message ("%s had an invalid TargetHandleType property", object_path);
685       return;
686     }
687
688   handle = tp_asv_get_uint32 (properties,
689     TP_IFACE_CHANNEL ".TargetHandle", &valid);
690   if (!valid)
691     {
692       g_message ("%s had an invalid TargetHandle property", object_path);
693       return;
694     }
695
696   /* We assume there is no channel dispather, so we're the only one dispatching
697    * it. Which means that a requested channel it is outgoing one */
698   requested = tp_asv_get_boolean (properties,
699     TP_IFACE_CHANNEL ".Requested", &valid);
700   if (!valid)
701     {
702       g_message ("%s had an invalid Requested property", object_path);
703       requested = FALSE;
704     }
705
706   dispatcher_connection_new_channel (self, connection,
707     object_path, channel_type, handle_type, handle, properties, !requested,
708     requests_satisfied, timestamp);
709 }
710
711 static void
712 dispatcher_connection_got_all (TpProxy *proxy,
713                                GHashTable *properties,
714                                const GError *error,
715                                gpointer user_data,
716                                GObject *object)
717 {
718   EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
719   EmpathyDispatcherPriv *priv = GET_PRIV (self);
720   GPtrArray *requestable_channels;
721
722   if (error) {
723     DEBUG ("Error: %s", error->message);
724     return;
725   }
726
727   requestable_channels = tp_asv_get_boxed (properties,
728     "RequestableChannelClasses", TP_ARRAY_TYPE_REQUESTABLE_CHANNEL_CLASS_LIST);
729
730   if (requestable_channels == NULL)
731     DEBUG ("No RequestableChannelClasses property !?! on connection");
732   else
733     {
734       ConnectionData *cd;
735       GList *requests, *l;
736       FindChannelRequest *request;
737       GList *retval;
738
739       cd = g_hash_table_lookup (priv->connections, proxy);
740       g_assert (cd != NULL);
741
742       cd->requestable_channels = g_boxed_copy (
743         TP_ARRAY_TYPE_REQUESTABLE_CHANNEL_CLASS_LIST, requestable_channels);
744
745       requests = g_hash_table_lookup (priv->outstanding_classes_requests,
746           proxy);
747
748       for (l = requests; l != NULL; l = l->next)
749         {
750           request = l->data;
751
752           retval = empathy_dispatcher_find_channel_classes (self,
753               TP_CONNECTION (proxy), request->channel_type,
754               request->handle_type, request->properties);
755           request->callback (retval, request->user_data);
756
757           free_find_channel_request (request);
758           g_list_free (retval);
759         }
760
761       g_list_free (requests);
762
763       g_hash_table_remove (priv->outstanding_classes_requests, proxy);
764     }
765 }
766
767 static void
768 connection_ready_cb (TpConnection *connection,
769     const GError *error,
770     gpointer user_data)
771 {
772   EmpathyDispatcher *self = EMPATHY_DISPATCHER (user_data);
773
774   if (error != NULL)
775     {
776       DEBUG ("Error: %s", error->message);
777       goto out;
778     }
779
780   tp_cli_dbus_properties_call_get_all (connection, -1,
781       TP_IFACE_CONNECTION_INTERFACE_REQUESTS, dispatcher_connection_got_all,
782       NULL, NULL, G_OBJECT (self));
783
784 out:
785   g_object_unref (self);
786 }
787
788 static void
789 dispatcher_init_connection_if_needed (EmpathyDispatcher *self,
790     TpConnection *connection)
791 {
792   EmpathyDispatcherPriv *priv = GET_PRIV (self);
793
794   if (g_hash_table_lookup (priv->connections, connection) != NULL)
795     return;
796
797   g_hash_table_insert (priv->connections, g_object_ref (connection),
798     new_connection_data ());
799
800   g_signal_connect (connection, "invalidated",
801     G_CALLBACK (dispatcher_connection_invalidated_cb), self);
802
803   /* Ensure to keep the self object alive while the call_when_ready is
804    * running */
805   g_object_ref (self);
806   tp_connection_call_when_ready (connection, connection_ready_cb, self);
807 }
808
809 static void
810 dispatcher_status_changed_cb (TpAccount *account,
811                               guint old_status,
812                               guint new_status,
813                               guint reason,
814                               gchar *dbus_error_name,
815                               GHashTable *details,
816                               EmpathyDispatcher *self)
817 {
818   TpConnection *conn = tp_account_get_connection (account);
819
820   if (conn != NULL)
821     dispatcher_init_connection_if_needed (self, conn);
822 }
823
824 static void
825 remove_idle_handlers (gpointer key,
826                       gpointer value,
827                       gpointer user_data)
828 {
829   guint source_id;
830
831   source_id = GPOINTER_TO_UINT (value);
832   g_source_remove (source_id);
833 }
834
835 static GObject *
836 dispatcher_constructor (GType type,
837                         guint n_construct_params,
838                         GObjectConstructParam *construct_params)
839 {
840   GObject *retval;
841   EmpathyDispatcherPriv *priv;
842
843   if (dispatcher != NULL)
844     return g_object_ref (dispatcher);
845
846   retval = G_OBJECT_CLASS (empathy_dispatcher_parent_class)->constructor
847     (type, n_construct_params, construct_params);
848
849   dispatcher = EMPATHY_DISPATCHER (retval);
850   g_object_add_weak_pointer (retval, (gpointer) &dispatcher);
851
852   priv = GET_PRIV (dispatcher);
853
854   if (priv->handler == NULL)
855     priv->handler = empathy_handler_new (NULL, NULL, NULL);
856
857   empathy_handler_set_handle_channels_func (priv->handler,
858     empathy_dispatcher_handle_channels,
859     dispatcher);
860
861   empathy_handler_set_channels_func (priv->handler,
862     empathy_dispatcher_get_channels,
863     dispatcher);
864
865   return retval;
866 }
867
868 static void
869 dispatcher_dispose (GObject *object)
870 {
871   EmpathyDispatcherPriv *priv = GET_PRIV (object);
872   GHashTableIter iter;
873   gpointer connection;
874   GList *l;
875
876   if (priv->dispose_has_run)
877     return;
878
879   priv->dispose_has_run = TRUE;
880
881   for (l = priv->handlers ; l != NULL; l = g_list_next (l))
882     g_object_unref (G_OBJECT (l->data));
883
884   g_list_free (priv->handlers);
885   priv->handlers = NULL;
886
887   if (priv->handler != NULL)
888     g_object_unref (priv->handler);
889   priv->handler = NULL;
890
891   g_hash_table_iter_init (&iter, priv->connections);
892   while (g_hash_table_iter_next (&iter, &connection, NULL))
893     {
894       g_signal_handlers_disconnect_by_func (connection,
895           dispatcher_connection_invalidated_cb, object);
896     }
897
898   g_hash_table_destroy (priv->connections);
899   priv->connections = NULL;
900
901   if (priv->channel_dispatcher != NULL)
902     g_object_unref (priv->channel_dispatcher);
903   priv->channel_dispatcher = NULL;
904
905   if (priv->dbus != NULL)
906     g_object_unref (priv->dbus);
907   priv->dbus = NULL;
908
909   G_OBJECT_CLASS (empathy_dispatcher_parent_class)->dispose (object);
910 }
911
912 static void
913 dispatcher_finalize (GObject *object)
914 {
915   EmpathyDispatcherPriv *priv = GET_PRIV (object);
916   GList *l;
917   GHashTableIter iter;
918   gpointer connection;
919   GList *list;
920   gpointer account, id;
921
922   if (priv->request_channel_class_async_ids != NULL)
923     {
924       g_hash_table_foreach (priv->request_channel_class_async_ids,
925         remove_idle_handlers, NULL);
926       g_hash_table_destroy (priv->request_channel_class_async_ids);
927     }
928
929   for (l = priv->channels; l; l = l->next)
930     {
931       g_signal_handlers_disconnect_by_func (l->data,
932           dispatcher_channel_invalidated_cb, object);
933     }
934
935   g_list_free (priv->channels);
936
937   g_hash_table_iter_init (&iter, priv->outstanding_classes_requests);
938   while (g_hash_table_iter_next (&iter, &connection, (gpointer *) &list))
939     {
940       g_list_foreach (list, (GFunc) free_find_channel_request, NULL);
941       g_list_free (list);
942     }
943
944   g_hash_table_iter_init (&iter, priv->status_changed_handlers);
945   while (g_hash_table_iter_next (&iter, &account, &id))
946     {
947       g_signal_handler_disconnect (account, GPOINTER_TO_UINT (id));
948     }
949   g_hash_table_destroy (priv->status_changed_handlers);
950
951   g_object_unref (priv->account_manager);
952
953   g_hash_table_destroy (priv->outstanding_classes_requests);
954 }
955
956 static void
957 dispatcher_set_property (GObject *object,
958   guint property_id,
959   const GValue *value,
960   GParamSpec *pspec)
961 {
962   EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
963   EmpathyDispatcherPriv *priv = GET_PRIV (self);
964
965   switch (property_id)
966     {
967       case PROP_HANDLER:
968         priv->handler = g_value_dup_object (value);
969         break;
970       default:
971         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
972         break;
973     }
974 }
975
976 static void
977 dispatcher_get_property (GObject *object,
978   guint property_id,
979   GValue *value,
980   GParamSpec *pspec)
981 {
982   EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
983   EmpathyDispatcherPriv *priv = GET_PRIV (self);
984
985   switch (property_id)
986     {
987       case PROP_HANDLER:
988         g_value_set_object (value, priv->handler);
989         break;
990       default:
991         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
992         break;
993     }
994 }
995
996 static void
997 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
998 {
999   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1000   GParamSpec *param_spec;
1001
1002   object_class->dispose = dispatcher_dispose;
1003   object_class->finalize = dispatcher_finalize;
1004   object_class->constructor = dispatcher_constructor;
1005
1006   object_class->get_property = dispatcher_get_property;
1007   object_class->set_property = dispatcher_set_property;
1008
1009   param_spec = g_param_spec_object ("handler", "handler",
1010     "The main Telepathy Client Hander object",
1011     EMPATHY_TYPE_HANDLER,
1012     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT_ONLY);
1013   g_object_class_install_property (object_class,
1014     PROP_HANDLER, param_spec);
1015
1016   signals[OBSERVE] =
1017     g_signal_new ("observe",
1018       G_TYPE_FROM_CLASS (klass),
1019       G_SIGNAL_RUN_LAST,
1020       0,
1021       NULL, NULL,
1022       g_cclosure_marshal_VOID__OBJECT,
1023       G_TYPE_NONE,
1024       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1025
1026   signals[DISPATCH] =
1027     g_signal_new ("dispatch",
1028       G_TYPE_FROM_CLASS (klass),
1029       G_SIGNAL_RUN_LAST,
1030       0,
1031       NULL, NULL,
1032       g_cclosure_marshal_VOID__OBJECT,
1033       G_TYPE_NONE,
1034       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1035
1036
1037   g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
1038 }
1039
1040 static void
1041 connect_account (EmpathyDispatcher *self,
1042     TpAccount *account)
1043 {
1044   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1045   TpConnection *conn = tp_account_get_connection (account);
1046   gulong id;
1047
1048   id = GPOINTER_TO_UINT (g_hash_table_lookup (priv->status_changed_handlers,
1049         account));
1050
1051   if (id != 0)
1052     return;
1053
1054   if (conn != NULL)
1055     dispatcher_status_changed_cb (account, 0, 0, 0, NULL, NULL, self);
1056
1057   id = g_signal_connect (account, "status-changed",
1058       G_CALLBACK (dispatcher_status_changed_cb), self);
1059
1060   g_hash_table_insert (priv->status_changed_handlers, g_object_ref (account),
1061       GUINT_TO_POINTER (id));
1062 }
1063
1064 static void
1065 account_manager_prepared_cb (GObject *source_object,
1066                              GAsyncResult *result,
1067                              gpointer user_data)
1068 {
1069   GList *accounts, *l;
1070   EmpathyDispatcher *self = user_data;
1071   TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
1072   GError *error = NULL;
1073
1074   if (!tp_account_manager_prepare_finish (account_manager, result, &error))
1075     {
1076       DEBUG ("Failed to prepare account manager: %s", error->message);
1077       g_error_free (error);
1078       return;
1079     }
1080
1081   accounts = tp_account_manager_get_valid_accounts (account_manager);
1082   for (l = accounts; l; l = l->next)
1083     {
1084       TpAccount *a = l->data;
1085
1086       connect_account (self, a);
1087     }
1088
1089   g_list_foreach (accounts, (GFunc) g_object_ref, NULL);
1090   g_list_free (accounts);
1091 }
1092
1093 static void
1094 account_prepare_cb (GObject *source_object,
1095     GAsyncResult *result,
1096     gpointer user_data)
1097 {
1098   EmpathyDispatcher *self = user_data;
1099   TpAccount *account = TP_ACCOUNT (source_object);
1100   GError *error = NULL;
1101
1102   if (!tp_account_prepare_finish (account, result, &error))
1103     {
1104       DEBUG ("Failed to prepare account: %s", error->message);
1105       g_error_free (error);
1106       return;
1107     }
1108
1109   connect_account (self, account);
1110 }
1111
1112 static void
1113 account_validity_changed_cb (TpAccountManager *manager,
1114     TpAccount *account,
1115     gboolean valid,
1116     gpointer user_data)
1117 {
1118   if (!valid)
1119     return;
1120
1121   tp_account_prepare_async (account, NULL, account_prepare_cb, user_data);
1122 }
1123
1124 static void
1125 empathy_dispatcher_init (EmpathyDispatcher *self)
1126 {
1127   EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
1128     EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
1129
1130   self->priv = priv;
1131   priv->account_manager = tp_account_manager_dup ();
1132
1133   priv->connections = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1134     g_object_unref, (GDestroyNotify) free_connection_data);
1135
1136   priv->outstanding_classes_requests = g_hash_table_new_full (g_direct_hash,
1137     g_direct_equal, g_object_unref, NULL);
1138
1139   priv->channels = NULL;
1140
1141   tp_account_manager_prepare_async (priv->account_manager, NULL,
1142       account_manager_prepared_cb, self);
1143
1144   tp_g_signal_connect_object (priv->account_manager,
1145       "account-validity-changed", G_CALLBACK (account_validity_changed_cb),
1146       self, 0);
1147
1148   priv->request_channel_class_async_ids = g_hash_table_new (g_direct_hash,
1149     g_direct_equal);
1150   priv->status_changed_handlers = g_hash_table_new_full (NULL, NULL,
1151       (GDestroyNotify) g_object_unref, NULL);
1152
1153   priv->dbus = tp_dbus_daemon_dup (NULL);
1154   priv->channel_dispatcher = tp_channel_dispatcher_new (priv->dbus);
1155 }
1156
1157 EmpathyDispatcher *
1158 empathy_dispatcher_new (const gchar *name,
1159   GPtrArray *filters,
1160   GStrv capabilities)
1161 {
1162   EmpathyHandler *handler;
1163   EmpathyDispatcher *ret;
1164
1165   g_assert (dispatcher == NULL);
1166   handler = empathy_handler_new (name, filters, capabilities);
1167
1168   ret = EMPATHY_DISPATCHER (
1169     g_object_new (EMPATHY_TYPE_DISPATCHER,
1170       "handler", handler,
1171       NULL));
1172   g_object_unref (handler);
1173
1174   return ret;
1175 }
1176
1177 EmpathyDispatcher *
1178 empathy_dispatcher_dup_singleton (void)
1179 {
1180   return EMPATHY_DISPATCHER (g_object_new (EMPATHY_TYPE_DISPATCHER, NULL));
1181 }
1182
1183 static void
1184 dispatcher_request_failed (EmpathyDispatcher *self,
1185                            DispatcherRequestData *request_data,
1186                            const GError *error)
1187 {
1188   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1189   ConnectionData *conn_data;
1190
1191   conn_data = g_hash_table_lookup (priv->connections,
1192       request_data->connection);
1193   if (request_data->cb != NULL)
1194     request_data->cb (NULL, error, request_data->user_data);
1195
1196   if (conn_data != NULL)
1197     {
1198       conn_data->outstanding_requests =
1199           g_list_remove (conn_data->outstanding_requests, request_data);
1200     }
1201   /* else Connection has been invalidated */
1202
1203   free_dispatcher_request_data (request_data);
1204 }
1205
1206 static void
1207 dispatcher_request_channel (DispatcherRequestData *request_data)
1208 {
1209   /* Extend the request_data to be a valid request */
1210   g_assert (request_data->request == NULL);
1211   request_data->request = tp_asv_new (
1212       TP_IFACE_CHANNEL ".ChannelType",
1213         G_TYPE_STRING, request_data->channel_type,
1214       TP_IFACE_CHANNEL ".TargetHandleType",
1215         G_TYPE_UINT, request_data->handle_type,
1216       NULL);
1217
1218   if (request_data->handle_type != TP_HANDLE_TYPE_NONE)
1219     tp_asv_set_uint32 (request_data->request, TP_IFACE_CHANNEL ".TargetHandle",
1220         request_data->handle);
1221
1222   empathy_dispatcher_call_create_or_ensure_channel (request_data->dispatcher,
1223       request_data);
1224 }
1225
1226 void
1227 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1228                                       gint64 timestamp,
1229                                       EmpathyDispatcherRequestCb *callback,
1230                                       gpointer user_data)
1231 {
1232   EmpathyDispatcher *self;
1233   EmpathyDispatcherPriv *priv;
1234   TpConnection *connection;
1235   ConnectionData *connection_data;
1236   DispatcherRequestData *request_data;
1237
1238   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1239
1240   self = empathy_dispatcher_dup_singleton ();
1241   priv = GET_PRIV (self);
1242
1243   connection = empathy_contact_get_connection (contact);
1244   connection_data = g_hash_table_lookup (priv->connections, connection);
1245   if (connection_data == NULL)
1246     {
1247       /* Connection has been invalidated */
1248       if (callback != NULL)
1249         {
1250           GError error = { TP_DBUS_ERRORS, TP_DBUS_ERROR_PROXY_UNREFERENCED,
1251               "Connection has been invalidated" };
1252           callback (NULL, &error, user_data);
1253         }
1254       goto out;
1255     }
1256
1257   /* The contact handle might not be known yet */
1258   request_data = new_dispatcher_request_data (self, connection,
1259     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT,
1260     empathy_contact_get_handle (contact), NULL, timestamp, contact,
1261     callback, user_data);
1262   request_data->should_ensure = TRUE;
1263
1264   connection_data->outstanding_requests = g_list_prepend
1265     (connection_data->outstanding_requests, request_data);
1266
1267   dispatcher_request_channel (request_data);
1268
1269 out:
1270   g_object_unref (self);
1271 }
1272
1273 static void
1274 ensure_text_channel_cb (GObject *source,
1275     GAsyncResult *result,
1276     gpointer user_data)
1277 {
1278   GError *error = NULL;
1279
1280   if (!tp_account_channel_request_ensure_channel_finish (
1281         TP_ACCOUNT_CHANNEL_REQUEST (source), result, &error))
1282     {
1283       DEBUG ("Failed to ensure text channel: %s", error->message);
1284       g_error_free (error);
1285     }
1286 }
1287
1288 void
1289 empathy_dispatcher_chat_with_contact_id (TpAccount *account,
1290     const gchar *contact_id,
1291     gint64 timestamp)
1292 {
1293   GHashTable *request;
1294   TpAccountChannelRequest *req;
1295
1296   request = tp_asv_new (
1297       TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
1298         TP_IFACE_CHANNEL_TYPE_TEXT,
1299       TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT, TP_HANDLE_TYPE_CONTACT,
1300       TP_PROP_CHANNEL_TARGET_ID, G_TYPE_STRING, contact_id,
1301       NULL);
1302
1303   req = tp_account_channel_request_new (account, request, timestamp);
1304
1305   tp_account_channel_request_ensure_channel_async (req, NULL, NULL,
1306       ensure_text_channel_cb, NULL);
1307
1308   g_hash_table_unref (request);
1309   g_object_unref (req);
1310 }
1311
1312 static void
1313 dispatcher_request_handles_cb (TpConnection *connection,
1314                                const GArray *handles,
1315                                const GError *error,
1316                                gpointer user_data,
1317                                GObject *object)
1318 {
1319   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1320
1321   request_data->pending_call = NULL;
1322
1323   if (error != NULL)
1324     {
1325       EmpathyDispatcher *self = request_data->dispatcher;
1326       EmpathyDispatcherPriv *priv = GET_PRIV (self);
1327       ConnectionData *cd;
1328
1329       cd = g_hash_table_lookup (priv->connections, request_data->connection);
1330
1331       if (request_data->cb)
1332         request_data->cb (NULL, error, request_data->user_data);
1333
1334       cd->outstanding_requests = g_list_remove (cd->outstanding_requests,
1335         request_data);
1336
1337       free_dispatcher_request_data (request_data);
1338       return;
1339     }
1340
1341   request_data->handle = g_array_index (handles, guint, 0);
1342   dispatcher_request_channel (request_data);
1343 }
1344
1345 void
1346 empathy_dispatcher_join_muc (TpConnection *connection,
1347                              const gchar *roomname,
1348                              gint64 timestamp)
1349 {
1350   EmpathyDispatcher *self;
1351   EmpathyDispatcherPriv *priv;
1352   DispatcherRequestData *request_data;
1353   ConnectionData *connection_data;
1354   const gchar *names[] = { roomname, NULL };
1355   TpProxyPendingCall *call;
1356
1357   g_return_if_fail (TP_IS_CONNECTION (connection));
1358   g_return_if_fail (!EMP_STR_EMPTY (roomname));
1359
1360   self = empathy_dispatcher_dup_singleton ();
1361   priv = GET_PRIV (self);
1362
1363   connection_data = g_hash_table_lookup (priv->connections, connection);
1364   g_assert (connection_data != NULL);
1365
1366   /* Don't know the room handle yet */
1367   request_data  = new_dispatcher_request_data (self, connection,
1368     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_ROOM, 0, NULL, timestamp,
1369     NULL, NULL, NULL);
1370   request_data->should_ensure = TRUE;
1371
1372   connection_data->outstanding_requests = g_list_prepend
1373     (connection_data->outstanding_requests, request_data);
1374
1375   call = tp_cli_connection_call_request_handles (
1376     connection, -1,
1377     TP_HANDLE_TYPE_ROOM, names,
1378     dispatcher_request_handles_cb, request_data, NULL, NULL);
1379
1380   if (call != NULL)
1381     request_data->pending_call = call;
1382
1383   g_object_unref (self);
1384 }
1385
1386 static void
1387 dispatcher_channel_request_failed_cb (TpChannelRequest *request,
1388   const gchar *error,
1389   const gchar *message,
1390   gpointer user_data,
1391   GObject *weak_object)
1392 {
1393   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1394   EmpathyDispatcher *self =
1395       EMPATHY_DISPATCHER (request_data->dispatcher);
1396   GError *err = NULL;
1397
1398   request_data->pending_call = NULL;
1399
1400   DEBUG ("Request failed: %s - %s %s",
1401     tp_proxy_get_object_path (request),
1402     error, message);
1403
1404   tp_proxy_dbus_error_to_gerror (TP_PROXY (request),
1405     error, message, &err);
1406
1407   dispatcher_request_failed (self, request_data, err);
1408
1409   g_error_free (err);
1410 }
1411
1412 static void
1413 dispatcher_channel_request_succeeded_cb (TpChannelRequest *request,
1414   gpointer user_data,
1415   GObject *weak_object)
1416 {
1417   EmpathyDispatcher *self = EMPATHY_DISPATCHER (weak_object);
1418   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1419   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1420   ConnectionData *conn_data;
1421
1422   conn_data = g_hash_table_lookup (priv->connections,
1423     request_data->connection);
1424
1425   DEBUG ("Request succeeded: %s", tp_proxy_get_object_path (request));
1426
1427   /* When success gets called the internal request should have been satisfied,
1428    * if it's still in outstanding_requests and doesn't have an operation
1429    * assigned to it, the channel got handled by someone else.. */
1430
1431   if (g_list_find (conn_data->outstanding_requests, request_data) == NULL)
1432     return;
1433
1434   if (request_data->operation == NULL)
1435     {
1436       GError err = { TP_ERRORS, TP_ERROR_NOT_YOURS, "Not yours!" };
1437       dispatcher_request_failed (self, request_data, &err);
1438     }
1439 }
1440
1441 static void
1442 dispatcher_channel_request_proceed_cb (TpChannelRequest *request,
1443   const GError *error,
1444   gpointer user_data,
1445   GObject *weak_object)
1446 {
1447   EmpathyDispatcher *self = EMPATHY_DISPATCHER (weak_object);
1448   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1449
1450   request_data->pending_call = NULL;
1451
1452   if (error != NULL)
1453     dispatcher_request_failed (self, request_data, error);
1454 }
1455
1456 static void
1457 dispatcher_create_channel_cb (TpChannelDispatcher *proxy,
1458     const gchar *request_path,
1459     const GError *error,
1460     gpointer user_data,
1461     GObject *weak_object)
1462 {
1463   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1464   EmpathyDispatcher *self = EMPATHY_DISPATCHER (request_data->dispatcher);
1465   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1466   TpChannelRequest *request;
1467   GError *err = NULL;
1468   TpProxyPendingCall *call;
1469
1470   request_data->pending_call = NULL;
1471
1472   if (error != NULL)
1473     {
1474       dispatcher_request_failed (self, request_data, error);
1475       return;
1476     }
1477
1478   request = tp_channel_request_new (priv->dbus, request_path, NULL, NULL);
1479   request_data->channel_request = request;
1480
1481   if (tp_cli_channel_request_connect_to_failed (request,
1482       dispatcher_channel_request_failed_cb, request_data,
1483       NULL, G_OBJECT (self), &err) == NULL)
1484     {
1485       dispatcher_request_failed (self, request_data, err);
1486       g_error_free (err);
1487       return;
1488     }
1489
1490   if (tp_cli_channel_request_connect_to_succeeded (request,
1491       dispatcher_channel_request_succeeded_cb, request_data,
1492       NULL, G_OBJECT (self), &err) == NULL)
1493     {
1494       dispatcher_request_failed (self, request_data, err);
1495       g_error_free (err);
1496       return;
1497     }
1498
1499   call = tp_cli_channel_request_call_proceed (request,
1500     -1, dispatcher_channel_request_proceed_cb,
1501     request_data, NULL, G_OBJECT (self));
1502
1503   if (call != NULL)
1504     request_data->pending_call = call;
1505 }
1506
1507 static void
1508 empathy_dispatcher_call_create_or_ensure_channel (
1509     EmpathyDispatcher *self,
1510     DispatcherRequestData *request_data)
1511 {
1512   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1513   TpAccount *account;
1514   const gchar *handler = "";
1515   TpProxyPendingCall *call;
1516
1517   account = empathy_get_account_for_connection (request_data->connection);
1518
1519   g_assert (account != NULL);
1520
1521   if (request_data->cb)
1522     handler = empathy_handler_get_busname (priv->handler);
1523
1524   if (request_data->should_ensure)
1525     {
1526       call = tp_cli_channel_dispatcher_call_ensure_channel (
1527           priv->channel_dispatcher,
1528           -1, tp_proxy_get_object_path (TP_PROXY (account)),
1529           request_data->request, request_data->timestamp, handler,
1530           dispatcher_create_channel_cb, request_data, NULL, NULL);
1531     }
1532   else
1533     {
1534       call = tp_cli_channel_dispatcher_call_create_channel (
1535           priv->channel_dispatcher,
1536           -1, tp_proxy_get_object_path (TP_PROXY (account)),
1537           request_data->request, request_data->timestamp, handler,
1538           dispatcher_create_channel_cb, request_data, NULL,
1539           G_OBJECT (dispatcher));
1540     }
1541
1542   if (call != NULL)
1543     request_data->pending_call = call;
1544 }
1545
1546 /**
1547  * empathy_dispatcher_create_channel:
1548  * @self: the EmpathyDispatcher
1549  * @connection: the Connection to dispatch on
1550  * @request: an a{sv} map of properties for the request, i.e. using tp_asv_new()
1551  * @callback: a callback for when the channel arrives (or NULL)
1552  * @user_data: optional user data (or NULL)
1553  *
1554  * When calling this function, #EmpathyDispatcher takes ownership of your
1555  * reference to @request. DO NOT unref or destroy @request. When the request is
1556  * done, @request will be unreferenced. Take another reference if you want to
1557  * keep it around.
1558  */
1559 void
1560 empathy_dispatcher_create_channel (EmpathyDispatcher *self,
1561                                    TpConnection *connection,
1562                                    GHashTable *request,
1563                                    gint64 timestamp,
1564                                    EmpathyDispatcherRequestCb *callback,
1565                                    gpointer user_data)
1566 {
1567   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1568   ConnectionData *connection_data;
1569   DispatcherRequestData *request_data;
1570   const gchar *channel_type;
1571   guint handle_type;
1572   guint handle;
1573   gboolean valid;
1574
1575   g_return_if_fail (EMPATHY_IS_DISPATCHER (self));
1576   g_return_if_fail (TP_IS_CONNECTION (connection));
1577   g_return_if_fail (request != NULL);
1578
1579   connection_data = g_hash_table_lookup (priv->connections, connection);
1580   g_assert (connection_data != NULL);
1581
1582   channel_type = tp_asv_get_string (request, TP_IFACE_CHANNEL ".ChannelType");
1583
1584   handle_type = tp_asv_get_uint32 (request,
1585     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1586   if (!valid)
1587     handle_type = TP_UNKNOWN_HANDLE_TYPE;
1588
1589   handle = tp_asv_get_uint32 (request, TP_IFACE_CHANNEL ".TargetHandle", NULL);
1590
1591   request_data  = new_dispatcher_request_data (self, connection,
1592     channel_type, handle_type, handle, request, timestamp,
1593     NULL, callback, user_data);
1594
1595   connection_data->outstanding_requests = g_list_prepend
1596     (connection_data->outstanding_requests, request_data);
1597
1598   empathy_dispatcher_call_create_or_ensure_channel (self, request_data);
1599 }
1600
1601 static gboolean
1602 channel_class_matches (GValueArray *class,
1603                        const char *channel_type,
1604                        guint handle_type,
1605                        GArray *fixed_properties)
1606 {
1607   GHashTable *fprops;
1608   GValue *v;
1609   const char *c_type;
1610   guint h_type;
1611   gboolean valid;
1612
1613   v = g_value_array_get_nth (class, 0);
1614
1615   /* if the class doesn't match channel type discard it. */
1616   fprops = g_value_get_boxed (v);
1617   c_type = tp_asv_get_string (fprops, TP_IFACE_CHANNEL ".ChannelType");
1618
1619   if (tp_strdiff (channel_type, c_type))
1620     return FALSE;
1621
1622   /* we have the right channel type, see if the handle type matches */
1623   h_type = tp_asv_get_uint32 (fprops,
1624                               TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1625
1626   if (!valid || (handle_type != h_type && handle_type != TP_UNKNOWN_HANDLE_TYPE))
1627     return FALSE;
1628
1629   if (fixed_properties != NULL)
1630     {
1631       gpointer h_key, h_val;
1632       guint idx;
1633       GHashTableIter iter;
1634       gboolean found;
1635
1636       g_hash_table_iter_init (&iter, fprops);
1637
1638       while (g_hash_table_iter_next (&iter, &h_key, &h_val))
1639         {
1640           /* discard ChannelType and TargetHandleType, as we already
1641            * checked them.
1642            */
1643           if (!tp_strdiff ((char *) h_key, TP_IFACE_CHANNEL ".ChannelType") ||
1644               !tp_strdiff
1645                 ((char *) h_key, TP_IFACE_CHANNEL ".TargetHandleType"))
1646             continue;
1647
1648           found = FALSE;
1649
1650           for (idx = 0; idx < fixed_properties->len; idx++)
1651             {
1652               /* if |key| doesn't exist in |fixed_properties|, discard
1653                * the class.
1654                */
1655               if (!tp_strdiff
1656                     ((char *) h_key,
1657                      g_array_index (fixed_properties, char *, idx)))
1658                 {
1659                   found = TRUE;
1660                   /* exit the for() loop */
1661                   break;
1662                 }
1663             }
1664
1665           if (!found)
1666             return FALSE;
1667         }
1668     }
1669   else
1670     {
1671       /* if no fixed_properties are specified, discard the classes
1672        * with some fixed properties other than the two we already
1673        * checked.
1674        */
1675       if (g_hash_table_size (fprops) > 2)
1676         return FALSE;
1677     }
1678
1679   return TRUE;
1680 }
1681
1682 static GList *
1683 empathy_dispatcher_find_channel_classes (EmpathyDispatcher *self,
1684                                          TpConnection *connection,
1685                                          const gchar *channel_type,
1686                                          guint handle_type,
1687                                          GArray *fixed_properties)
1688 {
1689   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1690   GValueArray *class;
1691   GPtrArray *classes;
1692   GList *matching_classes;
1693   guint i;
1694   ConnectionData *cd;
1695
1696   g_return_val_if_fail (channel_type != NULL, NULL);
1697
1698   cd = g_hash_table_lookup (priv->connections, connection);
1699
1700   if (cd == NULL)
1701     return NULL;
1702
1703   classes = cd->requestable_channels;
1704   if (classes == NULL)
1705     return NULL;
1706
1707   matching_classes = NULL;
1708
1709   for (i = 0; i < classes->len; i++)
1710     {
1711       class = g_ptr_array_index (classes, i);
1712
1713       if (!channel_class_matches
1714           (class, channel_type, handle_type, fixed_properties))
1715         continue;
1716
1717       matching_classes = g_list_prepend (matching_classes, class);
1718     }
1719
1720   return matching_classes;
1721 }
1722
1723 static gboolean
1724 find_channel_class_idle_cb (gpointer user_data)
1725 {
1726   GList *retval;
1727   GList *requests;
1728   FindChannelRequest *request = user_data;
1729   ConnectionData *cd;
1730   gboolean is_ready = TRUE;
1731   EmpathyDispatcherPriv *priv = GET_PRIV (request->dispatcher);
1732
1733   g_hash_table_remove (priv->request_channel_class_async_ids, request);
1734
1735   cd = g_hash_table_lookup (priv->connections, request->connection);
1736
1737   if (cd == NULL)
1738     is_ready = FALSE;
1739   else if (cd->requestable_channels == NULL)
1740     is_ready = FALSE;
1741
1742   if (is_ready)
1743     {
1744       retval = empathy_dispatcher_find_channel_classes (request->dispatcher,
1745           request->connection, request->channel_type, request->handle_type,
1746           request->properties);
1747
1748       request->callback (retval, request->user_data);
1749       free_find_channel_request (request);
1750       g_list_free (retval);
1751
1752       return FALSE;
1753     }
1754
1755   requests = g_hash_table_lookup (priv->outstanding_classes_requests,
1756       request->connection);
1757   requests = g_list_prepend (requests, request);
1758
1759   g_hash_table_insert (priv->outstanding_classes_requests,
1760       request->connection, requests);
1761
1762   return FALSE;
1763 }
1764
1765 static GArray *
1766 setup_varargs (va_list var_args,
1767                const char *channel_namespace,
1768                const char *first_property_name)
1769 {
1770   const char *name;
1771   char *name_full;
1772   GArray *properties;
1773
1774   if (first_property_name == NULL)
1775     return NULL;
1776
1777   name = first_property_name;
1778   properties = g_array_new (TRUE, TRUE, sizeof (char *));
1779
1780   while (name != NULL)
1781     {
1782       name_full = g_strdup (name);
1783       properties = g_array_append_val (properties, name_full);
1784       name = va_arg (var_args, char *);
1785     }
1786
1787   return properties;
1788 }
1789
1790 /**
1791  * empathy_dispatcher_find_requestable_channel_classes:
1792  * @dispatcher: an #EmpathyDispatcher
1793  * @connection: a #TpConnection
1794  * @channel_type: a string identifying the type of the channel to lookup
1795  * @handle_type: the handle type for the channel, or %TP_UNKNOWN_HANDLE_TYPE
1796  *               if you don't care about the channel's target handle type
1797  * @first_property_name: %NULL, or the name of the first fixed property,
1798  * followed optionally by more names, followed by %NULL.
1799  *
1800  * Returns all the channel classes that a client can request for the connection
1801  * @connection, of the type identified by @channel_type, @handle_type and the
1802  * fixed properties list.
1803  * The classes which are compatible with a fixed properties list (i.e. those
1804  * that will be returned by this function) are intended as those that do not
1805  * contain any fixed property other than those in the list; note that this
1806  * doesn't guarantee that all the classes compatible with the list will contain
1807  * all the requested fixed properties, so the clients will have to filter
1808  * the returned list themselves.
1809  * If @first_property_name is %NULL, only the classes with no other fixed
1810  * properties than ChannelType and TargetHandleType will be returned.
1811  * Note that this function may return %NULL without performing any lookup if
1812  * @connection is not ready. To ensure that @connection is always ready,
1813  * use the empathy_dispatcher_find_requestable_channel_classes_async() variant.
1814  *
1815  * Return value: a #GList of #GValueArray objects, where the first element in
1816  * the array is a #GHashTable of the fixed properties, and the second is
1817  * a #GStrv of the allowed properties for the class. The list should be free'd
1818  * with g_list_free() when done, but the objects inside the list are owned
1819  * by the #EmpathyDispatcher and must not be modified.
1820  */
1821 GList *
1822 empathy_dispatcher_find_requestable_channel_classes
1823                                  (EmpathyDispatcher *self,
1824                                   TpConnection *connection,
1825                                   const gchar *channel_type,
1826                                   guint handle_type,
1827                                   const char *first_property_name,
1828                                   ...)
1829 {
1830   va_list var_args;
1831   GArray *properties;
1832   EmpathyDispatcherPriv *priv;
1833   GList *retval;
1834   guint idx;
1835   char *str;
1836
1837   g_return_val_if_fail (EMPATHY_IS_DISPATCHER (self), NULL);
1838   g_return_val_if_fail (TP_IS_CONNECTION (connection), NULL);
1839   g_return_val_if_fail (channel_type != NULL, NULL);
1840
1841   priv = GET_PRIV (self);
1842
1843   va_start (var_args, first_property_name);
1844
1845   properties = setup_varargs (var_args, channel_type, first_property_name);
1846
1847   va_end (var_args);
1848
1849   retval = empathy_dispatcher_find_channel_classes (self, connection,
1850     channel_type, handle_type, properties);
1851
1852   if (properties != NULL)
1853     {
1854       /* free the properties array */
1855       for (idx = 0; idx < properties->len ; idx++)
1856         {
1857           str = g_array_index (properties, char *, idx);
1858           g_free (str);
1859         }
1860
1861       g_array_free (properties, TRUE);
1862     }
1863
1864   return retval;
1865 }
1866
1867 /**
1868  * empathy_dispatcher_find_requestable_channel_classes_async:
1869  * @dispatcher: an #EmpathyDispatcher
1870  * @connection: a #TpConnection
1871  * @channel_type: a string identifying the type of the channel to lookup
1872  * @handle_type: the handle type for the channel
1873  * @callback: the callback to call when @connection is ready
1874  * @user_data: the user data to pass to @callback
1875  * @first_property_name: %NULL, or the name of the first fixed property,
1876  * followed optionally by more names, followed by %NULL.
1877  *
1878  * Please see the documentation of
1879  * empathy_dispatcher_find_requestable_channel_classes() for a detailed
1880  * description of this function.
1881  */
1882 void
1883 empathy_dispatcher_find_requestable_channel_classes_async
1884                                  (EmpathyDispatcher *self,
1885                                   TpConnection *connection,
1886                                   const gchar *channel_type,
1887                                   guint handle_type,
1888                                   EmpathyDispatcherFindChannelClassCb callback,
1889                                   gpointer user_data,
1890                                   const char *first_property_name,
1891                                   ...)
1892 {
1893   va_list var_args;
1894   GArray *properties;
1895   FindChannelRequest *request;
1896   EmpathyDispatcherPriv *priv;
1897   guint source_id;
1898
1899   g_return_if_fail (EMPATHY_IS_DISPATCHER (self));
1900   g_return_if_fail (TP_IS_CONNECTION (connection));
1901   g_return_if_fail (channel_type != NULL);
1902   g_return_if_fail (handle_type != 0);
1903
1904   priv = GET_PRIV (self);
1905
1906   va_start (var_args, first_property_name);
1907
1908   properties = setup_varargs (var_args, channel_type, first_property_name);
1909
1910   va_end (var_args);
1911
1912   /* append another request for this connection */
1913   request = g_slice_new0 (FindChannelRequest);
1914   request->dispatcher = g_object_ref (self);
1915   request->channel_type = g_strdup (channel_type);
1916   request->handle_type = handle_type;
1917   request->connection = connection;
1918   request->callback = callback;
1919   request->user_data = user_data;
1920   request->properties = properties;
1921
1922   source_id = g_idle_add (find_channel_class_idle_cb, request);
1923
1924   g_hash_table_insert (priv->request_channel_class_async_ids,
1925     request, GUINT_TO_POINTER (source_id));
1926 }
1927
1928 static GList *
1929 empathy_dispatcher_get_channels (EmpathyHandler *handler,
1930   gpointer user_data)
1931 {
1932   EmpathyDispatcher *self = EMPATHY_DISPATCHER (user_data);
1933   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1934
1935   return priv->channels;
1936 }
1937
1938 static gboolean
1939 empathy_dispatcher_handle_channels (EmpathyHandler *handler,
1940     const gchar *account_path,
1941     const gchar *connection_path,
1942     const GPtrArray *channels,
1943     const GPtrArray *requests_satisfied,
1944     guint64 timestamp,
1945     GHashTable *handler_info,
1946     gpointer user_data,
1947     GError **error)
1948 {
1949   EmpathyDispatcher *self = EMPATHY_DISPATCHER (user_data);
1950   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1951   guint i;
1952   TpAccount *account;
1953   TpConnection *connection;
1954
1955   /* FIXME: should probably find out whether the account manager is prepared
1956    * before ensuring. See bug #600111. */
1957   account = tp_account_manager_ensure_account (priv->account_manager,
1958     account_path);
1959   g_assert (account != NULL);
1960
1961   connection = tp_account_ensure_connection (account, connection_path);
1962   if (connection == NULL)
1963     {
1964       g_set_error_literal (error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
1965         "Invalid connection argument");
1966       return FALSE;
1967     }
1968
1969   for (i = 0; i < channels->len ; i++)
1970     {
1971       GValueArray *arr = g_ptr_array_index (channels, i);
1972       const gchar *object_path;
1973       GHashTable *properties;
1974
1975       object_path = g_value_get_boxed (g_value_array_get_nth (arr, 0));
1976       properties = g_value_get_boxed (g_value_array_get_nth (arr, 1));
1977
1978       dispatcher_connection_new_channel_with_properties (self,
1979         connection, object_path, properties, requests_satisfied, timestamp);
1980     }
1981
1982   return TRUE;
1983 }
1984
1985
1986 EmpathyHandler *
1987 empathy_dispatcher_add_handler (EmpathyDispatcher *self,
1988     const gchar *name,
1989     GPtrArray *filters,
1990     GStrv capabilities)
1991 {
1992   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1993   EmpathyHandler *handler;
1994
1995   handler = empathy_handler_new (name, filters, capabilities);
1996   priv->handlers = g_list_prepend (priv->handlers, handler);
1997
1998   /* Only set the handle_channels function, the Channel property on the main
1999    * handler will always report all dispatched channels even if they came from
2000    * a different Handler */
2001   empathy_handler_set_handle_channels_func (handler,
2002     empathy_dispatcher_handle_channels, self);
2003
2004   return handler;
2005 }
2006
2007 void
2008 empathy_dispatcher_remove_handler (EmpathyDispatcher *self,
2009   EmpathyHandler *handler)
2010 {
2011   EmpathyDispatcherPriv *priv = GET_PRIV (self);
2012   GList *h;
2013
2014   h = g_list_find (priv->handlers, handler);
2015   g_return_if_fail (h != NULL);
2016
2017   priv->handlers = g_list_delete_link (priv->handlers, h);
2018
2019   g_object_unref (handler);
2020 }