]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
Add support for dispatching file transfers
[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   priv->chatroom_mgr = empathy_chatroom_manager_new (NULL);
1303 }
1304
1305 EmpathyDispatcher *
1306 empathy_get_dispatcher (void)
1307 {
1308   if (!dispatcher) {
1309     dispatcher = g_object_new (EMPATHY_TYPE_DISPATCHER, NULL);
1310     g_object_add_weak_pointer (G_OBJECT (dispatcher), (gpointer) &dispatcher);
1311   } else {
1312     g_object_ref (dispatcher);
1313   }
1314
1315   return dispatcher;
1316 }
1317
1318 static void
1319 dispatcher_connection_new_requested_channel (EmpathyDispatcher *dispatcher,
1320   DispatcherRequestData *request_data, const gchar *object_path,
1321   GHashTable *properties, const GError *error)
1322 {
1323   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1324   EmpathyDispatchOperation *operation = NULL;
1325   ConnectionData *conn_data;
1326
1327   conn_data = g_hash_table_lookup (priv->connections,
1328     request_data->connection);
1329
1330   if (error)
1331     {
1332       DEBUG ("Channel request failed: %s", error->message);
1333
1334       if (request_data->cb != NULL)
1335           request_data->cb (NULL, error, request_data->user_data);
1336
1337       conn_data->outstanding_requests =
1338         g_list_remove (conn_data->outstanding_requests, request_data);
1339       free_dispatcher_request_data (request_data);
1340
1341       goto out;
1342   }
1343
1344   operation = g_hash_table_lookup (conn_data->outstanding_channels,
1345     object_path);
1346
1347   if (operation != NULL)
1348     g_hash_table_remove (conn_data->outstanding_channels, object_path);
1349   else
1350     operation = g_hash_table_lookup (conn_data->dispatching_channels,
1351         object_path);
1352
1353   if (operation == NULL)
1354     {
1355       DispatchData *data = g_hash_table_lookup (conn_data->dispatched_channels,
1356         object_path);
1357
1358       if (data != NULL)
1359         {
1360           operation = empathy_dispatch_operation_new_with_wrapper (
1361             request_data->connection,
1362             data->channel, request_data->contact, FALSE,
1363             data->channel_wrapper);
1364         }
1365       else
1366         {
1367           TpChannel *channel;
1368
1369           if (properties != NULL)
1370             channel = tp_channel_new_from_properties (request_data->connection,
1371               object_path, properties, NULL);
1372           else
1373             channel = tp_channel_new (request_data->connection, object_path,
1374               request_data->channel_type, request_data->handle_type,
1375               request_data->handle, NULL);
1376
1377           g_signal_connect (channel, "invalidated",
1378             G_CALLBACK (dispatcher_channel_invalidated_cb),
1379             request_data->dispatcher);
1380
1381           operation = empathy_dispatch_operation_new (request_data->connection,
1382              channel, request_data->contact, FALSE);
1383           g_object_unref (channel);
1384         }
1385     }
1386   else
1387     {
1388       /* Already existed set potential extra information */
1389       g_object_set (G_OBJECT (operation),
1390         "contact", request_data->contact,
1391         NULL);
1392     }
1393
1394   request_data->operation = operation;
1395
1396   /* (pre)-approve this right away as we requested it */
1397   empathy_dispatch_operation_approve (operation);
1398
1399   dispatcher_start_dispatching (request_data->dispatcher, operation,
1400         conn_data);
1401 out:
1402   dispatcher_flush_outstanding_operations (request_data->dispatcher,
1403     conn_data);
1404
1405 }
1406
1407 static void
1408 dispatcher_request_channel_cb (TpConnection *connection,
1409   const gchar  *object_path, const GError *error,
1410   gpointer      user_data, GObject      *weak_object)
1411 {
1412   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1413   DispatcherRequestData *request_data = (DispatcherRequestData*) user_data;
1414
1415   dispatcher_connection_new_requested_channel (dispatcher,
1416     request_data, object_path, NULL, error);
1417 }
1418
1419 void
1420 empathy_dispatcher_call_with_contact ( EmpathyContact *contact,
1421   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1422 {
1423   g_assert_not_reached ();
1424 }
1425
1426 void
1427 empathy_dispatcher_call_with_contact_id (McAccount *account,
1428   const gchar  *contact_id, EmpathyDispatcherRequestCb *callback,
1429   gpointer user_data)
1430 {
1431   g_assert_not_reached ();
1432 }
1433
1434 static void
1435 dispatcher_chat_with_contact_cb (EmpathyContact *contact, gpointer user_data)
1436 {
1437   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1438
1439   request_data->handle = empathy_contact_get_handle (contact);
1440
1441   tp_cli_connection_call_request_channel (request_data->connection, -1,
1442     request_data->channel_type,
1443     request_data->handle_type,
1444     request_data->handle,
1445     TRUE, dispatcher_request_channel_cb,
1446     request_data, NULL, G_OBJECT (request_data->dispatcher));
1447 }
1448
1449 void
1450 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1451   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1452 {
1453   EmpathyDispatcher *dispatcher = empathy_get_dispatcher();
1454   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1455   McAccount *account = empathy_contact_get_account (contact);
1456   TpConnection *connection = g_hash_table_lookup (priv->accounts, account);
1457   ConnectionData *connection_data =
1458     g_hash_table_lookup (priv->connections, connection);
1459   DispatcherRequestData *request_data;
1460
1461   /* The contact handle might not be known yet */
1462   request_data  = new_dispatcher_request_data (dispatcher, connection,
1463     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT, 0, NULL,
1464     contact, callback, user_data);
1465
1466   connection_data->outstanding_requests = g_list_prepend
1467     (connection_data->outstanding_requests, request_data);
1468
1469   empathy_contact_call_when_ready (contact,
1470     EMPATHY_CONTACT_READY_HANDLE, dispatcher_chat_with_contact_cb,
1471     request_data);
1472
1473   g_object_unref (dispatcher);
1474 }
1475
1476 void
1477 empathy_dispatcher_chat_with_contact_id (McAccount *account, const gchar
1478   *contact_id, EmpathyDispatcherRequestCb *callback, gpointer user_data)
1479 {
1480   EmpathyDispatcher *dispatcher = empathy_get_dispatcher ();
1481   EmpathyContactFactory *factory;
1482   EmpathyContact        *contact;
1483
1484   factory = empathy_contact_factory_dup_singleton ();
1485   contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
1486
1487   empathy_dispatcher_chat_with_contact (contact, callback, user_data);
1488
1489   g_object_unref (contact);
1490   g_object_unref (factory);
1491   g_object_unref (dispatcher);
1492 }
1493
1494 #if 0
1495 typedef struct {
1496         GFile *gfile;
1497         TpHandle handle;
1498 } FileChannelRequest;
1499
1500 static void
1501 tp_file_state_notify_cb (EmpathyTpFile *tp_file)
1502 {
1503         EmpFileTransferState state;
1504
1505         state = empathy_tp_file_get_state (tp_file, NULL);
1506         if (state == EMP_FILE_TRANSFER_STATE_COMPLETED ||
1507             state == EMP_FILE_TRANSFER_STATE_CANCELLED) {
1508                 DEBUG ("Transfer is done, unref the object");
1509                 g_object_unref (tp_file);
1510         }
1511 }
1512
1513 static void
1514 file_channel_create_cb (TpConnection *connection,
1515                         const gchar  *object_path,
1516                         GHashTable   *properties,
1517                         const GError *error,
1518                         gpointer      user_data,
1519                         GObject      *weak_object)
1520 {
1521         TpChannel *channel;
1522         EmpathyTpFile *tp_file;
1523         FileChannelRequest *request = (FileChannelRequest *) user_data;
1524
1525         if (error) {
1526                 DEBUG ("Couldn't request channel: %s", error->message);
1527                 return;
1528         }
1529
1530         channel = tp_channel_new (connection,
1531                                  object_path,
1532                                  EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER,
1533                                  TP_HANDLE_TYPE_CONTACT,
1534                                  request->handle,
1535                                  NULL);
1536
1537         /* We give the ref to the callback, it is responsible to unref the
1538          * object once the transfer is done. */
1539         tp_file = empathy_tp_file_new (channel);
1540         empathy_tp_file_offer (tp_file, request->gfile, NULL);
1541         g_signal_connect (tp_file, "notify::state",
1542                           G_CALLBACK (tp_file_state_notify_cb),
1543                           NULL);
1544
1545         g_object_unref (request->gfile);
1546         g_slice_free (FileChannelRequest, request);
1547         g_object_unref (channel);
1548 }
1549
1550 #endif
1551
1552
1553 static void
1554 dispatcher_create_channel_cb (TpConnection *connect,
1555   const gchar *object_path, GHashTable *properties, const GError *error,
1556   gpointer user_data, GObject *weak_object)
1557 {
1558   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (weak_object);
1559   DispatcherRequestData *request_data = (DispatcherRequestData*) user_data;
1560
1561   dispatcher_connection_new_requested_channel (dispatcher,
1562     request_data, object_path, properties, error);
1563 }
1564
1565
1566 static void
1567 dispatcher_create_channel_with_contact_cb (EmpathyContact *contact,
1568   gpointer user_data)
1569 {
1570   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1571   GValue *target_handle;
1572
1573   g_assert (request_data->request);
1574
1575   request_data->handle = empathy_contact_get_handle (contact);
1576
1577   target_handle = tp_g_value_slice_new (G_TYPE_UINT);
1578   g_value_set_uint (target_handle, request_data->handle);
1579   g_hash_table_insert (request_data->request,
1580     TP_IFACE_CHANNEL ".TargetHandle", target_handle);
1581
1582   tp_cli_connection_interface_requests_call_create_channel (
1583     request_data->connection, -1,
1584     request_data->request, dispatcher_create_channel_cb, request_data, NULL,
1585     G_OBJECT (request_data->dispatcher));
1586 }
1587
1588 void
1589 empathy_dispatcher_send_file_to_contact (EmpathyContact *contact,
1590   const gchar *filename, guint64 size, guint64 date,
1591   const gchar *content_type, EmpathyDispatcherRequestCb *callback,
1592   gpointer user_data)
1593 {
1594   EmpathyDispatcher *dispatcher = empathy_get_dispatcher();
1595   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1596   McAccount *account = empathy_contact_get_account (contact);
1597   TpConnection *connection = g_hash_table_lookup (priv->accounts, account);
1598   ConnectionData *connection_data =
1599     g_hash_table_lookup (priv->connections, connection);
1600   DispatcherRequestData *request_data;
1601   GValue *value;
1602   GHashTable *request = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
1603       (GDestroyNotify) tp_g_value_slice_free);
1604
1605   /* org.freedesktop.Telepathy.Channel.ChannelType */
1606   value = tp_g_value_slice_new (G_TYPE_STRING);
1607   g_value_set_string (value, EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
1608   g_hash_table_insert (request, TP_IFACE_CHANNEL ".ChannelType", value);
1609
1610   /* org.freedesktop.Telepathy.Channel.TargetHandleType */
1611   value = tp_g_value_slice_new (G_TYPE_UINT);
1612   g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
1613   g_hash_table_insert (request, TP_IFACE_CHANNEL ".TargetHandleType", value);
1614
1615   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
1616   value = tp_g_value_slice_new (G_TYPE_STRING);
1617   g_value_set_string (value, content_type);
1618   g_hash_table_insert (request,
1619     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
1620
1621   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
1622   value = tp_g_value_slice_new (G_TYPE_STRING);
1623   g_value_set_string (value, filename);
1624   g_hash_table_insert (request,
1625     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
1626
1627   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
1628   value = tp_g_value_slice_new (G_TYPE_UINT64);
1629   g_value_set_uint64 (value, size);
1630   g_hash_table_insert (request,
1631     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
1632
1633   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
1634   value = tp_g_value_slice_new (G_TYPE_UINT64);
1635   g_value_set_uint64 (value, date);
1636   g_hash_table_insert (request,
1637     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
1638
1639
1640   /* The contact handle might not be known yet */
1641   request_data  = new_dispatcher_request_data (dispatcher, connection,
1642     EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER, TP_HANDLE_TYPE_CONTACT, 0, request,
1643     contact, callback, user_data);
1644   connection_data->outstanding_requests = g_list_prepend
1645     (connection_data->outstanding_requests, request_data);
1646
1647   empathy_contact_call_when_ready (contact,
1648     EMPATHY_CONTACT_READY_HANDLE, dispatcher_create_channel_with_contact_cb,
1649     request_data);
1650
1651   g_object_unref (dispatcher);
1652 }
1653
1654 #if 0
1655         MissionControl     *mc;
1656         McAccount          *account;
1657         TpConnection       *connection;
1658         guint               handle;
1659         FileChannelRequest *request;
1660         GHashTable         *args;
1661         GValue             *value;
1662         GFileInfo          *info;
1663         gchar              *filename;
1664         GTimeVal            last_modif;
1665         GError             *error = NULL;
1666
1667         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1668         g_return_if_fail (G_IS_FILE (gfile));
1669
1670         info = g_file_query_info (gfile,
1671                                   G_FILE_ATTRIBUTE_STANDARD_SIZE ","
1672                                   G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
1673                                   G_FILE_ATTRIBUTE_TIME_MODIFIED,
1674                                   0, NULL, &error);
1675
1676         if (error) {
1677                 DEBUG ("Can't get info about the file: %s", error->message);
1678                 g_clear_error (&error);
1679                 return;
1680         }
1681
1682         mc = empathy_mission_control_new ();
1683         account = empathy_contact_get_account (contact);
1684         connection = mission_control_get_tpconnection (mc, account, NULL);
1685         handle = empathy_contact_get_handle (contact);
1686
1687         request = g_slice_new0 (FileChannelRequest);
1688         request->gfile = g_object_ref (gfile);
1689         request->handle = handle;
1690
1691         filename = g_file_get_basename (request->gfile);
1692         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
1693
1694         DEBUG ("Sending %s from a stream to %s (size %"G_GINT64_FORMAT", content-type %s)",
1695                filename, empathy_contact_get_name (contact),
1696                g_file_info_get_size (info),
1697                g_file_info_get_content_type (info));
1698
1699         args = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
1700                                       (GDestroyNotify) tp_g_value_slice_free);
1701
1702         /* org.freedesktop.Telepathy.Channel.ChannelType */
1703         value = tp_g_value_slice_new (G_TYPE_STRING);
1704         g_value_set_string (value, EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
1705         g_hash_table_insert (args, TP_IFACE_CHANNEL ".ChannelType", value);
1706
1707         /* org.freedesktop.Telepathy.Channel.TargetHandleType */
1708         value = tp_g_value_slice_new (G_TYPE_UINT);
1709         g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
1710         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandleType", value);
1711
1712         /* org.freedesktop.Telepathy.Channel.TargetHandle */
1713         value = tp_g_value_slice_new (G_TYPE_UINT);
1714         g_value_set_uint (value, handle);
1715         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandle", value);
1716
1717         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
1718         value = tp_g_value_slice_new (G_TYPE_STRING);
1719         g_value_set_string (value, g_file_info_get_content_type (info));
1720         g_hash_table_insert (args,
1721                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
1722
1723         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
1724         value = tp_g_value_slice_new (G_TYPE_STRING);
1725         g_value_set_string (value, g_filename_display_basename (filename));
1726         g_hash_table_insert (args,
1727                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
1728
1729         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
1730         value = tp_g_value_slice_new (G_TYPE_UINT64);
1731         g_value_set_uint64 (value, g_file_info_get_size (info));
1732         g_hash_table_insert (args,
1733                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
1734
1735         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
1736         g_file_info_get_modification_time (info, &last_modif);
1737         value = tp_g_value_slice_new (G_TYPE_UINT64);
1738         g_value_set_uint64 (value, last_modif.tv_sec);
1739         g_hash_table_insert (args,
1740                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
1741
1742         /* FIXME: Description ? */
1743         /* FIXME: ContentHashType and ContentHash ? */
1744
1745         tp_cli_connection_interface_requests_call_create_channel (connection, -1,
1746                 args, file_channel_create_cb, request, NULL, NULL);
1747
1748         g_hash_table_destroy (args);
1749         g_free (filename);
1750         g_object_unref (mc);
1751         g_object_unref (connection);
1752 }
1753
1754 #endif