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