]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
contact-manager, dispatcher: renamed _new_connection_cb to _status_changed_cb
[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 dispatcher_init_connection_if_needed (EmpathyDispatcher *self,
841     TpConnection *connection)
842 {
843   EmpathyDispatcherPriv *priv = GET_PRIV (self);
844   GPtrArray   *capabilities;
845   GType        cap_type;
846   GValue       cap = {0, };
847   const gchar *remove_ = NULL;
848
849   if (g_hash_table_lookup (priv->connections, connection) != NULL)
850     return;
851
852   g_hash_table_insert (priv->connections, g_object_ref (connection),
853     new_connection_data ());
854
855   g_signal_connect (connection, "invalidated",
856     G_CALLBACK (dispatcher_connection_invalidated_cb), self);
857
858   if (tp_proxy_has_interface_by_id (TP_PROXY (connection),
859       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
860     {
861       tp_cli_dbus_properties_call_get_all (connection, -1,
862         TP_IFACE_CONNECTION_INTERFACE_REQUESTS,
863         dispatcher_connection_got_all,
864         NULL, NULL, G_OBJECT (self));
865     }
866
867   /* Advertise VoIP capabilities */
868   capabilities = g_ptr_array_sized_new (1);
869   cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
870     G_TYPE_UINT, G_TYPE_INVALID);
871   g_value_init (&cap, cap_type);
872   g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
873   dbus_g_type_struct_set (&cap,
874         0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
875         1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
876            TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
877            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
878            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P |
879            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_ICE_UDP,
880            G_MAXUINT);
881   g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
882
883   tp_cli_connection_interface_capabilities_call_advertise_capabilities (
884     connection, -1, capabilities, &remove_,
885     dispatcher_connection_advertise_capabilities_cb,
886     NULL, NULL, G_OBJECT (self));
887
888   g_value_unset (&cap);
889   g_ptr_array_free (capabilities, TRUE);
890 }
891
892 static void
893 dispatcher_status_changed_cb (TpAccount *account,
894                               guint old_status,
895                               guint new_status,
896                               guint reason,
897                               gchar *dbus_error_name,
898                               GHashTable *details,
899                               EmpathyDispatcher *self)
900 {
901   TpConnection *conn = tp_account_get_connection (account);
902
903   if (conn != NULL)
904     dispatcher_init_connection_if_needed (self, conn);
905 }
906
907 static void
908 remove_idle_handlers (gpointer key,
909                       gpointer value,
910                       gpointer user_data)
911 {
912   guint source_id;
913
914   source_id = GPOINTER_TO_UINT (value);
915   g_source_remove (source_id);
916 }
917
918 static GObject *
919 dispatcher_constructor (GType type,
920                         guint n_construct_params,
921                         GObjectConstructParam *construct_params)
922 {
923   GObject *retval;
924   EmpathyDispatcherPriv *priv;
925
926   if (dispatcher != NULL)
927     return g_object_ref (dispatcher);
928
929   retval = G_OBJECT_CLASS (empathy_dispatcher_parent_class)->constructor
930     (type, n_construct_params, construct_params);
931
932   dispatcher = EMPATHY_DISPATCHER (retval);
933   g_object_add_weak_pointer (retval, (gpointer) &dispatcher);
934
935   priv = GET_PRIV (dispatcher);
936
937   if (priv->handler == NULL)
938     priv->handler = empathy_handler_new (NULL, NULL, NULL);
939
940   empathy_handler_set_handle_channels_func (priv->handler,
941     empathy_dispatcher_handle_channels,
942     dispatcher);
943
944   empathy_handler_set_channels_func (priv->handler,
945     empathy_dispatcher_get_channels,
946     dispatcher);
947
948   return retval;
949 }
950
951 static void
952 dispatcher_dispose (GObject *object)
953 {
954   EmpathyDispatcherPriv *priv = GET_PRIV (object);
955   GHashTableIter iter;
956   gpointer connection;
957   GList *l;
958
959   if (priv->dispose_has_run)
960     return;
961
962   priv->dispose_has_run = TRUE;
963
964   for (l = priv->handlers ; l != NULL; l = g_list_next (l))
965     g_object_unref (G_OBJECT (l->data));
966
967   g_list_free (priv->handlers);
968   priv->handlers = NULL;
969
970   if (priv->handler != NULL)
971     g_object_unref (priv->handler);
972   priv->handler = NULL;
973
974   g_hash_table_iter_init (&iter, priv->connections);
975   while (g_hash_table_iter_next (&iter, &connection, NULL))
976     {
977       g_signal_handlers_disconnect_by_func (connection,
978           dispatcher_connection_invalidated_cb, object);
979     }
980
981   g_hash_table_destroy (priv->connections);
982   priv->connections = NULL;
983
984   G_OBJECT_CLASS (empathy_dispatcher_parent_class)->dispose (object);
985 }
986
987 static void
988 dispatcher_finalize (GObject *object)
989 {
990   EmpathyDispatcherPriv *priv = GET_PRIV (object);
991   GList *l;
992   GHashTableIter iter;
993   gpointer connection;
994   GList *list;
995
996   if (priv->request_channel_class_async_ids != NULL)
997     {
998       g_hash_table_foreach (priv->request_channel_class_async_ids,
999         remove_idle_handlers, NULL);
1000       g_hash_table_destroy (priv->request_channel_class_async_ids);
1001     }
1002
1003   for (l = priv->channels; l; l = l->next)
1004     {
1005       g_signal_handlers_disconnect_by_func (l->data,
1006           dispatcher_channel_invalidated_cb, object);
1007     }
1008
1009   g_list_free (priv->channels);
1010
1011   g_hash_table_iter_init (&iter, priv->outstanding_classes_requests);
1012   while (g_hash_table_iter_next (&iter, &connection, (gpointer *) &list))
1013     {
1014       g_list_foreach (list, (GFunc) free_find_channel_request, NULL);
1015       g_list_free (list);
1016     }
1017
1018   g_object_unref (priv->account_manager);
1019
1020   g_hash_table_destroy (priv->outstanding_classes_requests);
1021 }
1022
1023 static void
1024 dispatcher_set_property (GObject *object,
1025   guint property_id,
1026   const GValue *value,
1027   GParamSpec *pspec)
1028 {
1029   EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
1030   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1031
1032   switch (property_id)
1033     {
1034       case PROP_HANDLER:
1035         priv->handler = g_value_dup_object (value);
1036         break;
1037       default:
1038         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1039         break;
1040     }
1041 }
1042
1043 static void
1044 dispatcher_get_property (GObject *object,
1045   guint property_id,
1046   GValue *value,
1047   GParamSpec *pspec)
1048 {
1049   EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
1050   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1051
1052   switch (property_id)
1053     {
1054       case PROP_HANDLER:
1055         g_value_set_object (value, priv->handler);
1056         break;
1057       default:
1058         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1059         break;
1060     }
1061 }
1062
1063 static void
1064 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
1065 {
1066   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1067   GParamSpec *param_spec;
1068
1069   object_class->dispose = dispatcher_dispose;
1070   object_class->finalize = dispatcher_finalize;
1071   object_class->constructor = dispatcher_constructor;
1072
1073   object_class->get_property = dispatcher_get_property;
1074   object_class->set_property = dispatcher_set_property;
1075
1076   param_spec = g_param_spec_object ("handler", "handler",
1077     "The main Telepathy Client Hander object",
1078     EMPATHY_TYPE_HANDLER,
1079     G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS | G_PARAM_CONSTRUCT_ONLY);
1080   g_object_class_install_property (object_class,
1081     PROP_HANDLER, param_spec);
1082
1083   signals[OBSERVE] =
1084     g_signal_new ("observe",
1085       G_TYPE_FROM_CLASS (klass),
1086       G_SIGNAL_RUN_LAST,
1087       0,
1088       NULL, NULL,
1089       g_cclosure_marshal_VOID__OBJECT,
1090       G_TYPE_NONE,
1091       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1092
1093   signals[APPROVE] =
1094     g_signal_new ("approve",
1095       G_TYPE_FROM_CLASS (klass),
1096       G_SIGNAL_RUN_LAST,
1097       0,
1098       NULL, NULL,
1099       g_cclosure_marshal_VOID__OBJECT,
1100       G_TYPE_NONE,
1101       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1102
1103   signals[DISPATCH] =
1104     g_signal_new ("dispatch",
1105       G_TYPE_FROM_CLASS (klass),
1106       G_SIGNAL_RUN_LAST,
1107       0,
1108       NULL, NULL,
1109       g_cclosure_marshal_VOID__OBJECT,
1110       G_TYPE_NONE,
1111       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1112
1113
1114   g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
1115 }
1116
1117 static void
1118 account_manager_prepared_cb (GObject *source_object,
1119                              GAsyncResult *result,
1120                              gpointer user_data)
1121 {
1122   GList *accounts, *l;
1123   EmpathyDispatcher *self = user_data;
1124   TpAccountManager *account_manager = TP_ACCOUNT_MANAGER (source_object);
1125
1126   if (!tp_account_manager_prepare_finish (account_manager, result, NULL))
1127     return;
1128
1129   accounts = tp_account_manager_get_valid_accounts (account_manager);
1130   for (l = accounts; l; l = l->next)
1131     {
1132       TpAccount *a = l->data;
1133       TpConnection *conn = tp_account_get_connection (a);
1134
1135       if (conn != NULL)
1136         dispatcher_status_changed_cb (a, 0, 0, 0, NULL, NULL, self);
1137
1138       empathy_signal_connect_weak (a, "status-changed",
1139           G_CALLBACK (dispatcher_status_changed_cb),
1140           G_OBJECT (self));
1141     }
1142   g_list_free (accounts);
1143 }
1144
1145 static void
1146 empathy_dispatcher_init (EmpathyDispatcher *self)
1147 {
1148   EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
1149     EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
1150
1151   self->priv = priv;
1152   priv->account_manager = tp_account_manager_dup ();
1153
1154   priv->connections = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1155     g_object_unref, (GDestroyNotify) free_connection_data);
1156
1157   priv->outstanding_classes_requests = g_hash_table_new_full (g_direct_hash,
1158     g_direct_equal, g_object_unref, NULL);
1159
1160   priv->channels = NULL;
1161
1162   tp_account_manager_prepare_async (priv->account_manager, NULL,
1163       account_manager_prepared_cb, self);
1164
1165   priv->request_channel_class_async_ids = g_hash_table_new (g_direct_hash,
1166     g_direct_equal);
1167 }
1168
1169 EmpathyDispatcher *
1170 empathy_dispatcher_new (const gchar *name,
1171   GPtrArray *filters,
1172   GStrv capabilities)
1173 {
1174   EmpathyHandler *handler;
1175   EmpathyDispatcher *ret;
1176
1177   g_assert (dispatcher == NULL);
1178   handler = empathy_handler_new (name, filters, capabilities);
1179
1180   ret = EMPATHY_DISPATCHER (
1181     g_object_new (EMPATHY_TYPE_DISPATCHER,
1182       "handler", handler,
1183       NULL));
1184   g_object_unref (handler);
1185
1186   return ret;
1187 }
1188
1189 EmpathyDispatcher *
1190 empathy_dispatcher_dup_singleton (void)
1191 {
1192   return EMPATHY_DISPATCHER (g_object_new (EMPATHY_TYPE_DISPATCHER, NULL));
1193 }
1194
1195 static void
1196 dispatcher_request_failed (EmpathyDispatcher *self,
1197                            DispatcherRequestData *request_data,
1198                            const GError *error)
1199 {
1200   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1201   ConnectionData *conn_data;
1202
1203   conn_data = g_hash_table_lookup (priv->connections,
1204       request_data->connection);
1205   if (request_data->cb != NULL)
1206     request_data->cb (NULL, error, request_data->user_data);
1207
1208   if (conn_data != NULL)
1209     {
1210       conn_data->outstanding_requests =
1211           g_list_remove (conn_data->outstanding_requests, request_data);
1212     }
1213   /* else Connection has been invalidated */
1214
1215   free_dispatcher_request_data (request_data);
1216 }
1217
1218 static void
1219 dispatcher_connection_new_requested_channel (EmpathyDispatcher *self,
1220   DispatcherRequestData *request_data,
1221   const gchar *object_path,
1222   GHashTable *properties,
1223   const GError *error)
1224 {
1225   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1226   EmpathyDispatchOperation *operation = NULL;
1227   ConnectionData *conn_data;
1228
1229   conn_data = g_hash_table_lookup (priv->connections,
1230     request_data->connection);
1231
1232   if (error)
1233     {
1234       DEBUG ("Channel request failed: %s", error->message);
1235
1236       dispatcher_request_failed (self, request_data, error);
1237
1238       goto out;
1239     }
1240
1241   operation = g_hash_table_lookup (conn_data->outstanding_channels,
1242     object_path);
1243
1244   if (operation != NULL)
1245     g_hash_table_remove (conn_data->outstanding_channels, object_path);
1246   else
1247     operation = g_hash_table_lookup (conn_data->dispatching_channels,
1248         object_path);
1249
1250   if (operation == NULL)
1251     {
1252       DispatchData *data = g_hash_table_lookup (conn_data->dispatched_channels,
1253         object_path);
1254
1255       if (data != NULL)
1256         {
1257           operation = empathy_dispatch_operation_new_with_wrapper (
1258             request_data->connection,
1259             data->channel, request_data->contact, FALSE,
1260             data->channel_wrapper);
1261         }
1262       else
1263         {
1264           TpChannel *channel;
1265
1266           if (properties != NULL)
1267             channel = tp_channel_new_from_properties (request_data->connection,
1268               object_path, properties, NULL);
1269           else
1270             channel = tp_channel_new (request_data->connection, object_path,
1271               request_data->channel_type, request_data->handle_type,
1272               request_data->handle, NULL);
1273
1274           g_signal_connect (channel, "invalidated",
1275             G_CALLBACK (dispatcher_channel_invalidated_cb),
1276             request_data->dispatcher);
1277
1278           priv->channels = g_list_prepend (priv->channels, channel);
1279
1280           operation = empathy_dispatch_operation_new (request_data->connection,
1281              channel, request_data->contact, FALSE);
1282           g_object_unref (channel);
1283         }
1284     }
1285   else
1286     {
1287       /* Already existed set potential extra information */
1288       g_object_set (G_OBJECT (operation),
1289         "contact", request_data->contact,
1290         NULL);
1291     }
1292
1293   request_data->operation = operation;
1294
1295   /* (pre)-approve this right away as we requested it
1296    * This might cause the channel to be claimed, in which case the operation
1297    * will disappear. So ref it, and check the status before starting the
1298    * dispatching */
1299
1300   g_object_ref (operation);
1301   empathy_dispatch_operation_approve (operation);
1302
1303    if (empathy_dispatch_operation_get_status (operation) <
1304      EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
1305       dispatcher_start_dispatching (request_data->dispatcher, operation,
1306           conn_data);
1307
1308   g_object_unref (operation);
1309
1310 out:
1311   dispatcher_flush_outstanding_operations (request_data->dispatcher,
1312     conn_data);
1313 }
1314
1315 static void
1316 dispatcher_request_channel_cb (TpConnection *connection,
1317                                const gchar  *object_path,
1318                                const GError *error,
1319                                gpointer user_data,
1320                                GObject *weak_object)
1321 {
1322   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1323   EmpathyDispatcher *self =
1324       EMPATHY_DISPATCHER (request_data->dispatcher);
1325
1326   request_data->pending_call = NULL;
1327
1328   dispatcher_connection_new_requested_channel (self,
1329     request_data, object_path, NULL, error);
1330 }
1331
1332 static void
1333 dispatcher_request_channel (DispatcherRequestData *request_data)
1334 {
1335   if (tp_proxy_has_interface_by_id (TP_PROXY (request_data->connection),
1336       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
1337     {
1338       /* Extend the request_data to be a valid request */
1339       g_assert (request_data->request == NULL);
1340       request_data->request = tp_asv_new (
1341         TP_IFACE_CHANNEL ".ChannelType",
1342           G_TYPE_STRING, request_data->channel_type,
1343         TP_IFACE_CHANNEL ".TargetHandleType",
1344           G_TYPE_UINT, request_data->handle_type,
1345         NULL);
1346
1347       if (request_data->handle_type != TP_HANDLE_TYPE_NONE)
1348         tp_asv_set_uint32 (request_data->request,
1349           TP_IFACE_CHANNEL ".TargetHandle", request_data->handle);
1350
1351       empathy_dispatcher_call_create_or_ensure_channel (
1352         request_data->dispatcher, request_data);
1353     }
1354   else
1355     {
1356       request_data->pending_call = tp_cli_connection_call_request_channel (
1357         request_data->connection, -1,
1358         request_data->channel_type,
1359         request_data->handle_type,
1360         request_data->handle,
1361         TRUE, dispatcher_request_channel_cb,
1362         request_data, NULL, NULL);
1363     }
1364 }
1365
1366 void
1367 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1368                                       EmpathyDispatcherRequestCb *callback,
1369                                       gpointer user_data)
1370 {
1371   EmpathyDispatcher *self;
1372   EmpathyDispatcherPriv *priv;
1373   TpConnection *connection;
1374   ConnectionData *connection_data;
1375   DispatcherRequestData *request_data;
1376
1377   g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1378
1379   self = empathy_dispatcher_dup_singleton ();
1380   priv = GET_PRIV (self);
1381
1382   connection = empathy_contact_get_connection (contact);
1383   connection_data = g_hash_table_lookup (priv->connections, connection);
1384
1385   /* The contact handle might not be known yet */
1386   request_data = new_dispatcher_request_data (self, connection,
1387     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT,
1388     empathy_contact_get_handle (contact), NULL, contact, callback, user_data);
1389   request_data->should_ensure = TRUE;
1390
1391   connection_data->outstanding_requests = g_list_prepend
1392     (connection_data->outstanding_requests, request_data);
1393
1394   dispatcher_request_channel (request_data);
1395
1396   g_object_unref (self);
1397 }
1398
1399 typedef struct
1400 {
1401   EmpathyDispatcher *dispatcher;
1402   EmpathyDispatcherRequestCb *callback;
1403   gpointer user_data;
1404 } ChatWithContactIdData;
1405
1406 static void
1407 dispatcher_chat_with_contact_id_cb (EmpathyTpContactFactory *factory,
1408                                     EmpathyContact          *contact,
1409                                     const GError            *error,
1410                                     gpointer                 user_data,
1411                                     GObject                 *weak_object)
1412 {
1413   ChatWithContactIdData *data = user_data;
1414
1415   if (error)
1416     {
1417       /* FIXME: Should call data->callback with the error */
1418       DEBUG ("Error: %s", error->message);
1419     }
1420   else
1421     {
1422       empathy_dispatcher_chat_with_contact (contact, data->callback,
1423           data->user_data);
1424     }
1425
1426   g_object_unref (data->dispatcher);
1427   g_slice_free (ChatWithContactIdData, data);
1428 }
1429
1430 void
1431 empathy_dispatcher_chat_with_contact_id (TpConnection *connection,
1432                                          const gchar *contact_id,
1433                                          EmpathyDispatcherRequestCb *callback,
1434                                          gpointer user_data)
1435 {
1436   EmpathyDispatcher *self;
1437   EmpathyTpContactFactory *factory;
1438   ChatWithContactIdData *data;
1439
1440   g_return_if_fail (TP_IS_CONNECTION (connection));
1441   g_return_if_fail (!EMP_STR_EMPTY (contact_id));
1442
1443   self = empathy_dispatcher_dup_singleton ();
1444   factory = empathy_tp_contact_factory_dup_singleton (connection);
1445   data = g_slice_new0 (ChatWithContactIdData);
1446   data->dispatcher = self;
1447   data->callback = callback;
1448   data->user_data = user_data;
1449   empathy_tp_contact_factory_get_from_id (factory, contact_id,
1450       dispatcher_chat_with_contact_id_cb, data, NULL, NULL);
1451
1452   g_object_unref (factory);
1453 }
1454
1455 static void
1456 dispatcher_request_handles_cb (TpConnection *connection,
1457                                const GArray *handles,
1458                                const GError *error,
1459                                gpointer user_data,
1460                                GObject *object)
1461 {
1462   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1463
1464   request_data->pending_call = NULL;
1465
1466   if (error != NULL)
1467     {
1468       EmpathyDispatcher *self = EMPATHY_DISPATCHER (object);
1469       EmpathyDispatcherPriv *priv = GET_PRIV (self);
1470       ConnectionData *cd;
1471
1472       cd = g_hash_table_lookup (priv->connections, request_data->connection);
1473
1474       if (request_data->cb)
1475         request_data->cb (NULL, error, request_data->user_data);
1476
1477       cd->outstanding_requests = g_list_remove (cd->outstanding_requests,
1478         request_data);
1479
1480       free_dispatcher_request_data (request_data);
1481
1482       dispatcher_flush_outstanding_operations (self, cd);
1483       return;
1484     }
1485
1486   request_data->handle = g_array_index (handles, guint, 0);
1487   dispatcher_request_channel (request_data);
1488 }
1489
1490 void
1491 empathy_dispatcher_join_muc (TpConnection *connection,
1492                              const gchar *roomname,
1493                              EmpathyDispatcherRequestCb *callback,
1494                              gpointer user_data)
1495 {
1496   EmpathyDispatcher *self;
1497   EmpathyDispatcherPriv *priv;
1498   DispatcherRequestData *request_data;
1499   ConnectionData *connection_data;
1500   const gchar *names[] = { roomname, NULL };
1501
1502   g_return_if_fail (TP_IS_CONNECTION (connection));
1503   g_return_if_fail (!EMP_STR_EMPTY (roomname));
1504
1505   self = empathy_dispatcher_dup_singleton ();
1506   priv = GET_PRIV (self);
1507
1508   connection_data = g_hash_table_lookup (priv->connections, connection);
1509
1510   /* Don't know the room handle yet */
1511   request_data  = new_dispatcher_request_data (self, connection,
1512     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_ROOM, 0, NULL,
1513     NULL, callback, user_data);
1514
1515   connection_data->outstanding_requests = g_list_prepend
1516     (connection_data->outstanding_requests, request_data);
1517
1518   request_data->pending_call = tp_cli_connection_call_request_handles (
1519     connection, -1,
1520     TP_HANDLE_TYPE_ROOM, names,
1521     dispatcher_request_handles_cb, request_data, NULL, NULL);
1522
1523   g_object_unref (self);
1524 }
1525
1526 static void
1527 dispatcher_create_channel_cb (TpConnection *connect,
1528                               const gchar *object_path,
1529                               GHashTable *properties,
1530                               const GError *error,
1531                               gpointer user_data,
1532                               GObject *weak_object)
1533 {
1534   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1535   EmpathyDispatcher *self =
1536       EMPATHY_DISPATCHER (request_data->dispatcher);
1537
1538   request_data->pending_call = NULL;
1539
1540   dispatcher_connection_new_requested_channel (self,
1541     request_data, object_path, properties, error);
1542 }
1543
1544 static void
1545 dispatcher_ensure_channel_cb (TpConnection *connect,
1546                               gboolean is_ours,
1547                               const gchar *object_path,
1548                               GHashTable *properties,
1549                               const GError *error,
1550                               gpointer user_data,
1551                               GObject *weak_object)
1552 {
1553   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1554   EmpathyDispatcher *self =
1555       EMPATHY_DISPATCHER (request_data->dispatcher);
1556
1557   request_data->pending_call = NULL;
1558
1559   dispatcher_connection_new_requested_channel (self,
1560     request_data, object_path, properties, error);
1561 }
1562
1563 static void
1564 empathy_dispatcher_call_create_or_ensure_channel (
1565     EmpathyDispatcher *self,
1566     DispatcherRequestData *request_data)
1567 {
1568   if (request_data->should_ensure)
1569     {
1570       request_data->pending_call =
1571           tp_cli_connection_interface_requests_call_ensure_channel (
1572           request_data->connection, -1,
1573           request_data->request, dispatcher_ensure_channel_cb,
1574           request_data, NULL, NULL);
1575     }
1576   else
1577     {
1578       request_data->pending_call =
1579           tp_cli_connection_interface_requests_call_create_channel (
1580           request_data->connection, -1,
1581           request_data->request, dispatcher_create_channel_cb,
1582           request_data, NULL, NULL);
1583     }
1584 }
1585
1586 void
1587 empathy_dispatcher_create_channel (EmpathyDispatcher *self,
1588                                    TpConnection *connection,
1589                                    GHashTable *request,
1590                                    EmpathyDispatcherRequestCb *callback,
1591                                    gpointer user_data)
1592 {
1593   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1594   ConnectionData *connection_data;
1595   DispatcherRequestData *request_data;
1596   const gchar *channel_type;
1597   guint handle_type;
1598   guint handle;
1599   gboolean valid;
1600
1601   g_return_if_fail (EMPATHY_IS_DISPATCHER (self));
1602   g_return_if_fail (TP_IS_CONNECTION (connection));
1603   g_return_if_fail (request != NULL);
1604
1605   connection_data = g_hash_table_lookup (priv->connections, connection);
1606   g_assert (connection_data != NULL);
1607
1608   channel_type = tp_asv_get_string (request, TP_IFACE_CHANNEL ".ChannelType");
1609
1610   handle_type = tp_asv_get_uint32 (request,
1611     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1612   if (!valid)
1613     handle_type = TP_UNKNOWN_HANDLE_TYPE;
1614
1615   handle = tp_asv_get_uint32 (request, TP_IFACE_CHANNEL ".TargetHandle", NULL);
1616
1617   request_data  = new_dispatcher_request_data (self, connection,
1618     channel_type, handle_type, handle, request,
1619     NULL, callback, user_data);
1620
1621   connection_data->outstanding_requests = g_list_prepend
1622     (connection_data->outstanding_requests, request_data);
1623
1624   empathy_dispatcher_call_create_or_ensure_channel (self, request_data);
1625 }
1626
1627 static gboolean
1628 channel_class_matches (GValueArray *class,
1629                        const char *channel_type,
1630                        guint handle_type,
1631                        GArray *fixed_properties)
1632 {
1633   GHashTable *fprops;
1634   GValue *v;
1635   const char *c_type;
1636   guint h_type;
1637   gboolean valid;
1638
1639   v = g_value_array_get_nth (class, 0);
1640
1641   /* if the class doesn't match channel type discard it. */
1642   fprops = g_value_get_boxed (v);
1643   c_type = tp_asv_get_string (fprops, TP_IFACE_CHANNEL ".ChannelType");
1644
1645   if (tp_strdiff (channel_type, c_type))
1646     return FALSE;
1647
1648   /* we have the right channel type, see if the handle type matches */
1649   h_type = tp_asv_get_uint32 (fprops,
1650                               TP_IFACE_CHANNEL ".TargetHandleType", &valid);
1651
1652   if (!valid || handle_type != h_type)
1653     return FALSE;
1654
1655   if (fixed_properties != NULL)
1656     {
1657       gpointer h_key, h_val;
1658       guint idx;
1659       GHashTableIter iter;
1660       gboolean found;
1661
1662       g_hash_table_iter_init (&iter, fprops);
1663
1664       while (g_hash_table_iter_next (&iter, &h_key, &h_val))
1665         {
1666           /* discard ChannelType and TargetHandleType, as we already
1667            * checked them.
1668            */
1669           if (!tp_strdiff ((char *) h_key, TP_IFACE_CHANNEL ".ChannelType") ||
1670               !tp_strdiff
1671                 ((char *) h_key, TP_IFACE_CHANNEL ".TargetHandleType"))
1672             continue;
1673
1674           found = FALSE;
1675
1676           for (idx = 0; idx < fixed_properties->len; idx++)
1677             {
1678               /* if |key| doesn't exist in |fixed_properties|, discard
1679                * the class.
1680                */
1681               if (!tp_strdiff
1682                     ((char *) h_key,
1683                      g_array_index (fixed_properties, char *, idx)))
1684                 {
1685                   found = TRUE;
1686                   /* exit the for() loop */
1687                   break;
1688                 }
1689             }
1690
1691           if (!found)
1692             return FALSE;
1693         }
1694     }
1695   else
1696     {
1697       /* if no fixed_properties are specified, discard the classes
1698        * with some fixed properties other than the two we already
1699        * checked.
1700        */
1701       if (g_hash_table_size (fprops) > 2)
1702         return FALSE;
1703     }
1704
1705   return TRUE;
1706 }
1707
1708 static GList *
1709 empathy_dispatcher_find_channel_classes (EmpathyDispatcher *self,
1710                                          TpConnection *connection,
1711                                          const gchar *channel_type,
1712                                          guint handle_type,
1713                                          GArray *fixed_properties)
1714 {
1715   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1716   GValueArray *class;
1717   GPtrArray *classes;
1718   GList *matching_classes;
1719   guint i;
1720   ConnectionData *cd;
1721
1722   g_return_val_if_fail (channel_type != NULL, NULL);
1723   g_return_val_if_fail (handle_type != 0, NULL);
1724
1725   cd = g_hash_table_lookup (priv->connections, connection);
1726
1727   if (cd == NULL)
1728     return NULL;
1729
1730   classes = cd->requestable_channels;
1731   if (classes == NULL)
1732     return NULL;
1733
1734   matching_classes = NULL;
1735
1736   for (i = 0; i < classes->len; i++)
1737     {
1738       class = g_ptr_array_index (classes, i);
1739
1740       if (!channel_class_matches
1741           (class, channel_type, handle_type, fixed_properties))
1742         continue;
1743
1744       matching_classes = g_list_prepend (matching_classes, class);
1745     }
1746
1747   return matching_classes;
1748 }
1749
1750 static gboolean
1751 find_channel_class_idle_cb (gpointer user_data)
1752 {
1753   GList *retval;
1754   GList *requests;
1755   FindChannelRequest *request = user_data;
1756   ConnectionData *cd;
1757   gboolean is_ready = TRUE;
1758   EmpathyDispatcherPriv *priv = GET_PRIV (request->dispatcher);
1759
1760   g_hash_table_remove (priv->request_channel_class_async_ids, request);
1761
1762   cd = g_hash_table_lookup (priv->connections, request->connection);
1763
1764   if (cd == NULL)
1765     is_ready = FALSE;
1766   else if (cd->requestable_channels == NULL)
1767     is_ready = FALSE;
1768
1769   if (is_ready)
1770     {
1771       retval = empathy_dispatcher_find_channel_classes (request->dispatcher,
1772           request->connection, request->channel_type, request->handle_type,
1773           request->properties);
1774
1775       request->callback (retval, request->user_data);
1776       free_find_channel_request (request);
1777       g_list_free (retval);
1778
1779       return FALSE;
1780     }
1781
1782   requests = g_hash_table_lookup (priv->outstanding_classes_requests,
1783       request->connection);
1784   requests = g_list_prepend (requests, request);
1785
1786   g_hash_table_insert (priv->outstanding_classes_requests,
1787       request->connection, requests);
1788
1789   return FALSE;
1790 }
1791
1792 static GArray *
1793 setup_varargs (va_list var_args,
1794                const char *channel_namespace,
1795                const char *first_property_name)
1796 {
1797   const char *name;
1798   char *name_full;
1799   GArray *properties;
1800
1801   if (first_property_name == NULL)
1802     return NULL;
1803
1804   name = first_property_name;
1805   properties = g_array_new (TRUE, TRUE, sizeof (char *));
1806
1807   while (name != NULL)
1808     {
1809       name_full = g_strdup (name);
1810       properties = g_array_append_val (properties, name_full);
1811       name = va_arg (var_args, char *);
1812     }
1813
1814   return properties;
1815 }
1816
1817 /**
1818  * empathy_dispatcher_find_requestable_channel_classes:
1819  * @dispatcher: an #EmpathyDispatcher
1820  * @connection: a #TpConnection
1821  * @channel_type: a string identifying the type of the channel to lookup
1822  * @handle_type: the handle type for the channel
1823  * @first_property_name: %NULL, or the name of the first fixed property,
1824  * followed optionally by more names, followed by %NULL.
1825  *
1826  * Returns all the channel classes that a client can request for the connection
1827  * @connection, of the type identified by @channel_type, @handle_type and the
1828  * fixed properties list.
1829  * The classes which are compatible with a fixed properties list (i.e. those
1830  * that will be returned by this function) are intended as those that do not
1831  * contain any fixed property other than those in the list; note that this
1832  * doesn't guarantee that all the classes compatible with the list will contain
1833  * all the requested fixed properties, so the clients will have to filter
1834  * the returned list themselves.
1835  * If @first_property_name is %NULL, only the classes with no other fixed
1836  * properties than ChannelType and TargetHandleType will be returned.
1837  * Note that this function may return %NULL without performing any lookup if
1838  * @connection is not ready. To ensure that @connection is always ready,
1839  * use the empathy_dispatcher_find_requestable_channel_classes_async() variant.
1840  *
1841  * Return value: a #GList of #GValueArray objects, where the first element in
1842  * the array is a #GHashTable of the fixed properties, and the second is
1843  * a #GStrv of the allowed properties for the class. The list should be free'd
1844  * with g_list_free() when done, but the objects inside the list are owned
1845  * by the #EmpathyDispatcher and must not be modified.
1846  */
1847 GList *
1848 empathy_dispatcher_find_requestable_channel_classes
1849                                  (EmpathyDispatcher *self,
1850                                   TpConnection *connection,
1851                                   const gchar *channel_type,
1852                                   guint handle_type,
1853                                   const char *first_property_name,
1854                                   ...)
1855 {
1856   va_list var_args;
1857   GArray *properties;
1858   EmpathyDispatcherPriv *priv;
1859   GList *retval;
1860   guint idx;
1861   char *str;
1862
1863   g_return_val_if_fail (EMPATHY_IS_DISPATCHER (self), NULL);
1864   g_return_val_if_fail (TP_IS_CONNECTION (connection), NULL);
1865   g_return_val_if_fail (channel_type != NULL, NULL);
1866   g_return_val_if_fail (handle_type != 0, NULL);
1867
1868   priv = GET_PRIV (self);
1869
1870   va_start (var_args, first_property_name);
1871
1872   properties = setup_varargs (var_args, channel_type, first_property_name);
1873
1874   va_end (var_args);
1875
1876   retval = empathy_dispatcher_find_channel_classes (self, connection,
1877     channel_type, handle_type, properties);
1878
1879   if (properties != NULL)
1880     {
1881       /* free the properties array */
1882       for (idx = 0; idx < properties->len ; idx++)
1883         {
1884           str = g_array_index (properties, char *, idx);
1885           g_free (str);
1886         }
1887
1888       g_array_free (properties, TRUE);
1889     }
1890
1891   return retval;
1892 }
1893
1894 /**
1895  * empathy_dispatcher_find_requestable_channel_classes_async:
1896  * @dispatcher: an #EmpathyDispatcher
1897  * @connection: a #TpConnection
1898  * @channel_type: a string identifying the type of the channel to lookup
1899  * @handle_type: the handle type for the channel
1900  * @callback: the callback to call when @connection is ready
1901  * @user_data: the user data to pass to @callback
1902  * @first_property_name: %NULL, or the name of the first fixed property,
1903  * followed optionally by more names, followed by %NULL.
1904  *
1905  * Please see the documentation of
1906  * empathy_dispatcher_find_requestable_channel_classes() for a detailed
1907  * description of this function.
1908  */
1909 void
1910 empathy_dispatcher_find_requestable_channel_classes_async
1911                                  (EmpathyDispatcher *self,
1912                                   TpConnection *connection,
1913                                   const gchar *channel_type,
1914                                   guint handle_type,
1915                                   EmpathyDispatcherFindChannelClassCb callback,
1916                                   gpointer user_data,
1917                                   const char *first_property_name,
1918                                   ...)
1919 {
1920   va_list var_args;
1921   GArray *properties;
1922   FindChannelRequest *request;
1923   EmpathyDispatcherPriv *priv;
1924   guint source_id;
1925
1926   g_return_if_fail (EMPATHY_IS_DISPATCHER (self));
1927   g_return_if_fail (TP_IS_CONNECTION (connection));
1928   g_return_if_fail (channel_type != NULL);
1929   g_return_if_fail (handle_type != 0);
1930
1931   priv = GET_PRIV (self);
1932
1933   va_start (var_args, first_property_name);
1934
1935   properties = setup_varargs (var_args, channel_type, first_property_name);
1936
1937   va_end (var_args);
1938
1939   /* append another request for this connection */
1940   request = g_slice_new0 (FindChannelRequest);
1941   request->dispatcher = g_object_ref (self);
1942   request->channel_type = g_strdup (channel_type);
1943   request->handle_type = handle_type;
1944   request->connection = connection;
1945   request->callback = callback;
1946   request->user_data = user_data;
1947   request->properties = properties;
1948
1949   source_id = g_idle_add (find_channel_class_idle_cb, request);
1950
1951   g_hash_table_insert (priv->request_channel_class_async_ids,
1952     request, GUINT_TO_POINTER (source_id));
1953 }
1954
1955 static GList *
1956 empathy_dispatcher_get_channels (EmpathyHandler *handler,
1957   gpointer user_data)
1958 {
1959   EmpathyDispatcher *self = EMPATHY_DISPATCHER (user_data);
1960   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1961
1962   return priv->channels;
1963 }
1964
1965 static gboolean
1966 empathy_dispatcher_handle_channels (EmpathyHandler *handler,
1967     const gchar *account_path,
1968     const gchar *connection_path,
1969     const GPtrArray *channels,
1970     const GPtrArray *requests_satisfied,
1971     guint64 timestamp,
1972     GHashTable *handler_info,
1973     gpointer user_data,
1974     GError **error)
1975 {
1976   EmpathyDispatcher *self = EMPATHY_DISPATCHER (user_data);
1977   EmpathyDispatcherPriv *priv = GET_PRIV (self);
1978   guint i;
1979   TpAccount *account;
1980   TpConnection *connection;
1981
1982   /* FIXME: should probably find out whether the account manager is prepared
1983    * before ensuring. */
1984   account = tp_account_manager_ensure_account (priv->account_manager,
1985     account_path);
1986   g_assert (account != NULL);
1987
1988   connection = tp_account_ensure_connection (account, connection_path);
1989   if (connection == NULL)
1990     {
1991       g_set_error_literal (error, TP_ERRORS, TP_ERROR_INVALID_ARGUMENT,
1992         "Invalid connection argument");
1993       return FALSE;
1994     }
1995
1996   for (i = 0; i < channels->len ; i++)
1997     {
1998       GValueArray *arr = g_ptr_array_index (channels, i);
1999       const gchar *object_path;
2000       GHashTable *properties;
2001
2002       object_path = g_value_get_boxed (g_value_array_get_nth (arr, 0));
2003       properties = g_value_get_boxed (g_value_array_get_nth (arr, 1));
2004
2005       dispatcher_connection_new_channel_with_properties (self,
2006         connection, object_path, properties);
2007     }
2008
2009   return TRUE;
2010 }
2011
2012
2013 EmpathyHandler *
2014 empathy_dispatcher_add_handler (EmpathyDispatcher *self,
2015     const gchar *name,
2016     GPtrArray *filters,
2017     GStrv capabilities)
2018 {
2019   EmpathyDispatcherPriv *priv = GET_PRIV (self);
2020   EmpathyHandler *handler;
2021
2022   handler = empathy_handler_new (name, filters, capabilities);
2023   priv->handlers = g_list_prepend (priv->handlers, handler);
2024
2025   /* Only set the handle_channels function, the Channel property on the main
2026    * handler will always report all dispatched channels even if they came from
2027    * a different Handler */
2028   empathy_handler_set_handle_channels_func (handler,
2029     empathy_dispatcher_handle_channels, self);
2030
2031   return handler;
2032 }
2033
2034 void
2035 empathy_dispatcher_remove_handler (EmpathyDispatcher *self,
2036   EmpathyHandler *handler)
2037 {
2038   EmpathyDispatcherPriv *priv = GET_PRIV (self);
2039   GList *h;
2040
2041   h = g_list_find (priv->handlers, handler);
2042   g_return_if_fail (h != NULL);
2043
2044   priv->handlers = g_list_delete_link (priv->handlers, h);
2045
2046   g_object_unref (handler);
2047 }