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