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