]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
Let a EmpathyChatroomManager observe the dispatcher
[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   EmpathyChatroomManager *chatroom_mgr;
61 } EmpathyDispatcherPriv;
62
63 G_DEFINE_TYPE (EmpathyDispatcher, empathy_dispatcher, G_TYPE_OBJECT);
64
65 enum {
66   OBSERVE,
67   APPROVE,
68   DISPATCH,
69   LAST_SIGNAL
70 };
71
72 static guint signals[LAST_SIGNAL];
73 static EmpathyDispatcher *dispatcher = NULL;
74
75 typedef struct {
76   EmpathyDispatcherTube  public;
77   EmpathyContactFactory *factory;
78   gchar                 *bus_name;
79   gchar                 *object_path;
80   guint                  ref_count;
81   gboolean               handled;
82 } DispatcherTube;
83
84 typedef struct {
85   EmpathyDispatcher *dispatcher;
86   EmpathyDispatchOperation *operation;
87   TpConnection *connection;
88   gchar *channel_type;
89   guint handle_type;
90   guint handle;
91   EmpathyContact *contact;
92   /* Properties to pass to the channel when requesting it */
93   GHashTable *request;
94   EmpathyDispatcherRequestCb *cb;
95   gpointer user_data;
96   gpointer *request_data;
97 } DispatcherRequestData;
98
99 typedef struct {
100   TpChannel *channel;
101   /* Channel type specific wrapper object */
102   GObject *channel_wrapper;
103 } DispatchData;
104
105 typedef struct {
106   McAccount *account;
107   /* ObjectPath => DispatchData.. */
108   GHashTable *dispatched_channels;
109   /* ObjectPath -> EmpathyDispatchOperations */
110   GHashTable *dispatching_channels;
111   /* ObjectPath -> EmpathyDispatchOperations */
112   GHashTable *outstanding_channels;
113   /* List of DispatcherRequestData */
114   GList *outstanding_requests;
115 } ConnectionData;
116
117 static DispatchData *
118 new_dispatch_data (TpChannel *channel, GObject *channel_wrapper)
119 {
120   DispatchData *d = g_slice_new0 (DispatchData);
121   d->channel = channel;
122   d->channel_wrapper = channel_wrapper;
123
124   return d;
125 }
126
127 static void
128 free_dispatch_data (DispatchData *data)
129 {
130   g_object_unref (data->channel);
131   g_object_unref (data->channel_wrapper);
132
133   g_slice_free (DispatchData, data);
134 }
135
136
137 static DispatcherRequestData *
138 new_dispatcher_request_data (EmpathyDispatcher *dispatcher,
139   TpConnection *connection, const gchar *channel_type, guint handle_type,
140   guint handle, GHashTable *request,
141   EmpathyContact *contact, EmpathyDispatcherRequestCb *cb, gpointer user_data)
142 {
143   DispatcherRequestData *result = g_slice_new0 (DispatcherRequestData);
144
145   result->dispatcher = dispatcher;
146   result->connection = connection;
147
148   result->channel_type = g_strdup (channel_type);
149   result->handle_type = handle_type;
150   result->handle = handle;
151   result->request = request;
152
153   if (contact != NULL)
154     result->contact = g_object_ref (contact);
155
156   result->cb = cb;
157   result->user_data = user_data;
158
159   return result;
160 }
161
162 static void
163 free_dispatcher_request_data (DispatcherRequestData *r)
164 {
165   g_free (r->channel_type);
166
167   if (r->contact != NULL)
168     g_object_unref (r->contact);
169
170   if (r->request != NULL)
171     g_hash_table_unref (r->request);
172
173   g_slice_free (DispatcherRequestData, r);
174 }
175
176 static ConnectionData *
177 new_connection_data (McAccount *account)
178 {
179   ConnectionData *cd = g_slice_new0 (ConnectionData);
180   cd->account = g_object_ref (account);
181
182   cd->dispatched_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
183     g_free, (GDestroyNotify) free_dispatch_data);
184
185   cd->dispatching_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
186     g_free, g_object_unref);
187
188   cd->outstanding_channels = g_hash_table_new_full (g_str_hash, g_str_equal,
189     g_free, NULL);
190
191   return cd;
192 }
193
194 static void
195 free_connection_data (ConnectionData *cd)
196 {
197   GList *l;
198   g_object_unref (cd->account);
199   g_hash_table_destroy (cd->dispatched_channels);
200   g_hash_table_destroy (cd->dispatching_channels);
201
202   for (l = cd->outstanding_requests ; l != NULL; l = g_list_delete_link (l,l))
203     {
204       free_dispatcher_request_data (l->data);
205     }
206 }
207
208 #if 0
209 GType
210 empathy_dispatcher_tube_get_type (void)
211 {
212         static GType type_id = 0;
213
214         if (!type_id) {
215                 type_id = g_boxed_type_register_static ("EmpathyDispatcherTube",
216                                                         (GBoxedCopyFunc) empathy_dispatcher_tube_ref,
217                                                         (GBoxedFreeFunc) empathy_dispatcher_tube_unref);
218         }
219
220         return type_id;
221 }
222
223 EmpathyDispatcherTube *
224 empathy_dispatcher_tube_ref (EmpathyDispatcherTube *data)
225 {
226         DispatcherTube *tube = (DispatcherTube*) data;
227
228         g_return_val_if_fail (tube != NULL, NULL);
229
230         tube->ref_count++;
231
232         return data;
233 }
234
235 void
236 empathy_dispatcher_tube_unref (EmpathyDispatcherTube *data)
237 {
238         DispatcherTube *tube = (DispatcherTube*) data;
239
240         g_return_if_fail (tube != NULL);
241
242         if (--tube->ref_count == 0) {
243                 if (!tube->handled) {
244                         DEBUG ("Tube can't be handled, closing");
245                         tp_cli_channel_type_tubes_call_close_tube (tube->public.channel, -1,
246                                                                    tube->public.id,
247                                                                    NULL, NULL, NULL,
248                                                                    NULL);
249                 }
250
251                 g_free (tube->bus_name);
252                 g_free (tube->object_path);
253                 g_object_unref (tube->factory);
254                 g_object_unref (tube->public.channel);
255                 g_object_unref (tube->public.initiator);
256                 g_slice_free (DispatcherTube, tube);
257         }
258 }
259
260 static void
261 dispatcher_tubes_handle_tube_cb (TpProxy      *channel,
262                                  const GError *error,
263                                  gpointer      user_data,
264                                  GObject      *dispatcher)
265 {
266         DispatcherTube *tube = user_data;
267
268         if (error) {
269                 DEBUG ("Error: %s", error->message);
270         } else {
271                 tube->handled = TRUE;
272         }
273 }
274
275
276 void
277 empathy_dispatcher_tube_process (EmpathyDispatcher     *dispatcher,
278                                  EmpathyDispatcherTube *etube)
279 {
280         DispatcherTube *tube = (DispatcherTube*) etube;
281
282         if (tube->public.activatable) {
283                 TpProxy *connection;
284                 TpProxy *thandler;
285                 gchar   *object_path;
286                 guint    handle_type;
287                 guint    handle;
288
289                 /* Create the proxy for the tube handler */
290                 thandler = g_object_new (TP_TYPE_PROXY,
291                                          "dbus-connection", tp_get_bus (),
292                                          "bus-name", tube->bus_name,
293                                          "object-path", tube->object_path,
294                                          NULL);
295                 tp_proxy_add_interface_by_id (thandler, EMP_IFACE_QUARK_TUBE_HANDLER);
296
297                 /* Give the tube to the handler */
298                 g_object_get (tube->public.channel,
299                               "connection", &connection,
300                               "object-path", &object_path,
301                               "handle_type", &handle_type,
302                               "handle", &handle,
303                               NULL);
304
305                 DEBUG ("Dispatching tube");
306                 emp_cli_tube_handler_call_handle_tube (thandler, -1,
307                                                        connection->bus_name,
308                                                        connection->object_path,
309                                                        object_path, handle_type,
310                                                        handle, tube->public.id,
311                                                        dispatcher_tubes_handle_tube_cb,
312                                                        empathy_dispatcher_tube_ref (etube),
313                                                        (GDestroyNotify) empathy_dispatcher_tube_unref,
314                                                        G_OBJECT (dispatcher));
315
316                 g_object_unref (thandler);
317                 g_object_unref (connection);
318                 g_free (object_path);
319         }
320 }
321
322 static void
323 dispatcher_tubes_new_tube_cb (TpChannel   *channel,
324                               guint        id,
325                               guint        initiator,
326                               guint        type,
327                               const gchar *service,
328                               GHashTable  *parameters,
329                               guint        state,
330                               gpointer     user_data,
331                               GObject     *dispatcher)
332 {
333         static TpDBusDaemon   *daemon = NULL;
334         DispatcherTube        *tube;
335         McAccount             *account;
336         guint                  number;
337         gchar                **names;
338         gboolean               running = FALSE;
339         GError                *error = NULL;
340
341         /* Increase tube count */
342         number = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (channel), "tube-count"));
343         g_object_set_data (G_OBJECT (channel), "tube-count", GUINT_TO_POINTER (++number));
344         DEBUG ("Increased tube count for channel %p: %d", channel, number);
345
346         /* We dispatch only local pending tubes */
347         if (state != TP_TUBE_STATE_LOCAL_PENDING) {
348                 return;
349         }
350
351         if (!daemon) {
352                 daemon = tp_dbus_daemon_new (tp_get_bus ());
353         }
354
355         account = empathy_channel_get_account (channel);
356         tube = g_slice_new (DispatcherTube);
357         tube->ref_count = 1;
358         tube->handled = FALSE;
359         tube->factory = empathy_contact_factory_dup_singleton ();
360         tube->bus_name = empathy_tube_handler_build_bus_name (type, service);
361         tube->object_path = empathy_tube_handler_build_object_path (type, service);
362         tube->public.activatable = FALSE;
363         tube->public.id = id;
364         tube->public.channel = g_object_ref (channel);
365         tube->public.initiator = empathy_contact_factory_get_from_handle (tube->factory,
366                                                                           account,
367                                                                           initiator);
368         g_object_unref (account);
369
370         DEBUG ("Looking for tube handler: %s", tube->bus_name);
371         /* Check if that bus-name has an owner, if it has one that means the
372          * app is already running and we can directly give the channel. */
373         tp_cli_dbus_daemon_run_name_has_owner (daemon, -1, tube->bus_name,
374                                                &running, NULL, NULL);
375         if (running) {
376                 DEBUG ("Tube handler running");
377                 tube->public.activatable = TRUE;
378                 empathy_dispatcher_tube_process (EMPATHY_DISPATCHER (dispatcher),
379                                                  (EmpathyDispatcherTube*) tube);
380                 empathy_dispatcher_tube_unref ((EmpathyDispatcherTube*) tube);
381                 return;
382         }
383
384         DEBUG ("Tube handler is not running. Try to activate it");
385         /* Check if that bus-name is activatable, if not that means the
386          * application needed to handle this tube isn't installed. */
387         if (!tp_cli_dbus_daemon_run_list_activatable_names (daemon, -1,
388                                                             &names, &error,
389                                                             NULL)) {
390                 DEBUG ("Error listing activatable names: %s", error->message);
391                 g_clear_error (&error);
392         } else {
393                 gchar **name;
394
395                 for (name = names; *name; name++) {
396                         if (!tp_strdiff (*name, tube->bus_name)) {
397                                 DEBUG ("Found tube handler");
398                                 tube->public.activatable = TRUE;
399                                 break;
400                         }
401                 }
402                 g_strfreev (names);
403         }
404
405         if (!tube->public.activatable)
406                 DEBUG ("Didn't find tube handler");
407
408         g_signal_emit (dispatcher, signals[FILTER_TUBE], 0, tube);
409         empathy_dispatcher_tube_unref ((EmpathyDispatcherTube*) tube);
410 }
411
412 static void
413 dispatcher_tubes_list_tubes_cb (TpChannel       *channel,
414                                 const GPtrArray *tubes,
415                                 const GError    *error,
416                                 gpointer         user_data,
417                                 GObject         *dispatcher)
418 {
419         guint i;
420
421         if (error) {
422                 DEBUG ("Error: %s", error->message);
423                 return;
424         }
425
426         for (i = 0; i < tubes->len; i++) {
427                 GValueArray *values;
428
429                 values = g_ptr_array_index (tubes, i);
430                 dispatcher_tubes_new_tube_cb (channel,
431                                               g_value_get_uint (g_value_array_get_nth (values, 0)),
432                                               g_value_get_uint (g_value_array_get_nth (values, 1)),
433                                               g_value_get_uint (g_value_array_get_nth (values, 2)),
434                                               g_value_get_string (g_value_array_get_nth (values, 3)),
435                                               g_value_get_boxed (g_value_array_get_nth (values, 4)),
436                                               g_value_get_uint (g_value_array_get_nth (values, 5)),
437                                               user_data, dispatcher);
438         }
439 }
440
441 static void
442 dispatcher_tubes_channel_invalidated_cb (TpProxy           *proxy,
443                                          guint              domain,
444                                          gint               code,
445                                          gchar             *message,
446                                          EmpathyDispatcher *dispatcher)
447 {
448         EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
449
450         DEBUG ("%s", message);
451
452         priv->tubes = g_slist_remove (priv->tubes, proxy);
453         g_object_unref (proxy);
454 }
455
456 static void
457 dispatcher_tubes_tube_closed_cb (TpChannel *channel,
458                                  guint      id,
459                                  gpointer   user_data,
460                                  GObject   *dispatcher)
461 {
462         guint number;
463
464         number = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (channel), "tube-count"));
465         if (number == 1) {
466                 DEBUG ("No more tube, closing channel");
467                 tp_cli_channel_call_close (channel, -1, NULL, NULL, NULL, NULL);
468         }
469         else if (number > 1) {
470                 DEBUG ("Decrease tube count: %d", number);
471                 g_object_set_data (G_OBJECT (channel), "tube-count", GUINT_TO_POINTER (--number));
472         }
473 }
474
475
476 static void
477 dispatcher_tubes_handle_channel (EmpathyDispatcher *dispatcher,
478                                  TpChannel         *channel)
479 {
480         EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
481
482         DEBUG ("Called");
483
484         priv->tubes = g_slist_prepend (priv->tubes, g_object_ref (channel));
485         g_signal_connect (channel, "invalidated",
486                           G_CALLBACK (dispatcher_tubes_channel_invalidated_cb),
487                           dispatcher);
488
489         tp_cli_channel_type_tubes_connect_to_tube_closed (channel,
490                                                           dispatcher_tubes_tube_closed_cb,
491                                                           NULL, NULL,
492                                                           G_OBJECT (dispatcher), NULL);
493         tp_cli_channel_type_tubes_connect_to_new_tube (channel,
494                                                        dispatcher_tubes_new_tube_cb,
495                                                        NULL, NULL,
496                                                        G_OBJECT (dispatcher), NULL);
497         tp_cli_channel_type_tubes_call_list_tubes (channel, -1,
498                                                    dispatcher_tubes_list_tubes_cb,
499                                                    NULL, NULL,
500                                                    G_OBJECT (dispatcher));
501 }
502
503 #endif
504
505 static void
506 dispatcher_connection_invalidated_cb (TpConnection  *connection,
507   guint          domain, gint           code, gchar         *message,
508   EmpathyDispatcher *dispatcher)
509 {
510   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
511   ConnectionData *cd;
512
513   DEBUG ("Error: %s", message);
514   cd = g_hash_table_lookup (priv->connections, connection);
515
516   g_hash_table_remove (priv->accounts, cd->account);
517   g_hash_table_remove (priv->connections, connection);
518 }
519
520 #if 0
521
522 typedef struct
523 {
524   EmpathyDispatcher *self;
525   EmpathyChatroom *chatroom;
526 } dispatcher_connection_invalidated_cb_ctx;
527
528 static dispatcher_connection_invalidated_cb_ctx *
529 dispatcher_connection_invalidated_cb_ctx_new (EmpathyDispatcher *dispatcher,
530                                               EmpathyChatroom *chatroom)
531 {
532   dispatcher_connection_invalidated_cb_ctx *ctx;
533
534   ctx = g_slice_new (dispatcher_connection_invalidated_cb_ctx);
535
536   ctx->self = g_object_ref (dispatcher);
537   ctx->chatroom = g_object_ref (chatroom);
538
539   return ctx;
540 }
541
542 static void
543 dispatcher_connection_invalidated_cb_ctx_free (
544     dispatcher_connection_invalidated_cb_ctx *ctx)
545 {
546   g_object_unref (ctx->self);
547   g_object_unref (ctx->chatroom);
548
549   g_slice_free (dispatcher_connection_invalidated_cb_ctx, ctx);
550 }
551
552 static void dispatcher_chatroom_invalidated_cb (
553     TpProxy *channel,
554     guint domain,
555     gint code,
556     gchar *message,
557     dispatcher_connection_invalidated_cb_ctx *ctx)
558 {
559   EmpathyDispatcherPriv *priv = GET_PRIV (ctx->self);
560   gboolean favorite;
561
562   g_object_get (ctx->chatroom, "favorite", &favorite, NULL);
563
564   if (favorite)
565     {
566       /* Chatroom is in favorites so don't remove it from the manager */
567       g_object_set (ctx->chatroom, "tp-channel", NULL, NULL);
568     }
569   else
570     {
571       empathy_chatroom_manager_remove (priv->chatroom_mgr, ctx->chatroom);
572     }
573 }
574
575 #endif
576
577
578 /********************* Sanity from here at some point *********/
579 static gboolean
580 dispatcher_operation_can_start (EmpathyDispatcher *self,
581   EmpathyDispatchOperation *operation, ConnectionData *cd)
582 {
583   GList *l;
584   const gchar *channel_type =
585     empathy_dispatch_operation_get_channel_type (operation);
586
587   for (l = cd->outstanding_requests; l != NULL; l = g_list_next (l))
588     {
589       DispatcherRequestData *d = (DispatcherRequestData *) l->data;
590
591       if (d->operation == NULL && !tp_strdiff (d->channel_type, channel_type))
592         {
593           return FALSE;
594         }
595     }
596
597   return TRUE;
598 }
599
600 static void
601 dispatch_operation_flush_requests (EmpathyDispatcher *dispatcher,
602   EmpathyDispatchOperation *operation, GError *error, ConnectionData *cd)
603 {
604   GList *l;
605
606   l = cd->outstanding_requests;
607   while (l != NULL)
608     {
609       DispatcherRequestData *d = (DispatcherRequestData *) l->data;
610       GList *lt = l;
611
612       l = g_list_next (l);
613
614       if (d->operation == operation)
615         {
616           if (d->cb != NULL)
617             {
618               if (error != NULL)
619                 d->cb (NULL, error, d->user_data);
620               else
621                 d->cb (operation, NULL, d->user_data);
622             }
623
624           cd->outstanding_requests = g_list_delete_link
625             (cd->outstanding_requests, lt);
626
627           free_dispatcher_request_data (d);
628         }
629     }
630 }
631
632 static void
633 dispatcher_channel_invalidated_cb (TpProxy *proxy, guint domain, gint code,
634   gchar *message, EmpathyDispatcher *dispatcher)
635 {
636   /* Channel went away... */
637   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
638   TpConnection *connection;
639   EmpathyDispatchOperation *operation;
640   ConnectionData *cd;
641   const gchar *object_path;
642
643   g_object_get (G_OBJECT (proxy), "connection", &connection, NULL);
644
645   cd = g_hash_table_lookup (priv->connections, connection);
646   /* Connection itself invalidated? */
647   if (cd == NULL)
648     return;
649
650   object_path = tp_proxy_get_object_path (proxy);
651
652   DEBUG ("Channel %s invalidated", object_path);
653
654   g_hash_table_remove (cd->dispatched_channels, object_path);
655   g_hash_table_remove (cd->dispatching_channels, object_path);
656
657   operation = g_hash_table_lookup (cd->outstanding_channels, object_path);
658   if (operation != NULL)
659     {
660       GError error = { domain, code, message };
661       dispatch_operation_flush_requests (dispatcher, operation, &error, cd);
662       g_hash_table_remove (cd->outstanding_channels, object_path);
663       g_object_unref (operation);
664     }
665 }
666
667 static void
668 dispatch_operation_approved_cb (EmpathyDispatchOperation *operation,
669   EmpathyDispatcher *dispatcher)
670 {
671   g_assert (empathy_dispatch_operation_is_incoming (operation));
672   DEBUG ("Send of for dispatching: %s",
673     empathy_dispatch_operation_get_object_path (operation));
674   g_signal_emit (dispatcher, signals[DISPATCH], 0, operation);
675 }
676
677 static void
678 dispatch_operation_claimed_cb (EmpathyDispatchOperation *operation,
679   EmpathyDispatcher *dispatcher)
680 {
681   /* Our job is done, remove the dispatch operation and mark the channel as
682    * dispatched */
683   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
684   TpConnection *connection;
685   ConnectionData *cd;
686   const gchar *object_path;
687
688   connection = empathy_dispatch_operation_get_tp_connection (operation);
689   cd = g_hash_table_lookup (priv->connections, connection);
690   g_assert (cd != NULL);
691   g_object_unref (G_OBJECT (connection));
692
693   object_path = empathy_dispatch_operation_get_object_path (operation);
694
695   if (g_hash_table_lookup (cd->dispatched_channels, object_path) == NULL)
696     {
697       DispatchData *d;
698       d = new_dispatch_data (
699         empathy_dispatch_operation_get_channel (operation),
700         empathy_dispatch_operation_get_channel_wrapper (operation));
701       g_hash_table_insert (cd->dispatched_channels,
702         g_strdup (object_path), d);
703     }
704   g_hash_table_remove (cd->dispatching_channels, object_path);
705
706   DEBUG ("Channel claimed: %s", object_path);
707 }
708
709 static void
710 dispatch_operation_ready_cb (EmpathyDispatchOperation *operation,
711   EmpathyDispatcher *dispatcher)
712 {
713   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
714   TpConnection *connection;
715   ConnectionData *cd;
716   EmpathyDispatchOperationState status;
717
718   g_signal_connect (operation, "approved",
719     G_CALLBACK (dispatch_operation_approved_cb), dispatcher);
720
721   g_signal_connect (operation, "claimed",
722     G_CALLBACK (dispatch_operation_claimed_cb), dispatcher);
723
724   /* Signal the observers */
725   DEBUG ("Send to observers: %s",
726     empathy_dispatch_operation_get_object_path (operation));
727   g_signal_emit (dispatcher, signals[OBSERVE], 0, operation);
728
729   empathy_dispatch_operation_start (operation);
730
731   /* Signal potential requestors */
732   connection =  empathy_dispatch_operation_get_tp_connection (operation);
733   cd = g_hash_table_lookup (priv->connections, connection);
734   g_assert (cd != NULL);
735   g_object_unref (G_OBJECT (connection));
736
737   g_object_ref (operation);
738
739   dispatch_operation_flush_requests (dispatcher, operation, NULL, cd);
740   status = empathy_dispatch_operation_get_status (operation);
741   g_object_unref (operation);
742
743   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_CLAIMED)
744     return;
745
746   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
747     {
748       DEBUG ("Send to approvers: %s",
749         empathy_dispatch_operation_get_object_path (operation));
750       g_signal_emit (dispatcher, signals[APPROVE], 0, operation);
751     }
752   else
753     {
754       g_assert (status == EMPATHY_DISPATCHER_OPERATION_STATE_DISPATCHING);
755       DEBUG ("Send of for dispatching: %s",
756         empathy_dispatch_operation_get_object_path (operation));
757       g_signal_emit (dispatcher, signals[DISPATCH], 0, operation);
758     }
759
760 }
761
762 static void
763 dispatcher_start_dispatching (EmpathyDispatcher *self,
764   EmpathyDispatchOperation *operation, ConnectionData *cd)
765 {
766   const gchar *object_path =
767     empathy_dispatch_operation_get_object_path (operation);
768
769   DEBUG ("Dispatching process started for %s", object_path);
770
771   if (g_hash_table_lookup (cd->dispatching_channels, object_path) == NULL)
772     {
773       g_assert (g_hash_table_lookup (cd->outstanding_channels,
774         object_path) == NULL);
775
776       g_hash_table_insert (cd->dispatching_channels,
777         g_strdup (object_path), operation);
778
779       switch (empathy_dispatch_operation_get_status (operation))
780         {
781           case EMPATHY_DISPATCHER_OPERATION_STATE_PREPARING:
782             g_signal_connect (operation, "ready",
783               G_CALLBACK (dispatch_operation_ready_cb), dispatcher);
784             break;
785           case EMPATHY_DISPATCHER_OPERATION_STATE_PENDING:
786             dispatch_operation_ready_cb (operation, dispatcher);
787             break;
788           default:
789             g_assert_not_reached();
790         }
791
792     }
793   else if (empathy_dispatch_operation_get_status (operation) >=
794       EMPATHY_DISPATCHER_OPERATION_STATE_PENDING)
795     {
796       /* Already dispatching and the operation is pending, thus the observers
797        * have seen it (if applicable), so we can flush the request right away.
798        */
799       dispatch_operation_flush_requests (self, operation, NULL, cd);
800     }
801 }
802
803
804 static void
805 dispatcher_flush_outstanding_operations (EmpathyDispatcher *self,
806   ConnectionData *cd)
807 {
808   GHashTableIter iter;
809   gpointer value;
810
811   g_hash_table_iter_init (&iter, cd->outstanding_channels);
812   while (g_hash_table_iter_next (&iter, NULL, &value))
813     {
814       EmpathyDispatchOperation *operation = EMPATHY_DISPATCH_OPERATION (value);
815
816       if (dispatcher_operation_can_start (self, operation, cd))
817         {
818           dispatcher_start_dispatching (dispatcher, operation, cd);
819           g_hash_table_iter_remove (&iter);
820         }
821     }
822 }
823
824
825 static void
826 dispatcher_connection_new_channel (EmpathyDispatcher *dispatcher,
827   TpConnection *connection,
828   const gchar  *object_path, const gchar  *channel_type,
829   guint handle_type, guint handle, GHashTable *properties,
830   gboolean incoming)
831 {
832   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
833   TpChannel         *channel;
834   ConnectionData *cd;
835   EmpathyDispatchOperation *operation;
836   EmpathyContact *contact = NULL;
837
838   cd = g_hash_table_lookup (priv->connections, connection);
839
840   /* Don't bother with channels we have already dispatched or are dispatching
841    * currently. This can happen when NewChannel(s) is fired after
842    * RequestChannel/CreateChannel/EnsureChannel */
843   if (g_hash_table_lookup (cd->dispatched_channels, object_path) != NULL)
844     return;
845
846   if (g_hash_table_lookup (cd->dispatching_channels, object_path) != NULL)
847     return;
848
849   /* Should never occur, but just in case a CM fires spurious NewChannel(s) 
850    * signals */
851   if (g_hash_table_lookup (cd->outstanding_channels, object_path) != NULL)
852     return;
853
854   DEBUG ("New channel of type %s on %s",
855     channel_type, object_path);
856
857   if (properties == NULL)
858     channel = tp_channel_new (connection, object_path, channel_type,
859       handle_type, handle, NULL);
860   else
861     channel = tp_channel_new_from_properties (connection, object_path,
862       properties, NULL);
863
864   g_signal_connect (channel, "invalidated",
865     G_CALLBACK (dispatcher_channel_invalidated_cb),
866     dispatcher);
867
868   if (handle_type == TP_CONN_HANDLE_TYPE_CONTACT)
869     {
870       EmpathyContactFactory *factory = empathy_contact_factory_new ();
871       contact = empathy_contact_factory_get_from_handle (factory,
872         cd->account, handle);
873       g_object_unref (factory);
874     }
875
876   operation = empathy_dispatch_operation_new (connection, channel, contact,
877     incoming);
878
879   g_object_unref (channel);
880
881   if (incoming)
882     {
883       /* Request could either be by us or by a remote party. If there are no
884        * outstanding requests for this channel type we can assume it's remote.
885        * Otherwise we wait untill they are all satisfied */
886       if (dispatcher_operation_can_start (dispatcher, operation, cd))
887         dispatcher_start_dispatching (dispatcher, operation, cd);
888       else
889         g_hash_table_insert (cd->outstanding_channels,
890           g_strdup (object_path), operation);
891     }
892   else
893     {
894       dispatcher_start_dispatching (dispatcher, operation, cd);
895     }
896 }
897
898 static void
899 dispatcher_connection_new_channel_cb (TpConnection *connection,
900   const gchar  *object_path, const gchar  *channel_type,
901   guint         handle_type, guint         handle,
902   gboolean      suppress_handler, gpointer      user_data,
903   GObject      *object)
904 {
905   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
906
907   /* Empathy heavily abuses surpress handler (don't try this at home), if
908    * surpress handler is true then it is an outgoing channel, which is
909    * requested either by us or some other party (like the megaphone applet).
910    * Otherwise it's an incoming channel */
911   dispatcher_connection_new_channel (dispatcher, connection,
912     object_path, channel_type, handle_type, handle, NULL, !suppress_handler);
913 }
914
915 static void
916 dispatcher_connection_new_channel_with_properties (
917   EmpathyDispatcher *dispatcher, TpConnection *connection,
918   const gchar *object_path, GHashTable *properties)
919 {
920   const gchar *channel_type;
921   guint handle_type;
922   guint handle;
923   gboolean requested;
924   gboolean valid;
925
926
927   channel_type = tp_asv_get_string (properties,
928     TP_IFACE_CHANNEL ".ChannelType");
929   if (channel_type == NULL)
930     {
931       g_message ("%s had an invalid ChannelType property", object_path);
932       return;
933     }
934
935   handle_type = tp_asv_get_uint32 (properties,
936     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
937   if (!valid)
938     {
939       g_message ("%s had an invalid TargetHandleType property", object_path);
940       return;
941     }
942
943   handle = tp_asv_get_uint32 (properties,
944     TP_IFACE_CHANNEL ".TargetHandle", &valid);
945   if (!valid)
946     {
947       g_message ("%s had an invalid TargetHandle property", object_path);
948       return;
949     }
950
951   /* We assume there is no channel dispather, so we're the only one dispatching
952    * it. Which means that a requested channel it is outgoing one */
953   requested = tp_asv_get_boolean (properties,
954     TP_IFACE_CHANNEL ".Requested", &valid);
955   if (!valid)
956     {
957       g_message ("%s had an invalid Requested property", object_path);
958       return;
959     }
960
961   dispatcher_connection_new_channel (dispatcher, connection,
962     object_path, channel_type, handle_type, handle, properties, !requested);
963 }
964
965
966 static void
967 dispatcher_connection_new_channels_cb (
968   TpConnection *connection, const GPtrArray *channels, gpointer user_data,
969   GObject *object)
970 {
971   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
972   int i;
973
974   for (i = 0; i < channels->len ; i++)
975     {
976       GValueArray *arr = g_ptr_array_index (channels, i);
977       const gchar *object_path;
978       GHashTable *properties;
979
980       object_path = g_value_get_boxed (g_value_array_get_nth (arr, 0));
981       properties = g_value_get_boxed (g_value_array_get_nth (arr, 1));
982
983       dispatcher_connection_new_channel_with_properties (dispatcher,
984         connection, object_path, properties);
985     }
986 }
987
988 #if 0  /* old dispatching  */
989   channel = tp_channel_new (connection, object_path, channel_type,
990     handle_type, handle, NULL);
991   tp_channel_run_until_ready (channel, NULL, NULL);
992
993   if (!tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TUBES)) {
994     dispatcher_tubes_handle_channel (dispatcher, channel);
995   }
996
997   if (!tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TEXT) &&
998       handle_type == TP_HANDLE_TYPE_ROOM)
999     {
1000       /* Add the chatroom to the chatroom manager */
1001       EmpathyChatroom *chatroom;
1002       GArray *handles;
1003       gchar **room_ids;
1004       MissionControl *mc;
1005       McAccount *account;
1006       dispatcher_connection_invalidated_cb_ctx *ctx;
1007
1008       handles = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), 1);
1009       g_array_append_val (handles, handle);
1010
1011       tp_cli_connection_run_inspect_handles (connection, -1,
1012           TP_HANDLE_TYPE_ROOM, handles, &room_ids, NULL, NULL);
1013
1014       mc = empathy_mission_control_new ();
1015       account = mission_control_get_account_for_tpconnection (mc, connection,
1016           NULL);
1017
1018       chatroom = empathy_chatroom_manager_find (priv->chatroom_mgr, account,
1019           room_ids[0]);
1020       if (chatroom == NULL)
1021         {
1022           chatroom = empathy_chatroom_new (account);
1023           empathy_chatroom_set_name (chatroom, room_ids[0]);
1024           empathy_chatroom_set_room (chatroom, room_ids[0]);
1025           empathy_chatroom_manager_add (priv->chatroom_mgr, chatroom);
1026         }
1027       else
1028         {
1029           g_object_ref (chatroom);
1030         }
1031
1032       g_object_set (chatroom, "tp-channel", channel, NULL);
1033
1034       ctx = dispatcher_connection_invalidated_cb_ctx_new (dispatcher, chatroom);
1035
1036       g_signal_connect_data (channel, "invalidated",
1037           G_CALLBACK (dispatcher_chatroom_invalidated_cb), ctx,
1038           (GClosureNotify) dispatcher_connection_invalidated_cb_ctx_free, 0);
1039
1040       g_free (room_ids[0]);
1041       g_free (room_ids);
1042       g_array_free (handles, TRUE);
1043       g_object_unref (mc);
1044       g_object_unref (account);
1045       g_object_unref (chatroom);
1046     }
1047
1048         if (suppress_handler) {
1049                 g_signal_emit (dispatcher, signals[DISPATCH_CHANNEL], 0, channel);
1050         } else {
1051                 g_signal_emit (dispatcher, signals[FILTER_CHANNEL], 0, channel);
1052         }
1053
1054         g_object_unref (channel);
1055
1056 }
1057 #endif
1058
1059 static void
1060 dispatcher_connection_got_channels_property (TpProxy *proxy,
1061   const GValue *channels_prop, const GError *error, gpointer user_data,
1062   GObject *object)
1063 {
1064   GPtrArray *channels;
1065
1066   if (error) {
1067     DEBUG ("Error: %s", error->message);
1068     return;
1069   }
1070
1071   channels = g_value_get_boxed (channels_prop);
1072   dispatcher_connection_new_channels_cb (TP_CONNECTION (proxy),
1073     channels, NULL, object);
1074 }
1075
1076 static void
1077 dispatcher_connection_list_channels_cb (TpConnection    *connection,
1078                                         const GPtrArray *channels,
1079                                         const GError    *error,
1080                                         gpointer         user_data,
1081                                         GObject         *dispatcher)
1082 {
1083         int i;
1084
1085         if (error) {
1086                 DEBUG ("Error: %s", error->message);
1087                 return;
1088         }
1089
1090         for (i = 0; i < channels->len; i++) {
1091                 GValueArray *values;
1092
1093                 values = g_ptr_array_index (channels, i);
1094                 /* We don't have any extra info, so assume already existing channels are
1095                  * incoming... */
1096                 dispatcher_connection_new_channel (EMPATHY_DISPATCHER (dispatcher),
1097                         connection,
1098                         g_value_get_boxed (g_value_array_get_nth (values, 0)),
1099                         g_value_get_string (g_value_array_get_nth (values, 1)),
1100                         g_value_get_uint (g_value_array_get_nth (values, 2)),
1101                         g_value_get_uint (g_value_array_get_nth (values, 3)),
1102                         NULL, TRUE);
1103         }
1104 }
1105
1106 static void
1107 dispatcher_connection_advertise_capabilities_cb (TpConnection    *connection,
1108                                                  const GPtrArray *capabilities,
1109                                                  const GError    *error,
1110                                                  gpointer         user_data,
1111                                                  GObject         *dispatcher)
1112 {
1113         if (error) {
1114                 DEBUG ("Error: %s", error->message);
1115         }
1116 }
1117
1118 static void
1119 dispatcher_connection_ready_cb (TpConnection  *connection,
1120   const GError *error, gpointer       dispatcher)
1121 {
1122   GPtrArray   *capabilities;
1123   GType        cap_type;
1124   GValue       cap = {0, };
1125   const gchar *remove = NULL;
1126
1127   if (error)
1128     {
1129       dispatcher_connection_invalidated_cb (connection, error->domain,
1130         error->code, error->message, dispatcher);
1131       return;
1132     }
1133
1134   g_signal_connect (connection, "invalidated",
1135     G_CALLBACK (dispatcher_connection_invalidated_cb), dispatcher);
1136
1137
1138   if (tp_proxy_has_interface_by_id (TP_PROXY (connection),
1139       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
1140     {
1141       tp_cli_connection_interface_requests_connect_to_new_channels (connection,
1142         dispatcher_connection_new_channels_cb,
1143         NULL, NULL, G_OBJECT (dispatcher), NULL);
1144
1145       tp_cli_dbus_properties_call_get (connection, -1,
1146         TP_IFACE_CONNECTION_INTERFACE_REQUESTS, "Channels",
1147         dispatcher_connection_got_channels_property,
1148         NULL, NULL, dispatcher);
1149     }
1150   else
1151     {
1152       tp_cli_connection_connect_to_new_channel (connection,
1153         dispatcher_connection_new_channel_cb,
1154         NULL, NULL, G_OBJECT (dispatcher), NULL);
1155
1156       tp_cli_connection_call_list_channels (connection, -1,
1157         dispatcher_connection_list_channels_cb, NULL, NULL,
1158         G_OBJECT (dispatcher));
1159
1160     }
1161
1162   /* Advertise VoIP capabilities */
1163   capabilities = g_ptr_array_sized_new (1);
1164   cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
1165     G_TYPE_UINT, G_TYPE_INVALID);
1166   g_value_init (&cap, cap_type);
1167   g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
1168   dbus_g_type_struct_set (&cap,
1169         0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
1170         1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
1171            TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
1172            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
1173            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P, G_MAXUINT);
1174   g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
1175
1176   tp_cli_connection_interface_capabilities_call_advertise_capabilities (
1177     connection, -1, capabilities, &remove,
1178     dispatcher_connection_advertise_capabilities_cb,
1179     NULL, NULL, G_OBJECT (dispatcher));
1180 }
1181
1182 static void
1183 dispatcher_update_account (EmpathyDispatcher *dispatcher, McAccount *account)
1184 {
1185   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1186   TpConnection *connection;
1187
1188   connection = g_hash_table_lookup (priv->accounts, account);
1189   if  (connection != NULL)
1190     return;
1191
1192   connection = mission_control_get_tpconnection (priv->mc, account, NULL);
1193   if (connection == NULL)
1194     return;
1195
1196   g_hash_table_insert (priv->connections, g_object_ref (connection),
1197     new_connection_data (account));
1198
1199   g_hash_table_insert (priv->accounts, g_object_ref (account),
1200     g_object_ref (connection));
1201
1202   tp_connection_call_when_ready (connection, dispatcher_connection_ready_cb,
1203     dispatcher);
1204 }
1205
1206 static void
1207 dispatcher_account_connection_cb (EmpathyAccountManager *manager,
1208   McAccount *account, TpConnectionStatusReason reason,
1209   TpConnectionStatus status, TpConnectionStatus previous,
1210   EmpathyDispatcher *dispatcher)
1211 {
1212   dispatcher_update_account (dispatcher, account);
1213 }
1214
1215 static void
1216 dispatcher_finalize (GObject *object)
1217 {
1218   EmpathyDispatcherPriv *priv = GET_PRIV (object);
1219
1220   g_signal_handlers_disconnect_by_func (priv->account_manager,
1221       dispatcher_account_connection_cb, object);
1222
1223   g_object_unref (priv->account_manager);
1224   g_object_unref (priv->mc);
1225
1226   g_hash_table_destroy (priv->connections);
1227
1228   g_object_unref (priv->chatroom_mgr);
1229 }
1230
1231 static void
1232 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
1233 {
1234   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1235
1236   object_class->finalize = dispatcher_finalize;
1237
1238   signals[OBSERVE] =
1239     g_signal_new ("observe",
1240       G_TYPE_FROM_CLASS (klass),
1241       G_SIGNAL_RUN_LAST,
1242       0,
1243       NULL, NULL,
1244       g_cclosure_marshal_VOID__OBJECT,
1245       G_TYPE_NONE,
1246       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1247
1248   signals[APPROVE] =
1249     g_signal_new ("approve",
1250       G_TYPE_FROM_CLASS (klass),
1251       G_SIGNAL_RUN_LAST,
1252       0,
1253       NULL, NULL,
1254       g_cclosure_marshal_VOID__OBJECT,
1255       G_TYPE_NONE,
1256       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1257
1258   signals[DISPATCH] =
1259     g_signal_new ("dispatch",
1260       G_TYPE_FROM_CLASS (klass),
1261       G_SIGNAL_RUN_LAST,
1262       0,
1263       NULL, NULL,
1264       g_cclosure_marshal_VOID__OBJECT,
1265       G_TYPE_NONE,
1266       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1267
1268   g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
1269
1270 }
1271
1272 static void
1273 empathy_dispatcher_init (EmpathyDispatcher *dispatcher)
1274 {
1275   GList *accounts, *l;
1276   EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (dispatcher,
1277     EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
1278
1279   dispatcher->priv = priv;
1280   priv->mc = empathy_mission_control_new ();
1281   priv->account_manager = empathy_account_manager_dup_singleton ();
1282
1283   g_signal_connect (priv->account_manager,
1284     "account-connection-changed",
1285     G_CALLBACK (dispatcher_account_connection_cb),
1286     dispatcher);
1287
1288   priv->accounts = g_hash_table_new_full (empathy_account_hash,
1289         empathy_account_equal, g_object_unref, g_object_unref);
1290
1291   priv->connections = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1292     g_object_unref, (GDestroyNotify) free_connection_data);
1293
1294   accounts = mc_accounts_list_by_enabled (TRUE);
1295
1296   for (l = accounts; l; l = l->next) {
1297     dispatcher_update_account (dispatcher, l->data);
1298     g_object_unref (l->data);
1299   }
1300   g_list_free (accounts);
1301
1302   /* FIXME thisshould probably be created by another object.. */
1303   priv->chatroom_mgr = empathy_chatroom_manager_new (NULL);
1304   empathy_chatroom_manager_observe (priv->chatroom_mgr, dispatcher);
1305 }
1306
1307 EmpathyDispatcher *
1308 empathy_get_dispatcher (void)
1309 {
1310   if (!dispatcher) {
1311     dispatcher = g_object_new (EMPATHY_TYPE_DISPATCHER, NULL);
1312     g_object_add_weak_pointer (G_OBJECT (dispatcher), (gpointer) &dispatcher);
1313   } else {
1314     g_object_ref (dispatcher);
1315   }
1316
1317   return dispatcher;
1318 }
1319
1320 static void
1321 dispatcher_connection_new_requested_channel (EmpathyDispatcher *dispatcher,
1322   DispatcherRequestData *request_data, const gchar *object_path,
1323   GHashTable *properties, const GError *error)
1324 {
1325   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1326   EmpathyDispatchOperation *operation = NULL;
1327   ConnectionData *conn_data;
1328
1329   conn_data = g_hash_table_lookup (priv->connections,
1330     request_data->connection);
1331
1332   if (error)
1333     {
1334       DEBUG ("Channel request failed: %s", error->message);
1335
1336       if (request_data->cb != NULL)
1337           request_data->cb (NULL, error, request_data->user_data);
1338
1339       conn_data->outstanding_requests =
1340         g_list_remove (conn_data->outstanding_requests, request_data);
1341       free_dispatcher_request_data (request_data);
1342
1343       goto out;
1344   }
1345
1346   operation = g_hash_table_lookup (conn_data->outstanding_channels,
1347     object_path);
1348
1349   if (operation != NULL)
1350     g_hash_table_remove (conn_data->outstanding_channels, object_path);
1351   else
1352     operation = g_hash_table_lookup (conn_data->dispatching_channels,
1353         object_path);
1354
1355   if (operation == NULL)
1356     {
1357       DispatchData *data = g_hash_table_lookup (conn_data->dispatched_channels,
1358         object_path);
1359
1360       if (data != NULL)
1361         {
1362           operation = empathy_dispatch_operation_new_with_wrapper (
1363             request_data->connection,
1364             data->channel, request_data->contact, FALSE,
1365             data->channel_wrapper);
1366         }
1367       else
1368         {
1369           TpChannel *channel;
1370
1371           if (properties != NULL)
1372             channel = tp_channel_new_from_properties (request_data->connection,
1373               object_path, properties, NULL);
1374           else
1375             channel = tp_channel_new (request_data->connection, object_path,
1376               request_data->channel_type, request_data->handle_type,
1377               request_data->handle, NULL);
1378
1379           g_signal_connect (channel, "invalidated",
1380             G_CALLBACK (dispatcher_channel_invalidated_cb),
1381             request_data->dispatcher);
1382
1383           operation = empathy_dispatch_operation_new (request_data->connection,
1384              channel, request_data->contact, FALSE);
1385           g_object_unref (channel);
1386         }
1387     }
1388   else
1389     {
1390       /* Already existed set potential extra information */
1391       g_object_set (G_OBJECT (operation),
1392         "contact", request_data->contact,
1393         NULL);
1394     }
1395
1396   request_data->operation = operation;
1397
1398   /* (pre)-approve this right away as we requested it */
1399   empathy_dispatch_operation_approve (operation);
1400
1401   dispatcher_start_dispatching (request_data->dispatcher, operation,
1402         conn_data);
1403 out:
1404   dispatcher_flush_outstanding_operations (request_data->dispatcher,
1405     conn_data);
1406 }
1407
1408 static void
1409 dispatcher_request_channel_cb (TpConnection *connection,
1410   const gchar  *object_path, const GError *error,
1411   gpointer      user_data, GObject      *weak_object)
1412 {
1413   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1414   DispatcherRequestData *request_data = (DispatcherRequestData*) user_data;
1415
1416   dispatcher_connection_new_requested_channel (dispatcher,
1417     request_data, object_path, NULL, error);
1418 }
1419
1420 void
1421 empathy_dispatcher_call_with_contact ( EmpathyContact *contact,
1422   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1423 {
1424   g_assert_not_reached ();
1425 }
1426
1427 void
1428 empathy_dispatcher_call_with_contact_id (McAccount *account,
1429   const gchar  *contact_id, EmpathyDispatcherRequestCb *callback,
1430   gpointer user_data)
1431 {
1432   g_assert_not_reached ();
1433 }
1434
1435 static void
1436 dispatcher_request_channel (DispatcherRequestData *request_data)
1437 {
1438   tp_cli_connection_call_request_channel (request_data->connection, -1,
1439     request_data->channel_type,
1440     request_data->handle_type,
1441     request_data->handle,
1442     TRUE, dispatcher_request_channel_cb,
1443     request_data, NULL, G_OBJECT (request_data->dispatcher));
1444 }
1445
1446 static void
1447 dispatcher_chat_with_contact_cb (EmpathyContact *contact, gpointer user_data)
1448 {
1449   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1450
1451   request_data->handle = empathy_contact_get_handle (contact);
1452
1453   dispatcher_request_channel (request_data);
1454 }
1455
1456 void
1457 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1458   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1459 {
1460   EmpathyDispatcher *dispatcher = empathy_get_dispatcher();
1461   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1462   McAccount *account = empathy_contact_get_account (contact);
1463   TpConnection *connection = g_hash_table_lookup (priv->accounts, account);
1464   ConnectionData *connection_data =
1465     g_hash_table_lookup (priv->connections, connection);
1466   DispatcherRequestData *request_data;
1467
1468   /* The contact handle might not be known yet */
1469   request_data  = new_dispatcher_request_data (dispatcher, connection,
1470     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT, 0, NULL,
1471     contact, callback, user_data);
1472
1473   connection_data->outstanding_requests = g_list_prepend
1474     (connection_data->outstanding_requests, request_data);
1475
1476   empathy_contact_call_when_ready (contact,
1477     EMPATHY_CONTACT_READY_HANDLE, dispatcher_chat_with_contact_cb,
1478     request_data);
1479
1480   g_object_unref (dispatcher);
1481 }
1482
1483 void
1484 empathy_dispatcher_chat_with_contact_id (McAccount *account, const gchar
1485   *contact_id, EmpathyDispatcherRequestCb *callback, gpointer user_data)
1486 {
1487   EmpathyDispatcher *dispatcher = empathy_get_dispatcher ();
1488   EmpathyContactFactory *factory;
1489   EmpathyContact        *contact;
1490
1491   factory = empathy_contact_factory_dup_singleton ();
1492   contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
1493
1494   empathy_dispatcher_chat_with_contact (contact, callback, user_data);
1495
1496   g_object_unref (contact);
1497   g_object_unref (factory);
1498   g_object_unref (dispatcher);
1499 }
1500
1501
1502 static void
1503 dispatcher_request_handles_cb (TpConnection *connection,
1504    const GArray *handles, const GError *error, gpointer user_data,
1505    GObject *object)
1506 {
1507   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1508
1509   if (error != NULL)
1510     {
1511       EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
1512       EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1513       ConnectionData *cd;
1514
1515       cd = g_hash_table_lookup (priv->connections, request_data->connection);
1516
1517       if (request_data->cb)
1518         request_data->cb (NULL, error, request_data->user_data);
1519
1520       cd->outstanding_requests = g_list_remove (cd->outstanding_requests,
1521         request_data);
1522
1523       free_dispatcher_request_data (request_data);
1524
1525       dispatcher_flush_outstanding_operations (dispatcher, cd);
1526       return;
1527     }
1528
1529   request_data->handle = g_array_index (handles, guint, 0);
1530   dispatcher_request_channel (request_data);
1531 }
1532
1533 void
1534 empathy_dispatcher_join_muc (McAccount *account, const gchar *roomname,
1535   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1536 {
1537   EmpathyDispatcher *dispatcher = empathy_get_dispatcher();
1538   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1539   DispatcherRequestData *request_data;
1540   TpConnection *connection = g_hash_table_lookup (priv->accounts, account);
1541   ConnectionData *connection_data =
1542     g_hash_table_lookup (priv->connections, connection);
1543   const gchar *names[] = { roomname, NULL };
1544
1545   /* Don't know the room handle yet */
1546   request_data  = new_dispatcher_request_data (dispatcher, connection,
1547     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_ROOM, 0, NULL,
1548     NULL, callback, user_data);
1549
1550   connection_data->outstanding_requests = g_list_prepend
1551     (connection_data->outstanding_requests, request_data);
1552
1553   tp_cli_connection_call_request_handles (connection, -1,
1554     TP_HANDLE_TYPE_ROOM, names,
1555     dispatcher_request_handles_cb, request_data, NULL,
1556     G_OBJECT (dispatcher));
1557
1558   g_object_unref (dispatcher);
1559 }
1560
1561 #if 0
1562 typedef struct {
1563         GFile *gfile;
1564         TpHandle handle;
1565 } FileChannelRequest;
1566
1567 static void
1568 tp_file_state_notify_cb (EmpathyTpFile *tp_file)
1569 {
1570         EmpFileTransferState state;
1571
1572         state = empathy_tp_file_get_state (tp_file, NULL);
1573         if (state == EMP_FILE_TRANSFER_STATE_COMPLETED ||
1574             state == EMP_FILE_TRANSFER_STATE_CANCELLED) {
1575                 DEBUG ("Transfer is done, unref the object");
1576                 g_object_unref (tp_file);
1577         }
1578 }
1579
1580 static void
1581 file_channel_create_cb (TpConnection *connection,
1582                         const gchar  *object_path,
1583                         GHashTable   *properties,
1584                         const GError *error,
1585                         gpointer      user_data,
1586                         GObject      *weak_object)
1587 {
1588         TpChannel *channel;
1589         EmpathyTpFile *tp_file;
1590         FileChannelRequest *request = (FileChannelRequest *) user_data;
1591
1592         if (error) {
1593                 DEBUG ("Couldn't request channel: %s", error->message);
1594                 return;
1595         }
1596
1597         channel = tp_channel_new (connection,
1598                                  object_path,
1599                                  EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER,
1600                                  TP_HANDLE_TYPE_CONTACT,
1601                                  request->handle,
1602                                  NULL);
1603
1604         /* We give the ref to the callback, it is responsible to unref the
1605          * object once the transfer is done. */
1606         tp_file = empathy_tp_file_new (channel);
1607         empathy_tp_file_offer (tp_file, request->gfile, NULL);
1608         g_signal_connect (tp_file, "notify::state",
1609                           G_CALLBACK (tp_file_state_notify_cb),
1610                           NULL);
1611
1612         g_object_unref (request->gfile);
1613         g_slice_free (FileChannelRequest, request);
1614         g_object_unref (channel);
1615 }
1616
1617 #endif
1618
1619
1620 static void
1621 dispatcher_create_channel_cb (TpConnection *connect,
1622   const gchar *object_path, GHashTable *properties, const GError *error,
1623   gpointer user_data, GObject *weak_object)
1624 {
1625   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1626   DispatcherRequestData *request_data = (DispatcherRequestData*) user_data;
1627
1628   dispatcher_connection_new_requested_channel (dispatcher,
1629     request_data, object_path, properties, error);
1630 }
1631
1632
1633 static void
1634 dispatcher_create_channel_with_contact_cb (EmpathyContact *contact,
1635   gpointer user_data)
1636 {
1637   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1638   GValue *target_handle;
1639
1640   g_assert (request_data->request);
1641
1642   request_data->handle = empathy_contact_get_handle (contact);
1643
1644   target_handle = tp_g_value_slice_new (G_TYPE_UINT);
1645   g_value_set_uint (target_handle, request_data->handle);
1646   g_hash_table_insert (request_data->request,
1647     TP_IFACE_CHANNEL ".TargetHandle", target_handle);
1648
1649   tp_cli_connection_interface_requests_call_create_channel (
1650     request_data->connection, -1,
1651     request_data->request, dispatcher_create_channel_cb, request_data, NULL,
1652     G_OBJECT (request_data->dispatcher));
1653 }
1654
1655 void
1656 empathy_dispatcher_send_file_to_contact (EmpathyContact *contact,
1657   const gchar *filename, guint64 size, guint64 date,
1658   const gchar *content_type, EmpathyDispatcherRequestCb *callback,
1659   gpointer user_data)
1660 {
1661   EmpathyDispatcher *dispatcher = empathy_get_dispatcher();
1662   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1663   McAccount *account = empathy_contact_get_account (contact);
1664   TpConnection *connection = g_hash_table_lookup (priv->accounts, account);
1665   ConnectionData *connection_data =
1666     g_hash_table_lookup (priv->connections, connection);
1667   DispatcherRequestData *request_data;
1668   GValue *value;
1669   GHashTable *request = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
1670       (GDestroyNotify) tp_g_value_slice_free);
1671
1672   /* org.freedesktop.Telepathy.Channel.ChannelType */
1673   value = tp_g_value_slice_new (G_TYPE_STRING);
1674   g_value_set_string (value, EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
1675   g_hash_table_insert (request, TP_IFACE_CHANNEL ".ChannelType", value);
1676
1677   /* org.freedesktop.Telepathy.Channel.TargetHandleType */
1678   value = tp_g_value_slice_new (G_TYPE_UINT);
1679   g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
1680   g_hash_table_insert (request, TP_IFACE_CHANNEL ".TargetHandleType", value);
1681
1682   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
1683   value = tp_g_value_slice_new (G_TYPE_STRING);
1684   g_value_set_string (value, content_type);
1685   g_hash_table_insert (request,
1686     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
1687
1688   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
1689   value = tp_g_value_slice_new (G_TYPE_STRING);
1690   g_value_set_string (value, filename);
1691   g_hash_table_insert (request,
1692     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
1693
1694   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
1695   value = tp_g_value_slice_new (G_TYPE_UINT64);
1696   g_value_set_uint64 (value, size);
1697   g_hash_table_insert (request,
1698     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
1699
1700   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
1701   value = tp_g_value_slice_new (G_TYPE_UINT64);
1702   g_value_set_uint64 (value, date);
1703   g_hash_table_insert (request,
1704     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
1705
1706
1707   /* The contact handle might not be known yet */
1708   request_data  = new_dispatcher_request_data (dispatcher, connection,
1709     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER, TP_HANDLE_TYPE_CONTACT, 0, request,
1710     contact, callback, user_data);
1711   connection_data->outstanding_requests = g_list_prepend
1712     (connection_data->outstanding_requests, request_data);
1713
1714   empathy_contact_call_when_ready (contact,
1715     EMPATHY_CONTACT_READY_HANDLE, dispatcher_create_channel_with_contact_cb,
1716     request_data);
1717
1718   g_object_unref (dispatcher);
1719 }
1720
1721 #if 0
1722         MissionControl     *mc;
1723         McAccount          *account;
1724         TpConnection       *connection;
1725         guint               handle;
1726         FileChannelRequest *request;
1727         GHashTable         *args;
1728         GValue             *value;
1729         GFileInfo          *info;
1730         gchar              *filename;
1731         GTimeVal            last_modif;
1732         GError             *error = NULL;
1733
1734         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1735         g_return_if_fail (G_IS_FILE (gfile));
1736
1737         info = g_file_query_info (gfile,
1738                                   G_FILE_ATTRIBUTE_STANDARD_SIZE ","
1739                                   G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
1740                                   G_FILE_ATTRIBUTE_TIME_MODIFIED,
1741                                   0, NULL, &error);
1742
1743         if (error) {
1744                 DEBUG ("Can't get info about the file: %s", error->message);
1745                 g_clear_error (&error);
1746                 return;
1747         }
1748
1749         mc = empathy_mission_control_new ();
1750         account = empathy_contact_get_account (contact);
1751         connection = mission_control_get_tpconnection (mc, account, NULL);
1752         handle = empathy_contact_get_handle (contact);
1753
1754         request = g_slice_new0 (FileChannelRequest);
1755         request->gfile = g_object_ref (gfile);
1756         request->handle = handle;
1757
1758         filename = g_file_get_basename (request->gfile);
1759         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
1760
1761         DEBUG ("Sending %s from a stream to %s (size %"G_GINT64_FORMAT", content-type %s)",
1762                filename, empathy_contact_get_name (contact),
1763                g_file_info_get_size (info),
1764                g_file_info_get_content_type (info));
1765
1766         args = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
1767                                       (GDestroyNotify) tp_g_value_slice_free);
1768
1769         /* org.freedesktop.Telepathy.Channel.ChannelType */
1770         value = tp_g_value_slice_new (G_TYPE_STRING);
1771         g_value_set_string (value, EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
1772         g_hash_table_insert (args, TP_IFACE_CHANNEL ".ChannelType", value);
1773
1774         /* org.freedesktop.Telepathy.Channel.TargetHandleType */
1775         value = tp_g_value_slice_new (G_TYPE_UINT);
1776         g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
1777         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandleType", value);
1778
1779         /* org.freedesktop.Telepathy.Channel.TargetHandle */
1780         value = tp_g_value_slice_new (G_TYPE_UINT);
1781         g_value_set_uint (value, handle);
1782         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandle", value);
1783
1784         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
1785         value = tp_g_value_slice_new (G_TYPE_STRING);
1786         g_value_set_string (value, g_file_info_get_content_type (info));
1787         g_hash_table_insert (args,
1788                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
1789
1790         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
1791         value = tp_g_value_slice_new (G_TYPE_STRING);
1792         g_value_set_string (value, g_filename_display_basename (filename));
1793         g_hash_table_insert (args,
1794                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
1795
1796         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
1797         value = tp_g_value_slice_new (G_TYPE_UINT64);
1798         g_value_set_uint64 (value, g_file_info_get_size (info));
1799         g_hash_table_insert (args,
1800                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
1801
1802         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
1803         g_file_info_get_modification_time (info, &last_modif);
1804         value = tp_g_value_slice_new (G_TYPE_UINT64);
1805         g_value_set_uint64 (value, last_modif.tv_sec);
1806         g_hash_table_insert (args,
1807                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
1808
1809         /* FIXME: Description ? */
1810         /* FIXME: ContentHashType and ContentHash ? */
1811
1812         tp_cli_connection_interface_requests_call_create_channel (connection, -1,
1813                 args, file_channel_create_cb, request, NULL, NULL);
1814
1815         g_hash_table_destroy (args);
1816         g_free (filename);
1817         g_object_unref (mc);
1818         g_object_unref (connection);
1819 }
1820
1821 #endif