]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
mission_control_get_tpconnection returns a new ref, don't forget to unref the connection.
[empathy.git] / libempathy / empathy-dispatcher.c
1 /* * Copyright (C) 2007-2008 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  */
19
20 #include <config.h>
21
22 #include <string.h>
23
24 #include <glib/gi18n-lib.h>
25
26 #include <telepathy-glib/enums.h>
27 #include <telepathy-glib/connection.h>
28 #include <telepathy-glib/util.h>
29 #include <telepathy-glib/dbus.h>
30 #include <telepathy-glib/proxy-subclass.h>
31
32 #include <libmissioncontrol/mission-control.h>
33 #include <libmissioncontrol/mc-account.h>
34
35 #include <extensions/extensions.h>
36
37 #include "empathy-dispatcher.h"
38 #include "empathy-utils.h"
39 #include "empathy-tube-handler.h"
40 #include "empathy-account-manager.h"
41 #include "empathy-contact-factory.h"
42 #include "empathy-tp-group.h"
43 #include "empathy-tp-file.h"
44 #include "empathy-chatroom-manager.h"
45 #include "empathy-utils.h"
46
47 #define DEBUG_FLAG EMPATHY_DEBUG_DISPATCHER
48 #include <libempathy/empathy-debug.h>
49
50 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyDispatcher)
51 typedef struct {
52   EmpathyAccountManager *account_manager;
53   MissionControl *mc;
54   /* connection to connection data mapping */
55   GHashTable     *connections;
56   /* accounts to connection mapping */
57   GHashTable     *accounts;
58   gpointer       token;
59   GSList         *tubes;
60 } EmpathyDispatcherPriv;
61
62 G_DEFINE_TYPE (EmpathyDispatcher, empathy_dispatcher, G_TYPE_OBJECT);
63
64 enum {
65   OBSERVE,
66   APPROVE,
67   DISPATCH,
68   LAST_SIGNAL
69 };
70
71 static guint signals[LAST_SIGNAL];
72 static EmpathyDispatcher *dispatcher = NULL;
73
74 typedef struct {
75   EmpathyDispatcher *dispatcher;
76   EmpathyDispatchOperation *operation;
77   TpConnection *connection;
78   gchar *channel_type;
79   guint handle_type;
80   guint handle;
81   EmpathyContact *contact;
82
83   /* Properties to pass to the channel when requesting it */
84   GHashTable *request;
85   EmpathyDispatcherRequestCb *cb;
86   gpointer user_data;
87   gpointer *request_data;
88 } DispatcherRequestData;
89
90 typedef struct {
91   TpChannel *channel;
92   /* Channel type specific wrapper object */
93   GObject *channel_wrapper;
94 } DispatchData;
95
96 typedef struct {
97   McAccount *account;
98   /* ObjectPath => DispatchData.. */
99   GHashTable *dispatched_channels;
100   /* ObjectPath -> EmpathyDispatchOperations */
101   GHashTable *dispatching_channels;
102   /* ObjectPath -> EmpathyDispatchOperations */
103   GHashTable *outstanding_channels;
104   /* List of DispatcherRequestData */
105   GList *outstanding_requests;
106 } ConnectionData;
107
108 static DispatchData *
109 new_dispatch_data (TpChannel *channel, GObject *channel_wrapper)
110 {
111   DispatchData *d = g_slice_new0 (DispatchData);
112   d->channel = g_object_ref (channel);
113   d->channel_wrapper = g_object_ref (channel_wrapper);
114
115   return d;
116 }
117
118 static void
119 free_dispatch_data (DispatchData *data)
120 {
121   g_object_unref (data->channel);
122   g_object_unref (data->channel_wrapper);
123
124   g_slice_free (DispatchData, data);
125 }
126
127
128 static DispatcherRequestData *
129 new_dispatcher_request_data (EmpathyDispatcher *dispatcher,
130   TpConnection *connection, const gchar *channel_type, guint handle_type,
131   guint handle, GHashTable *request,
132   EmpathyContact *contact, EmpathyDispatcherRequestCb *cb, gpointer user_data)
133 {
134   DispatcherRequestData *result = g_slice_new0 (DispatcherRequestData);
135
136   result->dispatcher = dispatcher;
137   result->connection = connection;
138
139   result->channel_type = g_strdup (channel_type);
140   result->handle_type = handle_type;
141   result->handle = handle;
142   result->request = request;
143
144   if (contact != NULL)
145     result->contact = g_object_ref (contact);
146
147   result->cb = cb;
148   result->user_data = user_data;
149
150   return result;
151 }
152
153 static void
154 free_dispatcher_request_data (DispatcherRequestData *r)
155 {
156   g_free (r->channel_type);
157
158   if (r->contact != NULL)
159     g_object_unref (r->contact);
160
161   if (r->request != NULL)
162     g_hash_table_unref (r->request);
163
164   g_slice_free (DispatcherRequestData, r);
165 }
166
167 static ConnectionData *
168 new_connection_data (McAccount *account)
169 {
170   ConnectionData *cd = g_slice_new0 (ConnectionData);
171   cd->account = g_object_ref (account);
172
173   cd->dispatched_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
174     g_free, (GDestroyNotify) free_dispatch_data);
175
176   cd->dispatching_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
177     g_free, g_object_unref);
178
179   cd->outstanding_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
180     g_free, NULL);
181
182   return cd;
183 }
184
185 static void
186 free_connection_data (ConnectionData *cd)
187 {
188   GList *l;
189   g_object_unref (cd->account);
190   g_hash_table_destroy (cd->dispatched_channels);
191   g_hash_table_destroy (cd->dispatching_channels);
192
193   for (l = cd->outstanding_requests ; l != NULL; l = g_list_delete_link (l,l))
194     {
195       free_dispatcher_request_data (l->data);
196     }
197 }
198
199 static void
200 dispatcher_connection_invalidated_cb (TpConnection  *connection,
201   guint          domain, gint           code, gchar         *message,
202   EmpathyDispatcher *dispatcher)
203 {
204   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
205   ConnectionData *cd;
206
207   DEBUG ("Error: %s", message);
208   cd = g_hash_table_lookup (priv->connections, connection);
209
210   g_hash_table_remove (priv->accounts, cd->account);
211   g_hash_table_remove (priv->connections, connection);
212 }
213
214 static gboolean
215 dispatcher_operation_can_start (EmpathyDispatcher *self,
216   EmpathyDispatchOperation *operation, ConnectionData *cd)
217 {
218   GList *l;
219   const gchar *channel_type =
220     empathy_dispatch_operation_get_channel_type (operation);
221
222   for (l = cd->outstanding_requests; l != NULL; l = g_list_next (l))
223     {
224       DispatcherRequestData *d = (DispatcherRequestData *) l->data;
225
226       if (d->operation == NULL && !tp_strdiff (d->channel_type, channel_type))
227         {
228           return FALSE;
229         }
230     }
231
232   return TRUE;
233 }
234
235 static void
236 dispatch_operation_flush_requests (EmpathyDispatcher *dispatcher,
237   EmpathyDispatchOperation *operation, GError *error, ConnectionData *cd)
238 {
239   GList *l;
240
241   l = cd->outstanding_requests;
242   while (l != NULL)
243     {
244       DispatcherRequestData *d = (DispatcherRequestData *) l->data;
245       GList *lt = l;
246
247       l = g_list_next (l);
248
249       if (d->operation == operation)
250         {
251           if (d->cb != NULL)
252             {
253               if (error != NULL)
254                 d->cb (NULL, error, d->user_data);
255               else
256                 d->cb (operation, NULL, d->user_data);
257             }
258
259           cd->outstanding_requests = g_list_delete_link
260             (cd->outstanding_requests, lt);
261
262           free_dispatcher_request_data (d);
263         }
264     }
265 }
266
267 static void
268 dispatcher_channel_invalidated_cb (TpProxy *proxy, guint domain, gint code,
269   gchar *message, EmpathyDispatcher *dispatcher)
270 {
271   /* Channel went away... */
272   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
273   TpConnection *connection;
274   EmpathyDispatchOperation *operation;
275   ConnectionData *cd;
276   const gchar *object_path;
277
278   connection = tp_channel_borrow_connection (TP_CHANNEL (proxy));
279
280   cd = g_hash_table_lookup (priv->connections, connection);
281   /* Connection itself invalidated? */
282   if (cd == NULL)
283     return;
284
285   object_path = tp_proxy_get_object_path (proxy);
286
287   DEBUG ("Channel %s invalidated", object_path);
288
289   g_hash_table_remove (cd->dispatched_channels, object_path);
290   g_hash_table_remove (cd->dispatching_channels, object_path);
291
292   operation = g_hash_table_lookup (cd->outstanding_channels, object_path);
293   if (operation != NULL)
294     {
295       GError error = { domain, code, message };
296       dispatch_operation_flush_requests (dispatcher, operation, &error, cd);
297       g_hash_table_remove (cd->outstanding_channels, object_path);
298       g_object_unref (operation);
299     }
300 }
301
302 static void
303 dispatch_operation_approved_cb (EmpathyDispatchOperation *operation,
304   EmpathyDispatcher *dispatcher)
305 {
306   g_assert (empathy_dispatch_operation_is_incoming (operation));
307   DEBUG ("Send of for dispatching: %s",
308     empathy_dispatch_operation_get_object_path (operation));
309   g_signal_emit (dispatcher, signals[DISPATCH], 0, operation);
310 }
311
312 static void
313 dispatch_operation_claimed_cb (EmpathyDispatchOperation *operation,
314   EmpathyDispatcher *dispatcher)
315 {
316   /* Our job is done, remove the dispatch operation and mark the channel as
317    * dispatched */
318   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
319   TpConnection *connection;
320   ConnectionData *cd;
321   const gchar *object_path;
322
323   connection = empathy_dispatch_operation_get_tp_connection (operation);
324   cd = g_hash_table_lookup (priv->connections, connection);
325   g_assert (cd != NULL);
326   g_object_unref (G_OBJECT (connection));
327
328   object_path = empathy_dispatch_operation_get_object_path (operation);
329
330   if (g_hash_table_lookup (cd->dispatched_channels, object_path) == NULL)
331     {
332       DispatchData *d;
333       d = new_dispatch_data (
334         empathy_dispatch_operation_get_channel (operation),
335         empathy_dispatch_operation_get_channel_wrapper (operation));
336       g_hash_table_insert (cd->dispatched_channels,
337         g_strdup (object_path), d);
338     }
339   g_hash_table_remove (cd->dispatching_channels, object_path);
340
341   DEBUG ("Channel claimed: %s", object_path);
342 }
343
344 static void
345 dispatch_operation_ready_cb (EmpathyDispatchOperation *operation,
346   EmpathyDispatcher *dispatcher)
347 {
348   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
349   TpConnection *connection;
350   ConnectionData *cd;
351   EmpathyDispatchOperationState status;
352
353   g_signal_connect (operation, "approved",
354     G_CALLBACK (dispatch_operation_approved_cb), dispatcher);
355
356   g_signal_connect (operation, "claimed",
357     G_CALLBACK (dispatch_operation_claimed_cb), dispatcher);
358
359   /* Signal the observers */
360   DEBUG ("Send to observers: %s",
361     empathy_dispatch_operation_get_object_path (operation));
362   g_signal_emit (dispatcher, signals[OBSERVE], 0, operation);
363
364   empathy_dispatch_operation_start (operation);
365
366   /* Signal potential requestors */
367   connection =  empathy_dispatch_operation_get_tp_connection (operation);
368   cd = g_hash_table_lookup (priv->connections, connection);
369   g_assert (cd != NULL);
370   g_object_unref (G_OBJECT (connection));
371
372   g_object_ref (operation);
373
374   dispatch_operation_flush_requests (dispatcher, operation, NULL, cd);
375   status = empathy_dispatch_operation_get_status (operation);
376   g_object_unref (operation);
377
378   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_CLAIMED)
379     return;
380
381   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
382     {
383       DEBUG ("Send to approvers: %s",
384         empathy_dispatch_operation_get_object_path (operation));
385       g_signal_emit (dispatcher, signals[APPROVE], 0, operation);
386     }
387   else
388     {
389       g_assert (status == EMPATHY_DISPATCHER_OPERATION_STATE_DISPATCHING);
390       DEBUG ("Send of for dispatching: %s",
391         empathy_dispatch_operation_get_object_path (operation));
392       g_signal_emit (dispatcher, signals[DISPATCH], 0, operation);
393     }
394
395 }
396
397 static void
398 dispatcher_start_dispatching (EmpathyDispatcher *self,
399   EmpathyDispatchOperation *operation, ConnectionData *cd)
400 {
401   const gchar *object_path =
402     empathy_dispatch_operation_get_object_path (operation);
403
404   DEBUG ("Dispatching process started for %s", object_path);
405
406   if (g_hash_table_lookup (cd->dispatching_channels, object_path) == NULL)
407     {
408       g_assert (g_hash_table_lookup (cd->outstanding_channels,
409         object_path) == NULL);
410
411       g_hash_table_insert (cd->dispatching_channels,
412         g_strdup (object_path), operation);
413
414       switch (empathy_dispatch_operation_get_status (operation))
415         {
416           case EMPATHY_DISPATCHER_OPERATION_STATE_PREPARING:
417             g_signal_connect (operation, "ready",
418               G_CALLBACK (dispatch_operation_ready_cb), dispatcher);
419             break;
420           case EMPATHY_DISPATCHER_OPERATION_STATE_PENDING:
421             dispatch_operation_ready_cb (operation, dispatcher);
422             break;
423           default:
424             g_assert_not_reached();
425         }
426
427     }
428   else if (empathy_dispatch_operation_get_status (operation) >=
429       EMPATHY_DISPATCHER_OPERATION_STATE_PENDING)
430     {
431       /* Already dispatching and the operation is pending, thus the observers
432        * have seen it (if applicable), so we can flush the request right away.
433        */
434       dispatch_operation_flush_requests (self, operation, NULL, cd);
435     }
436 }
437
438
439 static void
440 dispatcher_flush_outstanding_operations (EmpathyDispatcher *self,
441   ConnectionData *cd)
442 {
443   GHashTableIter iter;
444   gpointer value;
445
446   g_hash_table_iter_init (&iter, cd->outstanding_channels);
447   while (g_hash_table_iter_next (&iter, NULL, &value))
448     {
449       EmpathyDispatchOperation *operation = EMPATHY_DISPATCH_OPERATION (value);
450
451       if (dispatcher_operation_can_start (self, operation, cd))
452         {
453           dispatcher_start_dispatching (dispatcher, operation, cd);
454           g_hash_table_iter_remove (&iter);
455         }
456     }
457 }
458
459
460 static void
461 dispatcher_connection_new_channel (EmpathyDispatcher *dispatcher,
462   TpConnection *connection,
463   const gchar  *object_path, const gchar  *channel_type,
464   guint handle_type, guint handle, GHashTable *properties,
465   gboolean incoming)
466 {
467   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
468   TpChannel         *channel;
469   ConnectionData *cd;
470   EmpathyDispatchOperation *operation;
471   EmpathyContact *contact = NULL;
472   int i;
473   /* Channel types we never want to dispatch because they're either deprecated
474    * or can't sensibly be dispatch (e.g. channels that should always be
475    * requested) */
476   const char *blacklist[] = {
477     TP_IFACE_CHANNEL_TYPE_CONTACT_LIST,
478     TP_IFACE_CHANNEL_TYPE_TUBES,
479     TP_IFACE_CHANNEL_TYPE_ROOM_LIST,
480     NULL
481   };
482
483   cd = g_hash_table_lookup (priv->connections, connection);
484
485   /* Don't bother with channels we have already dispatched or are dispatching
486    * currently. This can happen when NewChannel(s) is fired after
487    * RequestChannel/CreateChannel/EnsureChannel */
488   if (g_hash_table_lookup (cd->dispatched_channels, object_path) != NULL)
489     return;
490
491   if (g_hash_table_lookup (cd->dispatching_channels, object_path) != NULL)
492     return;
493
494   /* Should never occur, but just in case a CM fires spurious NewChannel(s) 
495    * signals */
496   if (g_hash_table_lookup (cd->outstanding_channels, object_path) != NULL)
497     return;
498
499   /* Only pick up non-requested text channels. For all other it doesn't make
500    * sense to handle it if we didn't request it. The same goes for channels we
501    * discovered by the Channels property or ListChannels */
502   if (!incoming && tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TEXT))
503     {
504       DEBUG ("Ignoring incoming channel of type %s on %s",
505         channel_type, object_path);
506       return;
507     }
508
509   for (i = 0 ; blacklist[i] != NULL; i++)
510     {
511       if (!tp_strdiff (channel_type, blacklist[i]))
512         {
513           DEBUG ("Ignoring blacklisted channel type %s on %s",
514             channel_type, object_path);
515           return;
516         }
517     }
518
519   DEBUG ("New channel of type %s on %s", channel_type, object_path);
520
521   if (properties == NULL)
522     channel = tp_channel_new (connection, object_path, channel_type,
523       handle_type, handle, NULL);
524   else
525     channel = tp_channel_new_from_properties (connection, object_path,
526       properties, NULL);
527
528   g_signal_connect (channel, "invalidated",
529     G_CALLBACK (dispatcher_channel_invalidated_cb),
530     dispatcher);
531
532   if (handle_type == TP_CONN_HANDLE_TYPE_CONTACT)
533     {
534       EmpathyContactFactory *factory = empathy_contact_factory_dup_singleton ();
535       contact = empathy_contact_factory_get_from_handle (factory,
536         cd->account, handle);
537       g_object_unref (factory);
538     }
539
540   operation = empathy_dispatch_operation_new (connection, channel, contact,
541     incoming);
542
543   g_object_unref (channel);
544
545   if (incoming)
546     {
547       /* Request could either be by us or by a remote party. If there are no
548        * outstanding requests for this channel type we can assume it's remote.
549        * Otherwise we wait untill they are all satisfied */
550       if (dispatcher_operation_can_start (dispatcher, operation, cd))
551         dispatcher_start_dispatching (dispatcher, operation, cd);
552       else
553         g_hash_table_insert (cd->outstanding_channels,
554           g_strdup (object_path), operation);
555     }
556   else
557     {
558       dispatcher_start_dispatching (dispatcher, operation, cd);
559     }
560 }
561
562 static void
563 dispatcher_connection_new_channel_cb (TpConnection *connection,
564   const gchar  *object_path, const gchar  *channel_type,
565   guint         handle_type, guint         handle,
566   gboolean      suppress_handler, gpointer      user_data,
567   GObject      *object)
568 {
569   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
570
571   /* Empathy heavily abuses surpress handler (don't try this at home), if
572    * surpress handler is true then it is an outgoing channel, which is
573    * requested either by us or some other party (like the megaphone applet).
574    * Otherwise it's an incoming channel */
575   dispatcher_connection_new_channel (dispatcher, connection,
576     object_path, channel_type, handle_type, handle, NULL, !suppress_handler);
577 }
578
579 static void
580 dispatcher_connection_new_channel_with_properties (
581   EmpathyDispatcher *dispatcher, TpConnection *connection,
582   const gchar *object_path, GHashTable *properties)
583 {
584   const gchar *channel_type;
585   guint handle_type;
586   guint handle;
587   gboolean requested;
588   gboolean valid;
589
590
591   channel_type = tp_asv_get_string (properties,
592     TP_IFACE_CHANNEL ".ChannelType");
593   if (channel_type == NULL)
594     {
595       g_message ("%s had an invalid ChannelType property", object_path);
596       return;
597     }
598
599   handle_type = tp_asv_get_uint32 (properties,
600     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
601   if (!valid)
602     {
603       g_message ("%s had an invalid TargetHandleType property", object_path);
604       return;
605     }
606
607   handle = tp_asv_get_uint32 (properties,
608     TP_IFACE_CHANNEL ".TargetHandle", &valid);
609   if (!valid)
610     {
611       g_message ("%s had an invalid TargetHandle property", object_path);
612       return;
613     }
614
615   /* We assume there is no channel dispather, so we're the only one dispatching
616    * it. Which means that a requested channel it is outgoing one */
617   requested = tp_asv_get_boolean (properties,
618     TP_IFACE_CHANNEL ".Requested", &valid);
619   if (!valid)
620     {
621       g_message ("%s had an invalid Requested property", object_path);
622       return;
623     }
624
625   dispatcher_connection_new_channel (dispatcher, connection,
626     object_path, channel_type, handle_type, handle, properties, !requested);
627 }
628
629
630 static void
631 dispatcher_connection_new_channels_cb (
632   TpConnection *connection, const GPtrArray *channels, gpointer user_data,
633   GObject *object)
634 {
635   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
636   int i;
637
638   for (i = 0; i < channels->len ; i++)
639     {
640       GValueArray *arr = g_ptr_array_index (channels, i);
641       const gchar *object_path;
642       GHashTable *properties;
643
644       object_path = g_value_get_boxed (g_value_array_get_nth (arr, 0));
645       properties = g_value_get_boxed (g_value_array_get_nth (arr, 1));
646
647       dispatcher_connection_new_channel_with_properties (dispatcher,
648         connection, object_path, properties);
649     }
650 }
651
652 static void
653 dispatcher_connection_got_channels_property (TpProxy *proxy,
654   const GValue *channels_prop, const GError *error, gpointer user_data,
655   GObject *object)
656 {
657   GPtrArray *channels;
658
659   if (error) {
660     DEBUG ("Error: %s", error->message);
661     return;
662   }
663
664   channels = g_value_get_boxed (channels_prop);
665   dispatcher_connection_new_channels_cb (TP_CONNECTION (proxy),
666     channels, NULL, object);
667 }
668
669 static void
670 dispatcher_connection_list_channels_cb (TpConnection    *connection,
671                                         const GPtrArray *channels,
672                                         const GError    *error,
673                                         gpointer         user_data,
674                                         GObject         *dispatcher)
675 {
676         int i;
677
678         if (error) {
679                 DEBUG ("Error: %s", error->message);
680                 return;
681         }
682
683         for (i = 0; i < channels->len; i++) {
684                 GValueArray *values;
685
686                 values = g_ptr_array_index (channels, i);
687                 /* We don't have any extra info, so assume already existing channels are
688                  * incoming... */
689                 dispatcher_connection_new_channel (EMPATHY_DISPATCHER (dispatcher),
690                         connection,
691                         g_value_get_boxed (g_value_array_get_nth (values, 0)),
692                         g_value_get_string (g_value_array_get_nth (values, 1)),
693                         g_value_get_uint (g_value_array_get_nth (values, 2)),
694                         g_value_get_uint (g_value_array_get_nth (values, 3)),
695                         NULL, TRUE);
696         }
697 }
698
699 static void
700 dispatcher_connection_advertise_capabilities_cb (TpConnection    *connection,
701                                                  const GPtrArray *capabilities,
702                                                  const GError    *error,
703                                                  gpointer         user_data,
704                                                  GObject         *dispatcher)
705 {
706         if (error) {
707                 DEBUG ("Error: %s", error->message);
708         }
709 }
710
711 static void
712 dispatcher_connection_ready_cb (TpConnection  *connection,
713   const GError *error, gpointer       dispatcher)
714 {
715   GPtrArray   *capabilities;
716   GType        cap_type;
717   GValue       cap = {0, };
718   const gchar *remove = NULL;
719
720   if (error)
721     {
722       dispatcher_connection_invalidated_cb (connection, error->domain,
723         error->code, error->message, dispatcher);
724       return;
725     }
726
727   g_signal_connect (connection, "invalidated",
728     G_CALLBACK (dispatcher_connection_invalidated_cb), dispatcher);
729
730
731   if (tp_proxy_has_interface_by_id (TP_PROXY (connection),
732       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
733     {
734       tp_cli_connection_interface_requests_connect_to_new_channels (connection,
735         dispatcher_connection_new_channels_cb,
736         NULL, NULL, G_OBJECT (dispatcher), NULL);
737
738       tp_cli_dbus_properties_call_get (connection, -1,
739         TP_IFACE_CONNECTION_INTERFACE_REQUESTS, "Channels",
740         dispatcher_connection_got_channels_property,
741         NULL, NULL, dispatcher);
742     }
743   else
744     {
745       tp_cli_connection_connect_to_new_channel (connection,
746         dispatcher_connection_new_channel_cb,
747         NULL, NULL, G_OBJECT (dispatcher), NULL);
748
749       tp_cli_connection_call_list_channels (connection, -1,
750         dispatcher_connection_list_channels_cb, NULL, NULL,
751         G_OBJECT (dispatcher));
752
753     }
754
755   /* Advertise VoIP capabilities */
756   /* FIXME: Capabilities is leaked */
757   capabilities = g_ptr_array_sized_new (1);
758   cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
759     G_TYPE_UINT, G_TYPE_INVALID);
760   g_value_init (&cap, cap_type);
761   g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
762   dbus_g_type_struct_set (&cap,
763         0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
764         1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
765            TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
766            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
767            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P, G_MAXUINT);
768   g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
769
770   tp_cli_connection_interface_capabilities_call_advertise_capabilities (
771     connection, -1, capabilities, &remove,
772     dispatcher_connection_advertise_capabilities_cb,
773     NULL, NULL, G_OBJECT (dispatcher));
774 }
775
776 static void
777 dispatcher_update_account (EmpathyDispatcher *dispatcher, McAccount *account)
778 {
779   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
780   TpConnection *connection;
781
782   connection = g_hash_table_lookup (priv->accounts, account);
783   if  (connection != NULL)
784     return;
785
786   connection = mission_control_get_tpconnection (priv->mc, account, NULL);
787   if (connection == NULL)
788     return;
789
790   g_hash_table_insert (priv->connections, g_object_ref (connection),
791     new_connection_data (account));
792
793   g_hash_table_insert (priv->accounts, g_object_ref (account),
794     g_object_ref (connection));
795
796   tp_connection_call_when_ready (connection, dispatcher_connection_ready_cb,
797     dispatcher);
798
799   g_object_unref (connection);
800 }
801
802 static void
803 dispatcher_account_connection_cb (EmpathyAccountManager *manager,
804   McAccount *account, TpConnectionStatusReason reason,
805   TpConnectionStatus status, TpConnectionStatus previous,
806   EmpathyDispatcher *dispatcher)
807 {
808   dispatcher_update_account (dispatcher, account);
809 }
810
811
812 static GObject*
813 dispatcher_constructor (GType type, guint n_construct_params,
814   GObjectConstructParam *construct_params)
815 {
816   GObject *retval;
817
818   if (dispatcher == NULL)
819     {
820       retval = G_OBJECT_CLASS (empathy_dispatcher_parent_class)->constructor
821           (type, n_construct_params, construct_params);
822
823       dispatcher = EMPATHY_DISPATCHER (retval);
824       g_object_add_weak_pointer (retval, (gpointer *) &dispatcher);
825     }
826   else
827     {
828       retval = g_object_ref (dispatcher);
829     }
830
831   return retval;
832 }
833
834 static void
835 dispatcher_finalize (GObject *object)
836 {
837   EmpathyDispatcherPriv *priv = GET_PRIV (object);
838
839   g_signal_handlers_disconnect_by_func (priv->account_manager,
840       dispatcher_account_connection_cb, object);
841
842   g_object_unref (priv->account_manager);
843   g_object_unref (priv->mc);
844
845   g_hash_table_destroy (priv->accounts);
846   g_hash_table_destroy (priv->connections);
847 }
848
849 static void
850 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
851 {
852   GObjectClass *object_class = G_OBJECT_CLASS (klass);
853
854   object_class->finalize = dispatcher_finalize;
855   object_class->constructor = dispatcher_constructor;
856
857   signals[OBSERVE] =
858     g_signal_new ("observe",
859       G_TYPE_FROM_CLASS (klass),
860       G_SIGNAL_RUN_LAST,
861       0,
862       NULL, NULL,
863       g_cclosure_marshal_VOID__OBJECT,
864       G_TYPE_NONE,
865       1, EMPATHY_TYPE_DISPATCH_OPERATION);
866
867   signals[APPROVE] =
868     g_signal_new ("approve",
869       G_TYPE_FROM_CLASS (klass),
870       G_SIGNAL_RUN_LAST,
871       0,
872       NULL, NULL,
873       g_cclosure_marshal_VOID__OBJECT,
874       G_TYPE_NONE,
875       1, EMPATHY_TYPE_DISPATCH_OPERATION);
876
877   signals[DISPATCH] =
878     g_signal_new ("dispatch",
879       G_TYPE_FROM_CLASS (klass),
880       G_SIGNAL_RUN_LAST,
881       0,
882       NULL, NULL,
883       g_cclosure_marshal_VOID__OBJECT,
884       G_TYPE_NONE,
885       1, EMPATHY_TYPE_DISPATCH_OPERATION);
886
887   g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
888
889 }
890
891 static void
892 empathy_dispatcher_init (EmpathyDispatcher *dispatcher)
893 {
894   GList *accounts, *l;
895   EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (dispatcher,
896     EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
897
898   dispatcher->priv = priv;
899   priv->mc = empathy_mission_control_new ();
900   priv->account_manager = empathy_account_manager_dup_singleton ();
901
902   g_signal_connect (priv->account_manager,
903     "account-connection-changed",
904     G_CALLBACK (dispatcher_account_connection_cb),
905     dispatcher);
906
907   priv->accounts = g_hash_table_new_full (empathy_account_hash,
908         empathy_account_equal, g_object_unref, g_object_unref);
909
910   priv->connections = g_hash_table_new_full (g_direct_hash, g_direct_equal,
911     g_object_unref, (GDestroyNotify) free_connection_data);
912
913   accounts = mc_accounts_list_by_enabled (TRUE);
914
915   for (l = accounts; l; l = l->next) {
916     dispatcher_update_account (dispatcher, l->data);
917     g_object_unref (l->data);
918   }
919   g_list_free (accounts);
920 }
921
922 EmpathyDispatcher *
923 empathy_dispatcher_dup_singleton (void)
924 {
925   return EMPATHY_DISPATCHER (g_object_new (EMPATHY_TYPE_DISPATCHER, NULL));
926 }
927
928 static void
929 dispatcher_request_failed (EmpathyDispatcher *dispatcher,
930   DispatcherRequestData *request_data, const GError *error)
931 {
932   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
933   ConnectionData *conn_data;
934
935   conn_data = g_hash_table_lookup (priv->connections, request_data->connection);
936   if (request_data->cb != NULL)
937     request_data->cb (NULL, error, request_data->user_data);
938
939   conn_data->outstanding_requests =
940       g_list_remove (conn_data->outstanding_requests, request_data);
941   free_dispatcher_request_data (request_data);
942 }
943
944 static void
945 dispatcher_connection_new_requested_channel (EmpathyDispatcher *dispatcher,
946   DispatcherRequestData *request_data, const gchar *object_path,
947   GHashTable *properties, const GError *error)
948 {
949   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
950   EmpathyDispatchOperation *operation = NULL;
951   ConnectionData *conn_data;
952
953   conn_data = g_hash_table_lookup (priv->connections,
954     request_data->connection);
955
956   if (error)
957     {
958       DEBUG ("Channel request failed: %s", error->message);
959
960       dispatcher_request_failed (dispatcher, request_data, error);
961
962       goto out;
963   }
964
965   operation = g_hash_table_lookup (conn_data->outstanding_channels,
966     object_path);
967
968   if (operation != NULL)
969     g_hash_table_remove (conn_data->outstanding_channels, object_path);
970   else
971     operation = g_hash_table_lookup (conn_data->dispatching_channels,
972         object_path);
973
974   if (operation == NULL)
975     {
976       DispatchData *data = g_hash_table_lookup (conn_data->dispatched_channels,
977         object_path);
978
979       if (data != NULL)
980         {
981           operation = empathy_dispatch_operation_new_with_wrapper (
982             request_data->connection,
983             data->channel, request_data->contact, FALSE,
984             data->channel_wrapper);
985         }
986       else
987         {
988           TpChannel *channel;
989
990           if (properties != NULL)
991             channel = tp_channel_new_from_properties (request_data->connection,
992               object_path, properties, NULL);
993           else
994             channel = tp_channel_new (request_data->connection, object_path,
995               request_data->channel_type, request_data->handle_type,
996               request_data->handle, NULL);
997
998           g_signal_connect (channel, "invalidated",
999             G_CALLBACK (dispatcher_channel_invalidated_cb),
1000             request_data->dispatcher);
1001
1002           operation = empathy_dispatch_operation_new (request_data->connection,
1003              channel, request_data->contact, FALSE);
1004           g_object_unref (channel);
1005         }
1006     }
1007   else
1008     {
1009       /* Already existed set potential extra information */
1010       g_object_set (G_OBJECT (operation),
1011         "contact", request_data->contact,
1012         NULL);
1013     }
1014
1015   request_data->operation = operation;
1016
1017   /* (pre)-approve this right away as we requested it */
1018   empathy_dispatch_operation_approve (operation);
1019
1020   dispatcher_start_dispatching (request_data->dispatcher, operation,
1021         conn_data);
1022 out:
1023   dispatcher_flush_outstanding_operations (request_data->dispatcher,
1024     conn_data);
1025 }
1026
1027 static void
1028 dispatcher_request_channel_cb (TpConnection *connection,
1029   const gchar  *object_path, const GError *error,
1030   gpointer      user_data, GObject      *weak_object)
1031 {
1032   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1033   DispatcherRequestData *request_data = (DispatcherRequestData*) user_data;
1034
1035   dispatcher_connection_new_requested_channel (dispatcher,
1036     request_data, object_path, NULL, error);
1037 }
1038
1039 static void
1040 dispatcher_request_channel (DispatcherRequestData *request_data)
1041 {
1042   tp_cli_connection_call_request_channel (request_data->connection, -1,
1043     request_data->channel_type,
1044     request_data->handle_type,
1045     request_data->handle,
1046     TRUE, dispatcher_request_channel_cb,
1047     request_data, NULL, G_OBJECT (request_data->dispatcher));
1048 }
1049
1050 void
1051 empathy_dispatcher_call_with_contact ( EmpathyContact *contact,
1052   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1053 {
1054   EmpathyDispatcher *dispatcher = empathy_dispatcher_dup_singleton();
1055   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1056   McAccount *account;
1057   TpConnection *connection;
1058   ConnectionData *cd;
1059   DispatcherRequestData *request_data;
1060
1061   account = empathy_contact_get_account (contact);
1062   connection = g_hash_table_lookup (priv->accounts, account);
1063
1064   g_assert (connection != NULL);
1065   cd = g_hash_table_lookup (priv->connections, connection);
1066   request_data  = new_dispatcher_request_data (dispatcher, connection,
1067     TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA, TP_HANDLE_TYPE_NONE, 0, NULL,
1068     contact, callback, user_data);
1069
1070   cd->outstanding_requests = g_list_prepend
1071     (cd->outstanding_requests, request_data);
1072
1073   dispatcher_request_channel (request_data);
1074
1075   g_object_unref (dispatcher);
1076 }
1077
1078
1079 static void
1080 dispatcher_chat_with_contact_cb (EmpathyContact *contact,
1081   const GError *error, gpointer user_data, GObject *object)
1082 {
1083   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1084
1085   request_data->handle = empathy_contact_get_handle (contact);
1086
1087   dispatcher_request_channel (request_data);
1088 }
1089
1090 void
1091 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1092   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1093 {
1094   EmpathyDispatcher *dispatcher;
1095   EmpathyDispatcherPriv *priv;
1096   McAccount *account;
1097   TpConnection *connection;
1098   ConnectionData *connection_data;
1099   DispatcherRequestData *request_data;
1100
1101   dispatcher = empathy_dispatcher_dup_singleton();
1102   priv = GET_PRIV (dispatcher);
1103
1104   account = empathy_contact_get_account (contact);
1105   connection = g_hash_table_lookup (priv->accounts, account);
1106   connection_data = g_hash_table_lookup (priv->connections, connection);
1107
1108   /* The contact handle might not be known yet */
1109   request_data  = new_dispatcher_request_data (dispatcher, connection,
1110     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT, 0, NULL,
1111     contact, callback, user_data);
1112
1113   connection_data->outstanding_requests = g_list_prepend
1114     (connection_data->outstanding_requests, request_data);
1115
1116   empathy_contact_call_when_ready (contact,
1117     EMPATHY_CONTACT_READY_HANDLE, dispatcher_chat_with_contact_cb,
1118     request_data, NULL, G_OBJECT (dispatcher));
1119
1120   g_object_unref (dispatcher);
1121 }
1122
1123 void
1124 empathy_dispatcher_chat_with_contact_id (McAccount *account, const gchar
1125   *contact_id, EmpathyDispatcherRequestCb *callback, gpointer user_data)
1126 {
1127   EmpathyDispatcher *dispatcher = empathy_dispatcher_dup_singleton ();
1128   EmpathyContactFactory *factory;
1129   EmpathyContact        *contact;
1130
1131   factory = empathy_contact_factory_dup_singleton ();
1132   contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
1133
1134   empathy_dispatcher_chat_with_contact (contact, callback, user_data);
1135
1136   g_object_unref (contact);
1137   g_object_unref (factory);
1138   g_object_unref (dispatcher);
1139 }
1140
1141
1142 static void
1143 dispatcher_request_handles_cb (TpConnection *connection,
1144    const GArray *handles, const GError *error, gpointer user_data,
1145    GObject *object)
1146 {
1147   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1148
1149   if (error != NULL)
1150     {
1151       EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
1152       EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1153       ConnectionData *cd;
1154
1155       cd = g_hash_table_lookup (priv->connections, request_data->connection);
1156
1157       if (request_data->cb)
1158         request_data->cb (NULL, error, request_data->user_data);
1159
1160       cd->outstanding_requests = g_list_remove (cd->outstanding_requests,
1161         request_data);
1162
1163       free_dispatcher_request_data (request_data);
1164
1165       dispatcher_flush_outstanding_operations (dispatcher, cd);
1166       return;
1167     }
1168
1169   request_data->handle = g_array_index (handles, guint, 0);
1170   dispatcher_request_channel (request_data);
1171 }
1172
1173 void
1174 empathy_dispatcher_join_muc (McAccount *account, const gchar *roomname,
1175   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1176 {
1177   EmpathyDispatcher *dispatcher;
1178   EmpathyDispatcherPriv *priv;
1179   DispatcherRequestData *request_data;
1180   TpConnection *connection;
1181   ConnectionData *connection_data;
1182   const gchar *names[] = { roomname, NULL };
1183
1184   dispatcher = empathy_dispatcher_dup_singleton();
1185   priv = GET_PRIV (dispatcher);
1186
1187   connection = g_hash_table_lookup (priv->accounts, account);
1188   connection_data = g_hash_table_lookup (priv->connections, connection);
1189
1190
1191   /* Don't know the room handle yet */
1192   request_data  = new_dispatcher_request_data (dispatcher, connection,
1193     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_ROOM, 0, NULL,
1194     NULL, callback, user_data);
1195
1196   connection_data->outstanding_requests = g_list_prepend
1197     (connection_data->outstanding_requests, request_data);
1198
1199   tp_cli_connection_call_request_handles (connection, -1,
1200     TP_HANDLE_TYPE_ROOM, names,
1201     dispatcher_request_handles_cb, request_data, NULL,
1202     G_OBJECT (dispatcher));
1203
1204   g_object_unref (dispatcher);
1205 }
1206
1207 static void
1208 dispatcher_create_channel_cb (TpConnection *connect,
1209   const gchar *object_path, GHashTable *properties, const GError *error,
1210   gpointer user_data, GObject *weak_object)
1211 {
1212   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1213   DispatcherRequestData *request_data = (DispatcherRequestData*) user_data;
1214
1215   dispatcher_connection_new_requested_channel (dispatcher,
1216     request_data, object_path, properties, error);
1217 }
1218
1219
1220 static void
1221 dispatcher_create_channel_with_contact_cb (EmpathyContact *contact,
1222   const GError *error, gpointer user_data, GObject *object)
1223 {
1224   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1225   GValue *target_handle;
1226
1227   g_assert (request_data->request);
1228
1229   if (error != NULL)
1230     {
1231       dispatcher_request_failed (request_data->dispatcher,
1232         request_data, error);
1233       return;
1234     }
1235
1236   request_data->handle = empathy_contact_get_handle (contact);
1237
1238   target_handle = tp_g_value_slice_new (G_TYPE_UINT);
1239   g_value_set_uint (target_handle, request_data->handle);
1240   g_hash_table_insert (request_data->request,
1241     TP_IFACE_CHANNEL ".TargetHandle", target_handle);
1242
1243   tp_cli_connection_interface_requests_call_create_channel (
1244     request_data->connection, -1,
1245     request_data->request, dispatcher_create_channel_cb, request_data, NULL,
1246     G_OBJECT (request_data->dispatcher));
1247 }
1248
1249 void
1250 empathy_dispatcher_send_file_to_contact (EmpathyContact *contact,
1251   const gchar *filename, guint64 size, guint64 date,
1252   const gchar *content_type, EmpathyDispatcherRequestCb *callback,
1253   gpointer user_data)
1254 {
1255   EmpathyDispatcher *dispatcher = empathy_dispatcher_dup_singleton();
1256   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1257   McAccount *account = empathy_contact_get_account (contact);
1258   TpConnection *connection = g_hash_table_lookup (priv->accounts, account);
1259   ConnectionData *connection_data =
1260     g_hash_table_lookup (priv->connections, connection);
1261   DispatcherRequestData *request_data;
1262   GValue *value;
1263   GHashTable *request = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
1264       (GDestroyNotify) tp_g_value_slice_free);
1265
1266   /* org.freedesktop.Telepathy.Channel.ChannelType */
1267   value = tp_g_value_slice_new (G_TYPE_STRING);
1268   g_value_set_string (value, EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
1269   g_hash_table_insert (request, TP_IFACE_CHANNEL ".ChannelType", value);
1270
1271   /* org.freedesktop.Telepathy.Channel.TargetHandleType */
1272   value = tp_g_value_slice_new (G_TYPE_UINT);
1273   g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
1274   g_hash_table_insert (request, TP_IFACE_CHANNEL ".TargetHandleType", value);
1275
1276   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
1277   value = tp_g_value_slice_new (G_TYPE_STRING);
1278   g_value_set_string (value, content_type);
1279   g_hash_table_insert (request,
1280     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
1281
1282   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
1283   value = tp_g_value_slice_new (G_TYPE_STRING);
1284   g_value_set_string (value, filename);
1285   g_hash_table_insert (request,
1286     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
1287
1288   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
1289   value = tp_g_value_slice_new (G_TYPE_UINT64);
1290   g_value_set_uint64 (value, size);
1291   g_hash_table_insert (request,
1292     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
1293
1294   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
1295   value = tp_g_value_slice_new (G_TYPE_UINT64);
1296   g_value_set_uint64 (value, date);
1297   g_hash_table_insert (request,
1298     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
1299
1300
1301   /* The contact handle might not be known yet */
1302   request_data  = new_dispatcher_request_data (dispatcher, connection,
1303     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER, TP_HANDLE_TYPE_CONTACT, 0, request,
1304     contact, callback, user_data);
1305   connection_data->outstanding_requests = g_list_prepend
1306     (connection_data->outstanding_requests, request_data);
1307
1308   empathy_contact_call_when_ready (contact,
1309     EMPATHY_CONTACT_READY_HANDLE, dispatcher_create_channel_with_contact_cb,
1310     request_data, NULL, G_OBJECT (dispatcher));
1311
1312   g_object_unref (dispatcher);
1313 }