]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
Add an optional properties hash to the RequestData struct
[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   /* Properties to pass to the channel when requesting it */
94   GHashTable *properties;
95   EmpathyDispatcherRequestCb *cb;
96   gpointer user_data;
97   gpointer *request_data;
98 } DispatcherRequestData;
99
100 typedef struct {
101   TpChannel *channel;
102   /* Channel type specific wrapper object */
103   GObject *channel_wrapper;
104 } DispatchData;
105
106 typedef struct {
107   McAccount *account;
108   /* ObjectPath => DispatchData.. */
109   GHashTable *dispatched_channels;
110   /* ObjectPath -> EmpathyDispatchOperations */
111   GHashTable *dispatching_channels;
112   /* ObjectPath -> EmpathyDispatchOperations */
113   GHashTable *outstanding_channels;
114   /* List of DispatcherRequestData */
115   GList *outstanding_requests;
116 } ConnectionData;
117
118 static DispatchData *
119 new_dispatch_data (TpChannel *channel, GObject *channel_wrapper)
120 {
121   DispatchData *d = g_slice_new0 (DispatchData);
122   d->channel = channel;
123   d->channel_wrapper = channel_wrapper;
124
125   return d;
126 }
127
128 static void
129 free_dispatch_data (DispatchData *data)
130 {
131   g_object_unref (data->channel);
132   g_object_unref (data->channel_wrapper);
133
134   g_slice_free (DispatchData, data);
135 }
136
137
138 static DispatcherRequestData *
139 new_dispatcher_request_data (EmpathyDispatcher *dispatcher,
140   TpConnection *connection, const gchar *channel_type, guint handle_type,
141   guint handle, GHashTable *properties,
142   EmpathyContact *contact, EmpathyDispatcherRequestCb *cb, gpointer user_data)
143 {
144   DispatcherRequestData *result = g_slice_new0 (DispatcherRequestData);
145
146   result->dispatcher = dispatcher;
147   result->connection = connection;
148
149   result->channel_type = g_strdup (channel_type);
150   result->handle_type = handle_type;
151   result->handle = handle;
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->properties != NULL)
171     g_hash_table_unref (r->properties);
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
647   object_path = tp_proxy_get_object_path (proxy);
648
649   DEBUG ("Channel %s invalidated", object_path);
650
651   g_hash_table_remove (cd->dispatched_channels, object_path);
652   g_hash_table_remove (cd->dispatching_channels, object_path);
653
654   operation = g_hash_table_lookup (cd->outstanding_channels, object_path);
655   if (operation != NULL)
656     {
657       GError error = { domain, code, message };
658       dispatch_operation_flush_requests (dispatcher, operation, &error, cd);
659       g_hash_table_remove (cd->outstanding_channels, object_path);
660       g_object_unref (operation);
661     }
662 }
663
664 static void
665 dispatch_operation_approved_cb (EmpathyDispatchOperation *operation,
666   EmpathyDispatcher *dispatcher)
667 {
668   g_assert (empathy_dispatch_operation_is_incoming (operation));
669   DEBUG ("Send of for dispatching: %s",
670     empathy_dispatch_operation_get_object_path (operation));
671   g_signal_emit (dispatcher, signals[DISPATCH], 0, operation);
672 }
673
674 static void
675 dispatch_operation_claimed_cb (EmpathyDispatchOperation *operation,
676   EmpathyDispatcher *dispatcher)
677 {
678   /* Our job is done, remove the dispatch operation and mark the channel as
679    * dispatched */
680   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
681   TpConnection *connection;
682   ConnectionData *cd;
683   const gchar *object_path;
684
685   connection = empathy_dispatch_operation_get_tp_connection (operation);
686   cd = g_hash_table_lookup (priv->connections, connection);
687   g_assert (cd != NULL);
688   g_object_unref (G_OBJECT (connection));
689
690   object_path = empathy_dispatch_operation_get_object_path (operation);
691
692   if (g_hash_table_lookup (cd->dispatched_channels, object_path) == NULL)
693     {
694       DispatchData *d;
695       d = new_dispatch_data (
696         empathy_dispatch_operation_get_channel (operation),
697         empathy_dispatch_operation_get_channel_wrapper (operation));
698       g_hash_table_insert (cd->dispatched_channels,
699         g_strdup (object_path), d);
700     }
701   g_hash_table_remove (cd->dispatching_channels, object_path);
702
703   DEBUG ("Channel claimed: %s", object_path);
704 }
705
706 static void
707 dispatch_operation_ready_cb (EmpathyDispatchOperation *operation,
708   EmpathyDispatcher *dispatcher)
709 {
710   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
711   TpConnection *connection;
712   ConnectionData *cd;
713   EmpathyDispatchOperationState status;
714
715   g_signal_connect (operation, "approved",
716     G_CALLBACK (dispatch_operation_approved_cb), dispatcher);
717
718   g_signal_connect (operation, "claimed",
719     G_CALLBACK (dispatch_operation_claimed_cb), dispatcher);
720
721   /* Signal the observers */
722   DEBUG ("Send to observers: %s",
723     empathy_dispatch_operation_get_object_path (operation));
724   g_signal_emit (dispatcher, signals[OBSERVE], 0, operation);
725
726   empathy_dispatch_operation_start (operation);
727
728   /* Signal potential requestors */
729   connection =  empathy_dispatch_operation_get_tp_connection (operation);
730   cd = g_hash_table_lookup (priv->connections, connection);
731   g_assert (cd != NULL);
732   g_object_unref (G_OBJECT (connection));
733
734   g_object_ref (operation);
735
736   dispatch_operation_flush_requests (dispatcher, operation, NULL, cd);
737   status = empathy_dispatch_operation_get_status (operation);
738   g_object_unref (operation);
739
740   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_CLAIMED)
741     return;
742
743   if (status == EMPATHY_DISPATCHER_OPERATION_STATE_APPROVING)
744     {
745       DEBUG ("Send to approvers: %s",
746         empathy_dispatch_operation_get_object_path (operation));
747       g_signal_emit (dispatcher, signals[APPROVE], 0, operation);
748     }
749   else
750     {
751       g_assert (status == EMPATHY_DISPATCHER_OPERATION_STATE_DISPATCHING);
752       DEBUG ("Send of for dispatching: %s",
753         empathy_dispatch_operation_get_object_path (operation));
754       g_signal_emit (dispatcher, signals[DISPATCH], 0, operation);
755     }
756
757 }
758
759 static void
760 dispatcher_start_dispatching (EmpathyDispatcher *self,
761   EmpathyDispatchOperation *operation, ConnectionData *cd)
762 {
763   const gchar *object_path =
764     empathy_dispatch_operation_get_object_path (operation);
765
766   DEBUG ("Dispatching process started for %s", object_path);
767
768   if (g_hash_table_lookup (cd->dispatching_channels, object_path) == NULL)
769     {
770       g_assert (g_hash_table_lookup (cd->outstanding_channels,
771         object_path) == NULL);
772
773       g_hash_table_insert (cd->dispatching_channels,
774         g_strdup (object_path), operation);
775
776       switch (empathy_dispatch_operation_get_status (operation))
777         {
778           case EMPATHY_DISPATCHER_OPERATION_STATE_PREPARING:
779             g_signal_connect (operation, "ready",
780               G_CALLBACK (dispatch_operation_ready_cb), dispatcher);
781             break;
782           case EMPATHY_DISPATCHER_OPERATION_STATE_PENDING:
783             dispatch_operation_ready_cb (operation, dispatcher);
784             break;
785           default:
786             g_assert_not_reached();
787         }
788
789     }
790   else if (empathy_dispatch_operation_get_status (operation) >=
791       EMPATHY_DISPATCHER_OPERATION_STATE_PENDING)
792     {
793       /* Already dispatching and the operation is pending, thus the observers
794        * have seen it (if applicable), so we can flush the request right away.
795        */
796       dispatch_operation_flush_requests (self, operation, NULL, cd);
797     }
798 }
799
800
801 static void
802 dispatcher_flush_outstanding_operations (EmpathyDispatcher *self,
803   ConnectionData *cd)
804 {
805   GHashTableIter iter;
806   gpointer value;
807
808   g_hash_table_iter_init (&iter, cd->outstanding_channels);
809   while (g_hash_table_iter_next (&iter, NULL, &value))
810     {
811       EmpathyDispatchOperation *operation = EMPATHY_DISPATCH_OPERATION (value);
812
813       if (dispatcher_operation_can_start (self, operation, cd))
814         {
815           dispatcher_start_dispatching (dispatcher, operation, cd);
816           g_hash_table_iter_remove (&iter);
817         }
818     }
819 }
820
821
822 static void
823 dispatcher_connection_new_channel (EmpathyDispatcher *dispatcher,
824   TpConnection *connection,
825   const gchar  *object_path, const gchar  *channel_type,
826   guint handle_type, guint handle, GHashTable *properties,
827   gboolean incoming)
828 {
829   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
830   TpChannel         *channel;
831   ConnectionData *cd;
832   EmpathyDispatchOperation *operation;
833   EmpathyContact *contact = NULL;
834
835   cd = g_hash_table_lookup (priv->connections, connection);
836
837   /* Don't bother with channels we have already dispatched or are dispatching
838    * currently. This can happen when NewChannel(s) is fired after
839    * RequestChannel/CreateChannel/EnsureChannel */
840   if (g_hash_table_lookup (cd->dispatched_channels, object_path) != NULL)
841     return;
842
843   if (g_hash_table_lookup (cd->dispatching_channels, object_path) != NULL)
844     return;
845
846   /* Should never occur, but just in case a CM fires spurious NewChannel(s) 
847    * signals */
848   if (g_hash_table_lookup (cd->outstanding_channels, object_path) != NULL)
849     return;
850
851   DEBUG ("New channel of type %s on %s",
852     channel_type, object_path);
853
854   if (properties == NULL)
855     channel = tp_channel_new (connection, object_path, channel_type,
856       handle_type, handle, NULL);
857   else
858     channel = tp_channel_new_from_properties (connection, object_path,
859       properties, NULL);
860
861   g_signal_connect (channel, "invalidated",
862     G_CALLBACK (dispatcher_channel_invalidated_cb),
863     dispatcher);
864
865   if (handle_type == TP_CONN_HANDLE_TYPE_CONTACT)
866     {
867       EmpathyContactFactory *factory = empathy_contact_factory_new ();
868       contact = empathy_contact_factory_get_from_handle (factory,
869         cd->account, handle);
870       g_object_unref (factory);
871     }
872
873   operation = empathy_dispatch_operation_new (connection, channel, contact,
874     incoming);
875
876   g_object_unref (channel);
877
878   if (incoming)
879     {
880       /* Request could either be by us or by a remote party. If there are no
881        * outstanding requests for this channel type we can assume it's remote.
882        * Otherwise we wait untill they are all satisfied */
883       if (dispatcher_operation_can_start (dispatcher, operation, cd))
884         dispatcher_start_dispatching (dispatcher, operation, cd);
885       else
886         g_hash_table_insert (cd->outstanding_channels,
887           g_strdup (object_path), operation);
888     }
889   else
890     {
891       dispatcher_start_dispatching (dispatcher, operation, cd);
892     }
893 }
894
895 static void
896 dispatcher_connection_new_channel_cb (TpConnection *connection,
897   const gchar  *object_path, const gchar  *channel_type,
898   guint         handle_type, guint         handle,
899   gboolean      suppress_handler, gpointer      user_data,
900   GObject      *object)
901 {
902   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
903
904   /* Empathy heavily abuses surpress handler (don't try this at home), if
905    * surpress handler is true then it is an outgoing channel, which is
906    * requested either by us or some other party (like the megaphone applet).
907    * Otherwise it's an incoming channel */
908   dispatcher_connection_new_channel (dispatcher, connection,
909     object_path, channel_type, handle_type, handle, NULL, !suppress_handler);
910 }
911
912 static void
913 dispatcher_connection_new_channel_with_properties (
914   EmpathyDispatcher *dispatcher, TpConnection *connection,
915   const gchar *object_path, GHashTable *properties)
916 {
917   const gchar *channel_type;
918   guint handle_type;
919   guint handle;
920   gboolean requested;
921   gboolean valid;
922
923
924   channel_type = tp_asv_get_string (properties,
925     TP_IFACE_CHANNEL ".ChannelType");
926   if (channel_type == NULL)
927     {
928       g_message ("%s had an invalid ChannelType property", object_path);
929       return;
930     }
931
932   handle_type = tp_asv_get_uint32 (properties,
933     TP_IFACE_CHANNEL ".TargetHandleType", &valid);
934   if (!valid)
935     {
936       g_message ("%s had an invalid TargetHandleType property", object_path);
937       return;
938     }
939
940   handle = tp_asv_get_uint32 (properties,
941     TP_IFACE_CHANNEL ".TargetHandle", &valid);
942   if (!valid)
943     {
944       g_message ("%s had an invalid TargetHandle property", object_path);
945       return;
946     }
947
948   /* We assume there is no channel dispather, so we're the only one dispatching
949    * it. Which means that a requested channel it is outgoing one */
950   requested = tp_asv_get_boolean (properties,
951     TP_IFACE_CHANNEL ".Requested", &valid);
952   if (!valid)
953     {
954       g_message ("%s had an invalid Requested property", object_path);
955       return;
956     }
957
958   dispatcher_connection_new_channel (dispatcher, connection,
959     object_path, channel_type, handle_type, handle, properties, !requested);
960 }
961
962
963 static void
964 dispatcher_connection_new_channels_cb (
965   TpConnection *connection, const GPtrArray *channels, gpointer user_data,
966   GObject *object)
967 {
968   EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
969   int i;
970
971   for (i = 0; i < channels->len ; i++)
972     {
973       GValueArray *arr = g_ptr_array_index (channels, i);
974       const gchar *object_path;
975       GHashTable *properties;
976
977       object_path = g_value_get_boxed (g_value_array_get_nth (arr, 0));
978       properties = g_value_get_boxed (g_value_array_get_nth (arr, 1));
979
980       dispatcher_connection_new_channel_with_properties (dispatcher,
981         connection, object_path, properties);
982     }
983 }
984
985 #if 0  /* old dispatching  */
986   channel = tp_channel_new (connection, object_path, channel_type,
987     handle_type, handle, NULL);
988   tp_channel_run_until_ready (channel, NULL, NULL);
989
990   if (!tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TUBES)) {
991     dispatcher_tubes_handle_channel (dispatcher, channel);
992   }
993
994   if (!tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TEXT) &&
995       handle_type == TP_HANDLE_TYPE_ROOM)
996     {
997       /* Add the chatroom to the chatroom manager */
998       EmpathyChatroom *chatroom;
999       GArray *handles;
1000       gchar **room_ids;
1001       MissionControl *mc;
1002       McAccount *account;
1003       dispatcher_connection_invalidated_cb_ctx *ctx;
1004
1005       handles = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), 1);
1006       g_array_append_val (handles, handle);
1007
1008       tp_cli_connection_run_inspect_handles (connection, -1,
1009           TP_HANDLE_TYPE_ROOM, handles, &room_ids, NULL, NULL);
1010
1011       mc = empathy_mission_control_new ();
1012       account = mission_control_get_account_for_tpconnection (mc, connection,
1013           NULL);
1014
1015       chatroom = empathy_chatroom_manager_find (priv->chatroom_mgr, account,
1016           room_ids[0]);
1017       if (chatroom == NULL)
1018         {
1019           chatroom = empathy_chatroom_new (account);
1020           empathy_chatroom_set_name (chatroom, room_ids[0]);
1021           empathy_chatroom_set_room (chatroom, room_ids[0]);
1022           empathy_chatroom_manager_add (priv->chatroom_mgr, chatroom);
1023         }
1024       else
1025         {
1026           g_object_ref (chatroom);
1027         }
1028
1029       g_object_set (chatroom, "tp-channel", channel, NULL);
1030
1031       ctx = dispatcher_connection_invalidated_cb_ctx_new (dispatcher, chatroom);
1032
1033       g_signal_connect_data (channel, "invalidated",
1034           G_CALLBACK (dispatcher_chatroom_invalidated_cb), ctx,
1035           (GClosureNotify) dispatcher_connection_invalidated_cb_ctx_free, 0);
1036
1037       g_free (room_ids[0]);
1038       g_free (room_ids);
1039       g_array_free (handles, TRUE);
1040       g_object_unref (mc);
1041       g_object_unref (account);
1042       g_object_unref (chatroom);
1043     }
1044
1045         if (suppress_handler) {
1046                 g_signal_emit (dispatcher, signals[DISPATCH_CHANNEL], 0, channel);
1047         } else {
1048                 g_signal_emit (dispatcher, signals[FILTER_CHANNEL], 0, channel);
1049         }
1050
1051         g_object_unref (channel);
1052
1053 }
1054 #endif
1055
1056 static void
1057 dispatcher_connection_got_channels_property (TpProxy *proxy,
1058   const GValue *channels_prop, const GError *error, gpointer user_data,
1059   GObject *object)
1060 {
1061   GPtrArray *channels;
1062
1063   if (error) {
1064     DEBUG ("Error: %s", error->message);
1065     return;
1066   }
1067
1068   channels = g_value_get_boxed (channels_prop);
1069   dispatcher_connection_new_channels_cb (TP_CONNECTION (proxy),
1070     channels, NULL, object);
1071 }
1072
1073 static void
1074 dispatcher_connection_list_channels_cb (TpConnection    *connection,
1075                                         const GPtrArray *channels,
1076                                         const GError    *error,
1077                                         gpointer         user_data,
1078                                         GObject         *dispatcher)
1079 {
1080         int i;
1081
1082         if (error) {
1083                 DEBUG ("Error: %s", error->message);
1084                 return;
1085         }
1086
1087         for (i = 0; i < channels->len; i++) {
1088                 GValueArray *values;
1089
1090                 values = g_ptr_array_index (channels, i);
1091                 /* We don't have any extra info, so assume already existing channels are
1092                  * incoming... */
1093                 dispatcher_connection_new_channel (EMPATHY_DISPATCHER (dispatcher),
1094                         connection,
1095                         g_value_get_boxed (g_value_array_get_nth (values, 0)),
1096                         g_value_get_string (g_value_array_get_nth (values, 1)),
1097                         g_value_get_uint (g_value_array_get_nth (values, 2)),
1098                         g_value_get_uint (g_value_array_get_nth (values, 3)),
1099                         NULL, TRUE);
1100         }
1101 }
1102
1103 static void
1104 dispatcher_connection_advertise_capabilities_cb (TpConnection    *connection,
1105                                                  const GPtrArray *capabilities,
1106                                                  const GError    *error,
1107                                                  gpointer         user_data,
1108                                                  GObject         *dispatcher)
1109 {
1110         if (error) {
1111                 DEBUG ("Error: %s", error->message);
1112         }
1113 }
1114
1115 static void
1116 dispatcher_connection_ready_cb (TpConnection  *connection,
1117   const GError *error, gpointer       dispatcher)
1118 {
1119   GPtrArray   *capabilities;
1120   GType        cap_type;
1121   GValue       cap = {0, };
1122   const gchar *remove = NULL;
1123
1124   if (error)
1125     {
1126       dispatcher_connection_invalidated_cb (connection, error->domain,
1127         error->code, error->message, dispatcher);
1128       return;
1129     }
1130
1131   g_signal_connect (connection, "invalidated",
1132     G_CALLBACK (dispatcher_connection_invalidated_cb), dispatcher);
1133
1134
1135   if (tp_proxy_has_interface_by_id (TP_PROXY (connection),
1136       TP_IFACE_QUARK_CONNECTION_INTERFACE_REQUESTS))
1137     {
1138       tp_cli_connection_interface_requests_connect_to_new_channels (connection,
1139         dispatcher_connection_new_channels_cb,
1140         NULL, NULL, G_OBJECT (dispatcher), NULL);
1141
1142       tp_cli_dbus_properties_call_get (connection, -1,
1143         TP_IFACE_CONNECTION_INTERFACE_REQUESTS, "Channels",
1144         dispatcher_connection_got_channels_property,
1145         NULL, NULL, dispatcher);
1146     }
1147   else
1148     {
1149       tp_cli_connection_connect_to_new_channel (connection,
1150         dispatcher_connection_new_channel_cb,
1151         NULL, NULL, G_OBJECT (dispatcher), NULL);
1152
1153       tp_cli_connection_call_list_channels (connection, -1,
1154         dispatcher_connection_list_channels_cb, NULL, NULL,
1155         G_OBJECT (dispatcher));
1156
1157     }
1158
1159   /* Advertise VoIP capabilities */
1160   capabilities = g_ptr_array_sized_new (1);
1161   cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
1162     G_TYPE_UINT, G_TYPE_INVALID);
1163   g_value_init (&cap, cap_type);
1164   g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
1165   dbus_g_type_struct_set (&cap,
1166         0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
1167         1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
1168            TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
1169            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
1170            TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P, G_MAXUINT);
1171   g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
1172
1173   tp_cli_connection_interface_capabilities_call_advertise_capabilities (
1174     connection, -1, capabilities, &remove,
1175     dispatcher_connection_advertise_capabilities_cb,
1176     NULL, NULL, G_OBJECT (dispatcher));
1177 }
1178
1179 static void
1180 dispatcher_update_account (EmpathyDispatcher *dispatcher, McAccount *account)
1181 {
1182   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1183   TpConnection *connection;
1184
1185   connection = g_hash_table_lookup (priv->accounts, account);
1186   if  (connection != NULL)
1187     return;
1188
1189   connection = mission_control_get_tpconnection (priv->mc, account, NULL);
1190   if (connection == NULL)
1191     return;
1192
1193   g_hash_table_insert (priv->connections, g_object_ref (connection),
1194     new_connection_data (account));
1195
1196   g_hash_table_insert (priv->accounts, g_object_ref (account),
1197     g_object_ref (connection));
1198
1199   tp_connection_call_when_ready (connection, dispatcher_connection_ready_cb,
1200     dispatcher);
1201 }
1202
1203 static void
1204 dispatcher_account_connection_cb (EmpathyAccountManager *manager,
1205   McAccount *account, TpConnectionStatusReason reason,
1206   TpConnectionStatus status, TpConnectionStatus previous,
1207   EmpathyDispatcher *dispatcher)
1208 {
1209   dispatcher_update_account (dispatcher, account);
1210 }
1211
1212 static void
1213 dispatcher_finalize (GObject *object)
1214 {
1215   EmpathyDispatcherPriv *priv = GET_PRIV (object);
1216
1217   g_signal_handlers_disconnect_by_func (priv->account_manager,
1218       dispatcher_account_connection_cb, object);
1219
1220   g_object_unref (priv->account_manager);
1221   g_object_unref (priv->mc);
1222
1223   g_hash_table_destroy (priv->connections);
1224
1225   g_object_unref (priv->chatroom_mgr);
1226 }
1227
1228 static void
1229 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
1230 {
1231   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1232
1233   object_class->finalize = dispatcher_finalize;
1234
1235   signals[OBSERVE] =
1236     g_signal_new ("observe",
1237       G_TYPE_FROM_CLASS (klass),
1238       G_SIGNAL_RUN_LAST,
1239       0,
1240       NULL, NULL,
1241       g_cclosure_marshal_VOID__OBJECT,
1242       G_TYPE_NONE,
1243       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1244
1245   signals[APPROVE] =
1246     g_signal_new ("approve",
1247       G_TYPE_FROM_CLASS (klass),
1248       G_SIGNAL_RUN_LAST,
1249       0,
1250       NULL, NULL,
1251       g_cclosure_marshal_VOID__OBJECT,
1252       G_TYPE_NONE,
1253       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1254
1255   signals[DISPATCH] =
1256     g_signal_new ("dispatch",
1257       G_TYPE_FROM_CLASS (klass),
1258       G_SIGNAL_RUN_LAST,
1259       0,
1260       NULL, NULL,
1261       g_cclosure_marshal_VOID__OBJECT,
1262       G_TYPE_NONE,
1263       1, EMPATHY_TYPE_DISPATCH_OPERATION);
1264
1265   g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
1266
1267 }
1268
1269 static void
1270 empathy_dispatcher_init (EmpathyDispatcher *dispatcher)
1271 {
1272   GList *accounts, *l;
1273   EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (dispatcher,
1274     EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
1275
1276   dispatcher->priv = priv;
1277   priv->mc = empathy_mission_control_new ();
1278   priv->account_manager = empathy_account_manager_dup_singleton ();
1279
1280   g_signal_connect (priv->account_manager,
1281     "account-connection-changed",
1282     G_CALLBACK (dispatcher_account_connection_cb),
1283     dispatcher);
1284
1285   priv->accounts = g_hash_table_new_full (empathy_account_hash,
1286         empathy_account_equal, g_object_unref, g_object_unref);
1287
1288   priv->connections = g_hash_table_new_full (g_direct_hash, g_direct_equal,
1289     g_object_unref, (GDestroyNotify) free_connection_data);
1290
1291   accounts = mc_accounts_list_by_enabled (TRUE);
1292
1293   for (l = accounts; l; l = l->next) {
1294     dispatcher_update_account (dispatcher, l->data);
1295     g_object_unref (l->data);
1296   }
1297   g_list_free (accounts);
1298
1299   priv->chatroom_mgr = empathy_chatroom_manager_new (NULL);
1300 }
1301
1302 EmpathyDispatcher *
1303 empathy_get_dispatcher (void)
1304 {
1305   if (!dispatcher) {
1306     dispatcher = g_object_new (EMPATHY_TYPE_DISPATCHER, NULL);
1307     g_object_add_weak_pointer (G_OBJECT (dispatcher), (gpointer) &dispatcher);
1308   } else {
1309     g_object_ref (dispatcher);
1310   }
1311
1312   return dispatcher;
1313 }
1314
1315 static void
1316 dispatcher_request_channel_cb (TpConnection *connection,
1317   const gchar  *object_path, const GError *error,
1318   gpointer      user_data, GObject      *weak_object)
1319 {
1320   DispatcherRequestData *request_data = (DispatcherRequestData*) user_data;
1321   EmpathyDispatcherPriv *priv = GET_PRIV (request_data->dispatcher);
1322   EmpathyDispatchOperation *operation = NULL;
1323   ConnectionData *conn_data;
1324
1325   conn_data = g_hash_table_lookup (priv->connections,
1326     request_data->connection);
1327
1328   if (error)
1329     {
1330       DEBUG ("Channel request failed: %s", error->message);
1331
1332       if (request_data->cb != NULL)
1333           request_data->cb (NULL, error, request_data->user_data);
1334
1335       conn_data->outstanding_requests =
1336         g_list_remove (conn_data->outstanding_requests, request_data);
1337       free_dispatcher_request_data (request_data);
1338
1339       goto out;
1340   }
1341
1342   operation = g_hash_table_lookup (conn_data->outstanding_channels,
1343     object_path);
1344
1345   if (operation != NULL)
1346     g_hash_table_remove (conn_data->outstanding_channels, object_path);
1347   else
1348     operation = g_hash_table_lookup (conn_data->dispatching_channels,
1349         object_path);
1350
1351   /* FIXME check if we got an existing channel back */
1352   if (operation == NULL)
1353     {
1354       DispatchData *data = g_hash_table_lookup (conn_data->dispatched_channels,
1355         object_path);
1356
1357       if (data != NULL)
1358         {
1359           operation = empathy_dispatch_operation_new_with_wrapper (connection,
1360             data->channel, request_data->contact, FALSE,
1361             data->channel_wrapper);
1362         }
1363       else
1364         {
1365           TpChannel *channel = tp_channel_new (connection, object_path,
1366             request_data->channel_type, request_data->handle_type,
1367             request_data->handle, NULL);
1368
1369           g_signal_connect (channel, "invalidated",
1370             G_CALLBACK (dispatcher_channel_invalidated_cb),
1371             request_data->dispatcher);
1372
1373           operation = empathy_dispatch_operation_new (connection, channel,
1374             request_data->contact, FALSE);
1375           g_object_unref (channel);
1376         }
1377     }
1378   else
1379     {
1380       /* Already existed set potential extra information */
1381       g_object_set (G_OBJECT (operation),
1382         "contact", request_data->contact,
1383         NULL);
1384     }
1385
1386   request_data->operation = operation;
1387
1388   /* (pre)-approve this right away as we requested it */
1389   empathy_dispatch_operation_approve (operation);
1390
1391   dispatcher_start_dispatching (request_data->dispatcher, operation,
1392         conn_data);
1393 out:
1394   dispatcher_flush_outstanding_operations (request_data->dispatcher,
1395     conn_data);
1396 }
1397
1398 void
1399 empathy_dispatcher_call_with_contact ( EmpathyContact *contact,
1400   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1401 {
1402   g_assert_not_reached ();
1403 }
1404
1405 void
1406 empathy_dispatcher_call_with_contact_id (McAccount *account,
1407   const gchar  *contact_id, EmpathyDispatcherRequestCb *callback,
1408   gpointer user_data)
1409 {
1410   g_assert_not_reached ();
1411 }
1412
1413 static void
1414 dispatcher_chat_with_contact_cb (EmpathyContact *contact, gpointer user_data)
1415 {
1416   DispatcherRequestData *request_data = (DispatcherRequestData *) user_data;
1417
1418   request_data->handle = empathy_contact_get_handle (contact);
1419
1420   /* Note this does rape the surpress handler semantics */
1421   tp_cli_connection_call_request_channel (request_data->connection, -1,
1422     request_data->channel_type,
1423     request_data->handle_type,
1424     request_data->handle,
1425     TRUE, dispatcher_request_channel_cb,
1426     request_data, NULL, NULL);
1427 }
1428
1429 void
1430 empathy_dispatcher_chat_with_contact (EmpathyContact *contact,
1431   EmpathyDispatcherRequestCb *callback, gpointer user_data)
1432 {
1433   EmpathyDispatcher *dispatcher = empathy_get_dispatcher();
1434   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
1435   McAccount *account = empathy_contact_get_account (contact);
1436   TpConnection *connection = g_hash_table_lookup (priv->accounts, account);
1437   ConnectionData *connection_data =
1438     g_hash_table_lookup (priv->connections, connection);
1439   DispatcherRequestData *request_data;
1440
1441   /* The contact handle might not be known yet */
1442   request_data  = new_dispatcher_request_data (dispatcher, connection,
1443     TP_IFACE_CHANNEL_TYPE_TEXT, TP_HANDLE_TYPE_CONTACT, 0, NULL,
1444     contact, callback, user_data);
1445
1446   connection_data->outstanding_requests = g_list_prepend
1447     (connection_data->outstanding_requests, request_data);
1448
1449   empathy_contact_call_when_ready (contact,
1450     EMPATHY_CONTACT_READY_HANDLE, dispatcher_chat_with_contact_cb,
1451     request_data);
1452
1453   g_object_unref (dispatcher);
1454 }
1455
1456 void
1457 empathy_dispatcher_chat_with_contact_id (McAccount *account, const gchar
1458   *contact_id, EmpathyDispatcherRequestCb *callback, gpointer user_data)
1459 {
1460   EmpathyDispatcher *dispatcher = empathy_get_dispatcher ();
1461   EmpathyContactFactory *factory;
1462   EmpathyContact        *contact;
1463
1464   factory = empathy_contact_factory_dup_singleton ();
1465   contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
1466
1467   empathy_dispatcher_chat_with_contact (contact, callback, user_data);
1468
1469   g_object_unref (contact);
1470   g_object_unref (factory);
1471   g_object_unref (dispatcher);
1472 }
1473
1474 #if 0
1475 typedef struct {
1476         GFile *gfile;
1477         TpHandle handle;
1478 } FileChannelRequest;
1479
1480 static void
1481 tp_file_state_notify_cb (EmpathyTpFile *tp_file)
1482 {
1483         EmpFileTransferState state;
1484
1485         state = empathy_tp_file_get_state (tp_file, NULL);
1486         if (state == EMP_FILE_TRANSFER_STATE_COMPLETED ||
1487             state == EMP_FILE_TRANSFER_STATE_CANCELLED) {
1488                 DEBUG ("Transfer is done, unref the object");
1489                 g_object_unref (tp_file);
1490         }
1491 }
1492
1493 static void
1494 file_channel_create_cb (TpConnection *connection,
1495                         const gchar  *object_path,
1496                         GHashTable   *properties,
1497                         const GError *error,
1498                         gpointer      user_data,
1499                         GObject      *weak_object)
1500 {
1501         TpChannel *channel;
1502         EmpathyTpFile *tp_file;
1503         FileChannelRequest *request = (FileChannelRequest *) user_data;
1504
1505         if (error) {
1506                 DEBUG ("Couldn't request channel: %s", error->message);
1507                 return;
1508         }
1509
1510         channel = tp_channel_new (connection,
1511                                  object_path,
1512                                  EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER,
1513                                  TP_HANDLE_TYPE_CONTACT,
1514                                  request->handle,
1515                                  NULL);
1516
1517         /* We give the ref to the callback, it is responsible to unref the
1518          * object once the transfer is done. */
1519         tp_file = empathy_tp_file_new (channel);
1520         empathy_tp_file_offer (tp_file, request->gfile, NULL);
1521         g_signal_connect (tp_file, "notify::state",
1522                           G_CALLBACK (tp_file_state_notify_cb),
1523                           NULL);
1524
1525         g_object_unref (request->gfile);
1526         g_slice_free (FileChannelRequest, request);
1527         g_object_unref (channel);
1528 }
1529
1530 #endif
1531
1532 void
1533 empathy_dispatcher_send_file (EmpathyContact *contact,
1534                               GFile          *gfile)
1535 {
1536   g_assert_not_reached();
1537   return;
1538 }
1539
1540 #if 0
1541         MissionControl     *mc;
1542         McAccount          *account;
1543         TpConnection       *connection;
1544         guint               handle;
1545         FileChannelRequest *request;
1546         GHashTable         *args;
1547         GValue             *value;
1548         GFileInfo          *info;
1549         gchar              *filename;
1550         GTimeVal            last_modif;
1551         GError             *error = NULL;
1552
1553         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1554         g_return_if_fail (G_IS_FILE (gfile));
1555
1556         info = g_file_query_info (gfile,
1557                                   G_FILE_ATTRIBUTE_STANDARD_SIZE ","
1558                                   G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
1559                                   G_FILE_ATTRIBUTE_TIME_MODIFIED,
1560                                   0, NULL, &error);
1561
1562         if (error) {
1563                 DEBUG ("Can't get info about the file: %s", error->message);
1564                 g_clear_error (&error);
1565                 return;
1566         }
1567
1568         mc = empathy_mission_control_new ();
1569         account = empathy_contact_get_account (contact);
1570         connection = mission_control_get_tpconnection (mc, account, NULL);
1571         handle = empathy_contact_get_handle (contact);
1572
1573         request = g_slice_new0 (FileChannelRequest);
1574         request->gfile = g_object_ref (gfile);
1575         request->handle = handle;
1576
1577         filename = g_file_get_basename (request->gfile);
1578         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
1579
1580         DEBUG ("Sending %s from a stream to %s (size %"G_GINT64_FORMAT", content-type %s)",
1581                filename, empathy_contact_get_name (contact),
1582                g_file_info_get_size (info),
1583                g_file_info_get_content_type (info));
1584
1585         args = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
1586                                       (GDestroyNotify) tp_g_value_slice_free);
1587
1588         /* org.freedesktop.Telepathy.Channel.ChannelType */
1589         value = tp_g_value_slice_new (G_TYPE_STRING);
1590         g_value_set_string (value, EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
1591         g_hash_table_insert (args, TP_IFACE_CHANNEL ".ChannelType", value);
1592
1593         /* org.freedesktop.Telepathy.Channel.TargetHandleType */
1594         value = tp_g_value_slice_new (G_TYPE_UINT);
1595         g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
1596         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandleType", value);
1597
1598         /* org.freedesktop.Telepathy.Channel.TargetHandle */
1599         value = tp_g_value_slice_new (G_TYPE_UINT);
1600         g_value_set_uint (value, handle);
1601         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandle", value);
1602
1603         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
1604         value = tp_g_value_slice_new (G_TYPE_STRING);
1605         g_value_set_string (value, g_file_info_get_content_type (info));
1606         g_hash_table_insert (args,
1607                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
1608
1609         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
1610         value = tp_g_value_slice_new (G_TYPE_STRING);
1611         g_value_set_string (value, g_filename_display_basename (filename));
1612         g_hash_table_insert (args,
1613                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
1614
1615         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
1616         value = tp_g_value_slice_new (G_TYPE_UINT64);
1617         g_value_set_uint64 (value, g_file_info_get_size (info));
1618         g_hash_table_insert (args,
1619                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
1620
1621         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
1622         g_file_info_get_modification_time (info, &last_modif);
1623         value = tp_g_value_slice_new (G_TYPE_UINT64);
1624         g_value_set_uint64 (value, last_modif.tv_sec);
1625         g_hash_table_insert (args,
1626                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
1627
1628         /* FIXME: Description ? */
1629         /* FIXME: ContentHashType and ContentHash ? */
1630
1631         tp_cli_connection_interface_requests_call_create_channel (connection, -1,
1632                 args, file_channel_create_cb, request, NULL, NULL);
1633
1634         g_hash_table_destroy (args);
1635         g_free (filename);
1636         g_object_unref (mc);
1637         g_object_unref (connection);
1638 }
1639
1640 #endif