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