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