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