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