]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
Little fix for previous commit.
[empathy.git] / libempathy / empathy-dispatcher.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2007-2008 Collabora Ltd.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  * 
19  * Authors: Xavier Claessens <xclaesse@gmail.com>
20  */
21
22 #include <config.h>
23
24 #include <string.h>
25
26 #include <glib/gi18n.h>
27
28 #include <telepathy-glib/enums.h>
29 #include <telepathy-glib/connection.h>
30 #include <telepathy-glib/util.h>
31 #include <telepathy-glib/dbus.h>
32 #include <telepathy-glib/proxy-subclass.h>
33
34 #include <libmissioncontrol/mission-control.h>
35 #include <libmissioncontrol/mc-account.h>
36
37 #include <extensions/extensions.h>
38
39 #include "empathy-dispatcher.h"
40 #include "empathy-utils.h"
41 #include "empathy-tube-handler.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         GHashTable     *connections;
54         gpointer        token;
55         MissionControl *mc;
56         GSList         *tubes;
57   EmpathyChatroomManager *chatroom_mgr;
58 } EmpathyDispatcherPriv;
59
60 G_DEFINE_TYPE (EmpathyDispatcher, empathy_dispatcher, G_TYPE_OBJECT);
61
62 enum {
63         DISPATCH_CHANNEL,
64         FILTER_CHANNEL,
65         FILTER_TUBE,
66         LAST_SIGNAL
67 };
68
69 static guint signals[LAST_SIGNAL];
70 static EmpathyDispatcher *dispatcher = NULL;
71
72 void
73 empathy_dispatcher_channel_process (EmpathyDispatcher *dispatcher,
74                                     TpChannel         *channel)
75 {
76         g_signal_emit (dispatcher, signals[DISPATCH_CHANNEL], 0, channel);
77 }
78
79 typedef struct {
80         EmpathyDispatcherTube  public;
81         EmpathyContactFactory *factory;
82         gchar                 *bus_name;
83         gchar                 *object_path;
84         guint                  ref_count;
85         gboolean               handled;
86 } DispatcherTube;
87
88 GType
89 empathy_dispatcher_tube_get_type (void)
90 {
91         static GType type_id = 0;
92
93         if (!type_id) {
94                 type_id = g_boxed_type_register_static ("EmpathyDispatcherTube",
95                                                         (GBoxedCopyFunc) empathy_dispatcher_tube_ref,
96                                                         (GBoxedFreeFunc) empathy_dispatcher_tube_unref);
97         }
98
99         return type_id;
100 }
101
102 EmpathyDispatcherTube *
103 empathy_dispatcher_tube_ref (EmpathyDispatcherTube *data)
104 {
105         DispatcherTube *tube = (DispatcherTube*) data;
106
107         g_return_val_if_fail (tube != NULL, NULL);
108
109         tube->ref_count++;
110
111         return data;
112 }
113
114 void
115 empathy_dispatcher_tube_unref (EmpathyDispatcherTube *data)
116 {
117         DispatcherTube *tube = (DispatcherTube*) data;
118
119         g_return_if_fail (tube != NULL);
120
121         if (--tube->ref_count == 0) {
122                 if (!tube->handled) {
123                         DEBUG ("Tube can't be handled, closing");
124                         tp_cli_channel_type_tubes_call_close_tube (tube->public.channel, -1,
125                                                                    tube->public.id,
126                                                                    NULL, NULL, NULL,
127                                                                    NULL);
128                 }
129
130                 g_free (tube->bus_name);
131                 g_free (tube->object_path);
132                 g_object_unref (tube->factory);
133                 g_object_unref (tube->public.channel);
134                 g_object_unref (tube->public.initiator);
135                 g_slice_free (DispatcherTube, tube);
136         }
137 }
138
139 static void
140 dispatcher_tubes_handle_tube_cb (TpProxy      *channel,
141                                  const GError *error,
142                                  gpointer      user_data,
143                                  GObject      *dispatcher)
144 {
145         DispatcherTube *tube = user_data;
146
147         if (error) {
148                 DEBUG ("Error: %s", error->message);
149         } else {
150                 tube->handled = TRUE;
151         }
152 }
153
154 void
155 empathy_dispatcher_tube_process (EmpathyDispatcher     *dispatcher,
156                                  EmpathyDispatcherTube *user_data)
157 {
158         DispatcherTube *tube = (DispatcherTube*) user_data;
159
160         if (tube->public.activatable) {
161                 TpProxy *connection;
162                 TpProxy *thandler;
163                 gchar   *object_path;
164                 guint    handle_type;
165                 guint    handle;
166
167                 /* Create the proxy for the tube handler */
168                 thandler = g_object_new (TP_TYPE_PROXY,
169                                          "dbus-connection", tp_get_bus (),
170                                          "bus-name", tube->bus_name,
171                                          "object-path", tube->object_path,
172                                          NULL);
173                 tp_proxy_add_interface_by_id (thandler, EMP_IFACE_QUARK_TUBE_HANDLER);
174
175                 /* Give the tube to the handler */
176                 g_object_get (tube->public.channel,
177                               "connection", &connection,
178                               "object-path", &object_path,
179                               "handle_type", &handle_type,
180                               "handle", &handle,
181                               NULL);
182
183                 DEBUG ("Dispatching tube");
184                 emp_cli_tube_handler_call_handle_tube (thandler, -1,
185                                                        connection->bus_name,
186                                                        connection->object_path,
187                                                        object_path, handle_type,
188                                                        handle, tube->public.id,
189                                                        dispatcher_tubes_handle_tube_cb,
190                                                        empathy_dispatcher_tube_ref (user_data),
191                                                        (GDestroyNotify) empathy_dispatcher_tube_unref,
192                                                        G_OBJECT (dispatcher));
193
194                 g_object_unref (thandler);
195                 g_object_unref (connection);
196                 g_free (object_path);
197         }
198 }
199
200 static void
201 dispatcher_tubes_new_tube_cb (TpChannel   *channel,
202                               guint        id,
203                               guint        initiator,
204                               guint        type,
205                               const gchar *service,
206                               GHashTable  *parameters,
207                               guint        state,
208                               gpointer     user_data,
209                               GObject     *dispatcher)
210 {
211         static TpDBusDaemon   *daemon = NULL;
212         DispatcherTube        *tube;
213         McAccount             *account;
214         guint                  number;
215         gchar                **names;
216         gboolean               running = FALSE;
217         GError                *error = NULL;
218
219         /* Increase tube count */
220         number = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (channel), "tube-count"));
221         g_object_set_data (G_OBJECT (channel), "tube-count", GUINT_TO_POINTER (++number));
222         DEBUG ("Increased tube count for channel %p: %d", channel, number);
223
224         /* We dispatch only local pending tubes */
225         if (state != TP_TUBE_STATE_LOCAL_PENDING) {
226                 return;
227         }
228
229         if (!daemon) {
230                 daemon = tp_dbus_daemon_new (tp_get_bus ());
231         }
232
233         account = empathy_channel_get_account (channel);
234         tube = g_slice_new (DispatcherTube);
235         tube->ref_count = 1;
236         tube->handled = FALSE;
237         tube->factory = empathy_contact_factory_new ();
238         tube->bus_name = empathy_tube_handler_build_bus_name (type, service);
239         tube->object_path = empathy_tube_handler_build_object_path (type, service);
240         tube->public.activatable = FALSE;
241         tube->public.id = id;
242         tube->public.channel = g_object_ref (channel);
243         tube->public.initiator = empathy_contact_factory_get_from_handle (tube->factory,
244                                                                           account,
245                                                                           initiator);
246         g_object_unref (account);
247
248         /* Check if that bus-name has an owner, if it has one that means the
249          * app is already running and we can directly give the channel. */
250         tp_cli_dbus_daemon_run_name_has_owner (daemon, -1, tube->bus_name,
251                                                &running, NULL, NULL);
252         if (running) {
253                 DEBUG ("Tube handler running");
254                 tube->public.activatable = TRUE;
255                 empathy_dispatcher_tube_process (EMPATHY_DISPATCHER (dispatcher),
256                                                  (EmpathyDispatcherTube*) tube);
257                 empathy_dispatcher_tube_unref ((EmpathyDispatcherTube*) tube);
258                 return;
259         }
260
261         /* Check if that bus-name is activatable, if not that means the
262          * application needed to handle this tube isn't installed. */
263         if (!tp_cli_dbus_daemon_run_list_activatable_names (daemon, -1,
264                                                             &names, &error,
265                                                             NULL)) {
266                 DEBUG ("Error listing activatable names: %s", error->message);
267                 g_clear_error (&error);
268         } else {
269                 gchar **name;
270
271                 for (name = names; *name; name++) {
272                         if (!tp_strdiff (*name, tube->bus_name)) {
273                                 tube->public.activatable = TRUE;
274                                 break;
275                         }
276                 }
277                 g_strfreev (names);
278         }
279
280         g_signal_emit (dispatcher, signals[FILTER_TUBE], 0, tube);
281         empathy_dispatcher_tube_unref ((EmpathyDispatcherTube*) tube);
282 }
283
284 static void
285 dispatcher_tubes_list_tubes_cb (TpChannel       *channel,
286                                 const GPtrArray *tubes,
287                                 const GError    *error,
288                                 gpointer         user_data,
289                                 GObject         *dispatcher)
290 {
291         guint i;
292
293         if (error) {
294                 DEBUG ("Error: %s", error->message);
295                 return;
296         }
297
298         for (i = 0; i < tubes->len; i++) {
299                 GValueArray *values;
300
301                 values = g_ptr_array_index (tubes, i);
302                 dispatcher_tubes_new_tube_cb (channel,
303                                               g_value_get_uint (g_value_array_get_nth (values, 0)),
304                                               g_value_get_uint (g_value_array_get_nth (values, 1)),
305                                               g_value_get_uint (g_value_array_get_nth (values, 2)),
306                                               g_value_get_string (g_value_array_get_nth (values, 3)),
307                                               g_value_get_boxed (g_value_array_get_nth (values, 4)),
308                                               g_value_get_uint (g_value_array_get_nth (values, 5)),
309                                               user_data, dispatcher);
310         }
311 }
312
313 static void
314 dispatcher_tubes_channel_invalidated_cb (TpProxy           *proxy,
315                                          guint              domain,
316                                          gint               code,
317                                          gchar             *message,
318                                          EmpathyDispatcher *dispatcher)
319 {
320         EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
321
322         DEBUG ("%s", message);
323
324         priv->tubes = g_slist_remove (priv->tubes, proxy);
325         g_object_unref (proxy);
326 }
327
328 static void
329 dispatcher_tubes_tube_closed_cb (TpChannel *channel,
330                                  guint      id,
331                                  gpointer   user_data,
332                                  GObject   *dispatcher)
333 {
334         guint number;
335
336         number = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (channel), "tube-count"));
337         if (number == 1) {
338                 DEBUG ("No more tube, closing channel");
339                 tp_cli_channel_call_close (channel, -1, NULL, NULL, NULL, NULL);
340         }
341         else if (number > 1) {
342                 DEBUG ("Decrease tube count: %d", number);
343                 g_object_set_data (G_OBJECT (channel), "tube-count", GUINT_TO_POINTER (--number));
344         }
345 }
346
347 static void
348 dispatcher_tubes_handle_channel (EmpathyDispatcher *dispatcher,
349                                  TpChannel         *channel)
350 {
351         EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
352
353         DEBUG ("Called");
354
355         priv->tubes = g_slist_prepend (priv->tubes, g_object_ref (channel));
356         g_signal_connect (channel, "invalidated",
357                           G_CALLBACK (dispatcher_tubes_channel_invalidated_cb),
358                           dispatcher);
359
360         tp_cli_channel_type_tubes_connect_to_tube_closed (channel,
361                                                           dispatcher_tubes_tube_closed_cb,
362                                                           NULL, NULL,
363                                                           G_OBJECT (dispatcher), NULL);
364         tp_cli_channel_type_tubes_connect_to_new_tube (channel,
365                                                        dispatcher_tubes_new_tube_cb,
366                                                        NULL, NULL,
367                                                        G_OBJECT (dispatcher), NULL);
368         tp_cli_channel_type_tubes_call_list_tubes (channel, -1,
369                                                    dispatcher_tubes_list_tubes_cb,
370                                                    NULL, NULL,
371                                                    G_OBJECT (dispatcher));
372 }
373
374 static void
375 dispatcher_connection_invalidated_cb (TpConnection  *connection,
376                                       guint          domain,
377                                       gint           code,
378                                       gchar         *message,
379                                       EmpathyDispatcher *dispatcher)
380 {
381         EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
382         GHashTableIter         iter;
383         gpointer               key, value;
384
385         DEBUG ("Error: %s", message);
386
387         g_hash_table_iter_init (&iter, priv->connections);
388         while (g_hash_table_iter_next (&iter, &key, &value)) {
389                 if (value == connection) {
390                         g_hash_table_remove (priv->connections, key);
391                         break;
392                 }
393         }
394 }
395
396 typedef struct
397 {
398   EmpathyDispatcher *self;
399   EmpathyChatroom *chatroom;
400 } dispatcher_connection_invalidated_cb_ctx;
401
402 static dispatcher_connection_invalidated_cb_ctx *
403 dispatcher_connection_invalidated_cb_ctx_new (EmpathyDispatcher *dispatcher,
404                                               EmpathyChatroom *chatroom)
405 {
406   dispatcher_connection_invalidated_cb_ctx *ctx;
407
408   ctx = g_slice_new (dispatcher_connection_invalidated_cb_ctx);
409
410   ctx->self = g_object_ref (dispatcher);
411   ctx->chatroom = g_object_ref (chatroom);
412
413   return ctx;
414 }
415
416 static void
417 dispatcher_connection_invalidated_cb_ctx_free (
418     dispatcher_connection_invalidated_cb_ctx *ctx)
419 {
420   g_object_unref (ctx->self);
421   g_object_unref (ctx->chatroom);
422
423   g_slice_free (dispatcher_connection_invalidated_cb_ctx, ctx);
424 }
425
426 static void dispatcher_chatroom_invalidated_cb (
427     TpProxy *channel,
428     guint domain,
429     gint code,
430     gchar *message,
431     dispatcher_connection_invalidated_cb_ctx *ctx)
432 {
433   EmpathyDispatcherPriv *priv = GET_PRIV (ctx->self);
434   gboolean favorite;
435
436   g_object_get (ctx->chatroom, "favorite", &favorite, NULL);
437
438   if (favorite)
439     {
440       /* Chatroom is in favorites so don't remove it from the manager */
441       g_object_set (ctx->chatroom, "tp-channel", NULL, NULL);
442     }
443   else
444     {
445       empathy_chatroom_manager_remove (priv->chatroom_mgr, ctx->chatroom);
446     }
447 }
448
449 static void
450 dispatcher_connection_new_channel_cb (TpConnection *connection,
451                                       const gchar  *object_path,
452                                       const gchar  *channel_type,
453                                       guint         handle_type,
454                                       guint         handle,
455                                       gboolean      suppress_handler,
456                                       gpointer      user_data,
457                                       GObject      *object)
458 {
459         EmpathyDispatcher *dispatcher = EMPATHY_DISPATCHER (object);
460   EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
461         TpChannel         *channel;
462         gpointer           had_channels;
463
464         had_channels = g_object_get_data (G_OBJECT (connection), "had-channels");
465         if (had_channels == NULL) {
466                 /* ListChannels didn't return yet, return to avoid duplicate
467                  * dispatching */
468                 return;
469         }
470
471         channel = tp_channel_new (connection, object_path, channel_type,
472                                   handle_type, handle, NULL);
473         tp_channel_run_until_ready (channel, NULL, NULL);
474
475         if (!tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TUBES)) {
476                 dispatcher_tubes_handle_channel (dispatcher, channel);
477         }
478
479   if (!tp_strdiff (channel_type, TP_IFACE_CHANNEL_TYPE_TEXT) &&
480       handle_type == TP_HANDLE_TYPE_ROOM)
481     {
482       /* Add the chatroom to the chatroom manager */
483       EmpathyChatroom *chatroom;
484       GArray *handles;
485       gchar **room_ids;
486       MissionControl *mc;
487       McAccount *account;
488       dispatcher_connection_invalidated_cb_ctx *ctx;
489
490       handles = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), 1);
491       g_array_append_val (handles, handle);
492
493       tp_cli_connection_run_inspect_handles (connection, -1,
494           TP_HANDLE_TYPE_ROOM, handles, &room_ids, NULL, NULL);
495
496       mc = empathy_mission_control_new ();
497       account = mission_control_get_account_for_tpconnection (mc, connection,
498           NULL);
499
500       chatroom = empathy_chatroom_manager_find (priv->chatroom_mgr, account,
501           room_ids[0]);
502       if (chatroom == NULL)
503         {
504           chatroom = empathy_chatroom_new (account);
505           empathy_chatroom_set_name (chatroom, room_ids[0]);
506           empathy_chatroom_set_room (chatroom, room_ids[0]);
507           empathy_chatroom_manager_add (priv->chatroom_mgr, chatroom);
508         }
509       else
510         {
511           g_object_ref (chatroom);
512         }
513
514       g_object_set (chatroom, "tp-channel", channel, NULL);
515
516       ctx = dispatcher_connection_invalidated_cb_ctx_new (dispatcher, chatroom);
517
518       g_signal_connect_data (channel, "invalidated",
519           G_CALLBACK (dispatcher_chatroom_invalidated_cb), ctx,
520           (GClosureNotify) dispatcher_connection_invalidated_cb_ctx_free, 0);
521
522       g_free (room_ids[0]);
523       g_free (room_ids);
524       g_array_free (handles, TRUE);
525       g_object_unref (mc);
526       g_object_unref (account);
527       g_object_unref (chatroom);
528     }
529
530         if (suppress_handler) {
531                 g_signal_emit (dispatcher, signals[DISPATCH_CHANNEL], 0, channel);
532         } else {
533                 g_signal_emit (dispatcher, signals[FILTER_CHANNEL], 0, channel);
534         }
535
536         g_object_unref (channel);
537 }
538
539 static void
540 dispatcher_connection_list_channels_cb (TpConnection    *connection,
541                                         const GPtrArray *channels,
542                                         const GError    *error,
543                                         gpointer         user_data,
544                                         GObject         *dispatcher)
545 {
546         guint i;
547
548         if (error) {
549                 DEBUG ("Error: %s", error->message);
550                 return;
551         }
552
553         g_object_set_data (G_OBJECT (connection), "had-channels",
554                            GUINT_TO_POINTER (1));
555
556         for (i = 0; i < channels->len; i++) {
557                 GValueArray *values;
558
559                 values = g_ptr_array_index (channels, i);
560                 dispatcher_connection_new_channel_cb (connection,
561                         g_value_get_boxed (g_value_array_get_nth (values, 0)),
562                         g_value_get_string (g_value_array_get_nth (values, 1)),
563                         g_value_get_uint (g_value_array_get_nth (values, 2)),
564                         g_value_get_uint (g_value_array_get_nth (values, 3)),
565                         FALSE, user_data, dispatcher);
566         }
567 }
568
569 static void
570 dispatcher_connection_advertise_capabilities_cb (TpConnection    *connection,
571                                                  const GPtrArray *capabilities,
572                                                  const GError    *error,
573                                                  gpointer         user_data,
574                                                  GObject         *dispatcher)
575 {
576         if (error) {
577                 DEBUG ("Error: %s", error->message);
578         }
579 }
580
581 static void
582 dispatcher_connection_ready_cb (TpConnection  *connection,
583                                 const GError  *error,
584                                 gpointer       dispatcher)
585 {
586         GPtrArray   *capabilities;
587         GType        cap_type;
588         GValue       cap = {0, };
589         const gchar *remove = NULL;
590
591         if (error) {
592                 dispatcher_connection_invalidated_cb (connection,
593                                                       error->domain,
594                                                       error->code,
595                                                       error->message,
596                                                       dispatcher);
597                 return;
598         }
599
600         g_signal_connect (connection, "invalidated",
601                           G_CALLBACK (dispatcher_connection_invalidated_cb),
602                           dispatcher);
603         tp_cli_connection_connect_to_new_channel (connection,
604                                                   dispatcher_connection_new_channel_cb,
605                                                   NULL, NULL,
606                                                   G_OBJECT (dispatcher), NULL);
607         tp_cli_connection_call_list_channels (connection, -1,
608                                               dispatcher_connection_list_channels_cb,
609                                               NULL, NULL,
610                                               G_OBJECT (dispatcher));
611
612         /* Advertise VoIP capabilities */
613         capabilities = g_ptr_array_sized_new (1);
614         cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
615                                            G_TYPE_UINT, G_TYPE_INVALID);
616         g_value_init (&cap, cap_type);
617         g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
618         dbus_g_type_struct_set (&cap,
619                                 0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
620                                 1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
621                                    TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
622                                    TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
623                                    TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P,
624                                 G_MAXUINT);
625         g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
626
627         tp_cli_connection_interface_capabilities_call_advertise_capabilities (
628                 connection, -1,
629                 capabilities, &remove,
630                 dispatcher_connection_advertise_capabilities_cb,
631                 NULL, NULL, G_OBJECT (dispatcher));
632         /* FIXME: Is that leaked? */
633 }
634
635 static void
636 dispatcher_update_account (EmpathyDispatcher *dispatcher,
637                            McAccount         *account)
638 {
639         EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
640         TpConnection          *connection;
641
642         connection = g_hash_table_lookup (priv->connections, account);
643         if (connection) {
644                 return;
645         }
646
647         connection = mission_control_get_tpconnection (priv->mc, account, NULL);
648         if (!connection) {
649                 return;
650         }
651
652         g_hash_table_insert (priv->connections, g_object_ref (account), connection);
653         tp_connection_call_when_ready (connection,
654                                        dispatcher_connection_ready_cb,
655                                        dispatcher);
656 }
657
658 static void
659 dispatcher_status_changed_cb (MissionControl           *mc,
660                               TpConnectionStatus        status,
661                               McPresence                presence,
662                               TpConnectionStatusReason  reason,
663                               const gchar              *unique_name,
664                               EmpathyDispatcher            *dispatcher)
665 {
666         McAccount *account;
667
668         account = mc_account_lookup (unique_name);
669         dispatcher_update_account (dispatcher, account);
670         g_object_unref (account);
671 }
672
673 static void
674 dispatcher_finalize (GObject *object)
675 {
676         EmpathyDispatcherPriv *priv = GET_PRIV (object);
677         GSList                *l;
678
679         empathy_disconnect_account_status_changed (priv->token);
680         g_object_unref (priv->mc);
681
682         for (l = priv->tubes; l; l = l->next) {
683                 g_signal_handlers_disconnect_by_func (l->data,
684                                                       dispatcher_tubes_channel_invalidated_cb,
685                                                       object);
686                 g_object_unref (l->data);
687         }
688         g_slist_free (priv->tubes);
689
690         g_hash_table_destroy (priv->connections);
691
692   g_object_unref (priv->chatroom_mgr);
693 }
694
695 static void
696 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
697 {
698         GObjectClass *object_class = G_OBJECT_CLASS (klass);
699
700         object_class->finalize = dispatcher_finalize;
701
702         signals[DISPATCH_CHANNEL] =
703                 g_signal_new ("dispatch-channel",
704                               G_TYPE_FROM_CLASS (klass),
705                               G_SIGNAL_RUN_LAST,
706                               0,
707                               NULL, NULL,
708                               g_cclosure_marshal_VOID__OBJECT,
709                               G_TYPE_NONE,
710                               1, TP_TYPE_CHANNEL);
711         signals[FILTER_CHANNEL] =
712                 g_signal_new ("filter-channel",
713                               G_TYPE_FROM_CLASS (klass),
714                               G_SIGNAL_RUN_LAST,
715                               0,
716                               NULL, NULL,
717                               g_cclosure_marshal_VOID__OBJECT,
718                               G_TYPE_NONE,
719                               1, TP_TYPE_CHANNEL);
720         signals[FILTER_TUBE] =
721                 g_signal_new ("filter-tube",
722                               G_TYPE_FROM_CLASS (klass),
723                               G_SIGNAL_RUN_LAST,
724                               0,
725                               NULL, NULL,
726                               g_cclosure_marshal_VOID__BOXED,
727                               G_TYPE_NONE,
728                               1, EMPATHY_TYPE_DISPATCHER_TUBE);
729
730         g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
731 }
732
733 static void
734 empathy_dispatcher_init (EmpathyDispatcher *dispatcher)
735 {
736         GList                 *accounts, *l;
737         EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (dispatcher,
738                 EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
739
740         dispatcher->priv = priv;
741         priv->mc = empathy_mission_control_new ();
742         priv->token = empathy_connect_to_account_status_changed (priv->mc,
743                 G_CALLBACK (dispatcher_status_changed_cb),
744                 dispatcher, NULL);
745
746         priv->connections = g_hash_table_new_full (empathy_account_hash,
747                                                    empathy_account_equal,
748                                                    g_object_unref,
749                                                    g_object_unref);
750         accounts = mc_accounts_list_by_enabled (TRUE);
751         for (l = accounts; l; l = l->next) {
752                 dispatcher_update_account (dispatcher, l->data);
753                 g_object_unref (l->data);
754         }
755         g_list_free (accounts);
756
757   priv->chatroom_mgr = empathy_chatroom_manager_new (NULL);
758 }
759
760 EmpathyDispatcher *
761 empathy_dispatcher_new (void)
762 {
763         if (!dispatcher) {
764                 dispatcher = g_object_new (EMPATHY_TYPE_DISPATCHER, NULL);
765                 g_object_add_weak_pointer (G_OBJECT (dispatcher), (gpointer) &dispatcher);
766         } else {
767                 g_object_ref (dispatcher);
768         }
769
770         return dispatcher;
771 }
772
773 typedef struct {
774         const gchar *channel_type;
775         guint        handle_type;
776         guint        handle;
777 } DispatcherRequestData;
778
779 static void
780 dispatcher_request_channel_cb (TpConnection *connection,
781                                const gchar  *object_path,
782                                const GError *error,
783                                gpointer      user_data,
784                                GObject      *weak_object)
785 {
786         DispatcherRequestData *data = (DispatcherRequestData*) user_data;
787
788         if (error) {
789                 DEBUG ("Error: %s", error->message);
790                 return;
791         }
792
793         if (dispatcher) {
794                 TpChannel *channel;
795
796                 channel = tp_channel_new (connection, object_path,
797                                           data->channel_type,
798                                           data->handle_type,
799                                           data->handle, NULL);
800
801                 g_signal_emit (dispatcher, signals[DISPATCH_CHANNEL], 0, channel);
802         }
803 }
804
805 void
806 empathy_dispatcher_call_with_contact (EmpathyContact *contact)
807 {
808         MissionControl        *mc;
809         McAccount             *account;
810         TpConnection          *connection;
811         gchar                 *object_path;
812         TpChannel             *channel;
813         EmpathyContactFactory *factory;
814         EmpathyTpGroup        *group;
815         EmpathyContact        *self_contact;
816         GError                *error = NULL;
817
818         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
819
820         mc = empathy_mission_control_new ();
821         account = empathy_contact_get_account (contact);
822         connection = mission_control_get_tpconnection (mc, account, NULL);
823         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
824         g_object_unref (mc);
825
826         /* We abuse of suppress_handler, TRUE means OUTGOING. The channel
827          * will be catched in EmpathyFilter */
828         if (!tp_cli_connection_run_request_channel (connection, -1,
829                                                     TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
830                                                     TP_HANDLE_TYPE_NONE,
831                                                     0,
832                                                     TRUE,
833                                                     &object_path,
834                                                     &error,
835                                                     NULL)) {
836                 DEBUG ("Couldn't request channel: %s",
837                         error ? error->message : "No error given");
838                 g_clear_error (&error);
839                 g_object_unref (connection);
840                 return;
841         }
842
843         channel = tp_channel_new (connection,
844                                   object_path, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
845                                   TP_HANDLE_TYPE_NONE, 0, NULL);
846
847         group = empathy_tp_group_new (channel);
848         empathy_run_until_ready (group);
849
850         factory = empathy_contact_factory_new ();
851         self_contact = empathy_contact_factory_get_user (factory, account);
852         empathy_contact_run_until_ready (self_contact,
853                                          EMPATHY_CONTACT_READY_HANDLE,
854                                          NULL);
855
856         empathy_tp_group_add_member (group, contact, "");
857         empathy_tp_group_add_member (group, self_contact, "");  
858
859         g_object_unref (factory);
860         g_object_unref (self_contact);
861         g_object_unref (group);
862         g_object_unref (connection);
863         g_object_unref (channel);
864         g_free (object_path);
865 }
866
867 void
868 empathy_dispatcher_call_with_contact_id (McAccount *account, const gchar *contact_id)
869 {
870         EmpathyContactFactory *factory;
871         EmpathyContact        *contact;
872
873         factory = empathy_contact_factory_new ();
874         contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
875         empathy_contact_run_until_ready (contact, EMPATHY_CONTACT_READY_HANDLE, NULL);
876
877         empathy_dispatcher_call_with_contact (contact);
878
879         g_object_unref (contact);
880         g_object_unref (factory);
881 }
882
883 void
884 empathy_dispatcher_chat_with_contact (EmpathyContact  *contact)
885 {
886         MissionControl        *mc;
887         McAccount             *account;
888         TpConnection          *connection;
889         DispatcherRequestData *data;
890
891         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
892
893         mc = empathy_mission_control_new ();
894         account = empathy_contact_get_account (contact);
895         connection = mission_control_get_tpconnection (mc, account, NULL);
896         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
897         g_object_unref (mc);
898
899         /* We abuse of suppress_handler, TRUE means OUTGOING. */
900         data = g_new (DispatcherRequestData, 1);
901         data->channel_type = TP_IFACE_CHANNEL_TYPE_TEXT;
902         data->handle_type = TP_HANDLE_TYPE_CONTACT;
903         data->handle = empathy_contact_get_handle (contact);
904         tp_cli_connection_call_request_channel (connection, -1,
905                                                 data->channel_type,
906                                                 data->handle_type,
907                                                 data->handle,
908                                                 TRUE,
909                                                 dispatcher_request_channel_cb,
910                                                 data, g_free,
911                                                 NULL);
912         g_object_unref (connection);
913 }
914
915 void
916 empathy_dispatcher_chat_with_contact_id (McAccount   *account,
917                                          const gchar *contact_id)
918 {
919         EmpathyContactFactory *factory;
920         EmpathyContact        *contact;
921
922         factory = empathy_contact_factory_new ();
923         contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
924         empathy_contact_run_until_ready (contact, EMPATHY_CONTACT_READY_HANDLE, NULL);
925
926         empathy_dispatcher_chat_with_contact (contact);
927
928         g_object_unref (contact);
929         g_object_unref (factory);
930 }
931
932 typedef struct {
933         GFile *gfile;
934         TpHandle handle;
935 } FileChannelRequest;
936
937 static void
938 tp_file_state_notify_cb (EmpathyTpFile *tp_file)
939 {
940         EmpFileTransferState state;
941
942         state = empathy_tp_file_get_state (tp_file, NULL);
943         if (state == EMP_FILE_TRANSFER_STATE_COMPLETED ||
944             state == EMP_FILE_TRANSFER_STATE_CANCELLED) {
945                 DEBUG ("Transfer is done, unref the object");
946                 g_object_unref (tp_file);
947         }
948 }
949
950 static void
951 file_channel_create_cb (TpConnection *connection,
952                         const gchar  *object_path,
953                         GHashTable   *properties,
954                         const GError *error,
955                         gpointer      user_data,
956                         GObject      *weak_object)
957 {
958         TpChannel *channel;
959         EmpathyTpFile *tp_file;
960         FileChannelRequest *request = (FileChannelRequest *) user_data;
961
962         if (error) {
963                 DEBUG ("Couldn't request channel: %s", error->message);
964                 return;
965         }
966
967         channel = tp_channel_new (connection,
968                                  object_path,
969                                  EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER,
970                                  TP_HANDLE_TYPE_CONTACT,
971                                  request->handle,
972                                  NULL);
973
974         /* We give the ref to the callback, it is responsible to unref the
975          * object once the transfer is done. */
976         tp_file = empathy_tp_file_new (channel);
977         empathy_tp_file_offer (tp_file, request->gfile, NULL);
978         g_signal_connect (tp_file, "notify::state",
979                           G_CALLBACK (tp_file_state_notify_cb),
980                           NULL);
981
982         g_object_unref (request->gfile);
983         g_slice_free (FileChannelRequest, request);
984         g_object_unref (channel);
985 }
986
987 void
988 empathy_dispatcher_send_file (EmpathyContact *contact,
989                               GFile          *gfile)
990 {
991         MissionControl     *mc;
992         McAccount          *account;
993         TpConnection       *connection;
994         guint               handle;
995         FileChannelRequest *request;
996         GHashTable         *args;
997         GValue             *value;
998         GFileInfo          *info;
999         gchar              *filename;
1000         GTimeVal            last_modif;
1001         GError             *error = NULL;
1002
1003         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1004         g_return_if_fail (G_IS_FILE (gfile));
1005
1006         info = g_file_query_info (gfile,
1007                                   G_FILE_ATTRIBUTE_STANDARD_SIZE ","
1008                                   G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
1009                                   G_FILE_ATTRIBUTE_TIME_MODIFIED,
1010                                   0, NULL, &error);
1011
1012         if (error) {
1013                 DEBUG ("Can't get info about the file: %s", error->message);
1014                 g_clear_error (&error);
1015                 return;
1016         }
1017
1018         mc = empathy_mission_control_new ();
1019         account = empathy_contact_get_account (contact);
1020         connection = mission_control_get_tpconnection (mc, account, NULL);
1021         handle = empathy_contact_get_handle (contact);
1022
1023         request = g_slice_new0 (FileChannelRequest);
1024         request->gfile = g_object_ref (gfile);
1025         request->handle = handle;
1026
1027         filename = g_file_get_basename (request->gfile);
1028         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
1029
1030         DEBUG ("Sending %s from a stream to %s (size %lli, content-type %s)",
1031                filename, empathy_contact_get_name (contact),
1032                g_file_info_get_size (info),
1033                g_file_info_get_content_type (info));
1034
1035         args = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
1036                                       (GDestroyNotify) tp_g_value_slice_free);
1037
1038         /* org.freedesktop.Telepathy.Channel.ChannelType */
1039         value = tp_g_value_slice_new (G_TYPE_STRING);
1040         g_value_set_string (value, EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
1041         g_hash_table_insert (args, TP_IFACE_CHANNEL ".ChannelType", value);
1042
1043         /* org.freedesktop.Telepathy.Channel.TargetHandleType */
1044         value = tp_g_value_slice_new (G_TYPE_UINT);
1045         g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
1046         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandleType", value);
1047
1048         /* org.freedesktop.Telepathy.Channel.TargetHandle */
1049         value = tp_g_value_slice_new (G_TYPE_UINT);
1050         g_value_set_uint (value, handle);
1051         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandle", value);
1052
1053         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
1054         value = tp_g_value_slice_new (G_TYPE_STRING);
1055         g_value_set_string (value, g_file_info_get_content_type (info));
1056         g_hash_table_insert (args,
1057                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
1058
1059         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
1060         value = tp_g_value_slice_new (G_TYPE_STRING);
1061         g_value_set_string (value, g_filename_display_basename (filename));
1062         g_hash_table_insert (args,
1063                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
1064
1065         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
1066         value = tp_g_value_slice_new (G_TYPE_UINT64);
1067         g_value_set_uint64 (value, g_file_info_get_size (info));
1068         g_hash_table_insert (args,
1069                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
1070
1071         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
1072         g_file_info_get_modification_time (info, &last_modif);
1073         value = tp_g_value_slice_new (G_TYPE_UINT64);
1074         g_value_set_uint64 (value, last_modif.tv_sec);
1075         g_hash_table_insert (args,
1076                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
1077
1078         /* FIXME: Description ? */
1079         /* FIXME: ContentHashType and ContentHash ? */
1080
1081         tp_cli_connection_interface_requests_call_create_channel (connection, -1,
1082                 args, file_channel_create_cb, request, NULL, NULL);
1083
1084         g_hash_table_destroy (args);
1085         g_free (filename);
1086         g_object_unref (mc);
1087         g_object_unref (connection);
1088 }
1089