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