]> git.0d.be Git - empathy.git/blob - libempathy/empathy-dispatcher.c
Cleanup the coding style. If we can't get info about the GFile we abord the FT.
[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_manager_add (priv->chatroom_mgr, chatroom);
507         }
508       else
509         {
510           g_object_ref (chatroom);
511         }
512
513       g_object_set (chatroom, "tp-channel", channel, NULL);
514
515       ctx = dispatcher_connection_invalidated_cb_ctx_new (dispatcher, chatroom);
516
517       g_signal_connect_data (channel, "invalidated",
518           G_CALLBACK (dispatcher_chatroom_invalidated_cb), ctx,
519           (GClosureNotify) dispatcher_connection_invalidated_cb_ctx_free, 0);
520
521       g_free (room_ids[0]);
522       g_free (room_ids);
523       g_array_free (handles, TRUE);
524       g_object_unref (mc);
525       g_object_unref (account);
526       g_object_unref (chatroom);
527     }
528
529         if (suppress_handler) {
530                 g_signal_emit (dispatcher, signals[DISPATCH_CHANNEL], 0, channel);
531         } else {
532                 g_signal_emit (dispatcher, signals[FILTER_CHANNEL], 0, channel);
533         }
534
535         g_object_unref (channel);
536 }
537
538 static void
539 dispatcher_connection_list_channels_cb (TpConnection    *connection,
540                                         const GPtrArray *channels,
541                                         const GError    *error,
542                                         gpointer         user_data,
543                                         GObject         *dispatcher)
544 {
545         guint i;
546
547         if (error) {
548                 DEBUG ("Error: %s", error->message);
549                 return;
550         }
551
552         g_object_set_data (G_OBJECT (connection), "had-channels",
553                            GUINT_TO_POINTER (1));
554
555         for (i = 0; i < channels->len; i++) {
556                 GValueArray *values;
557
558                 values = g_ptr_array_index (channels, i);
559                 dispatcher_connection_new_channel_cb (connection,
560                         g_value_get_boxed (g_value_array_get_nth (values, 0)),
561                         g_value_get_string (g_value_array_get_nth (values, 1)),
562                         g_value_get_uint (g_value_array_get_nth (values, 2)),
563                         g_value_get_uint (g_value_array_get_nth (values, 3)),
564                         FALSE, user_data, dispatcher);
565         }
566 }
567
568 static void
569 dispatcher_connection_advertise_capabilities_cb (TpConnection    *connection,
570                                                  const GPtrArray *capabilities,
571                                                  const GError    *error,
572                                                  gpointer         user_data,
573                                                  GObject         *dispatcher)
574 {
575         if (error) {
576                 DEBUG ("Error: %s", error->message);
577         }
578 }
579
580 static void
581 dispatcher_connection_ready_cb (TpConnection  *connection,
582                                 const GError  *error,
583                                 gpointer       dispatcher)
584 {
585         GPtrArray   *capabilities;
586         GType        cap_type;
587         GValue       cap = {0, };
588         const gchar *remove = NULL;
589
590         if (error) {
591                 dispatcher_connection_invalidated_cb (connection,
592                                                       error->domain,
593                                                       error->code,
594                                                       error->message,
595                                                       dispatcher);
596                 return;
597         }
598
599         g_signal_connect (connection, "invalidated",
600                           G_CALLBACK (dispatcher_connection_invalidated_cb),
601                           dispatcher);
602         tp_cli_connection_connect_to_new_channel (connection,
603                                                   dispatcher_connection_new_channel_cb,
604                                                   NULL, NULL,
605                                                   G_OBJECT (dispatcher), NULL);
606         tp_cli_connection_call_list_channels (connection, -1,
607                                               dispatcher_connection_list_channels_cb,
608                                               NULL, NULL,
609                                               G_OBJECT (dispatcher));
610
611         /* Advertise VoIP capabilities */
612         capabilities = g_ptr_array_sized_new (1);
613         cap_type = dbus_g_type_get_struct ("GValueArray", G_TYPE_STRING,
614                                            G_TYPE_UINT, G_TYPE_INVALID);
615         g_value_init (&cap, cap_type);
616         g_value_take_boxed (&cap, dbus_g_type_specialized_construct (cap_type));
617         dbus_g_type_struct_set (&cap,
618                                 0, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
619                                 1, TP_CHANNEL_MEDIA_CAPABILITY_AUDIO |
620                                    TP_CHANNEL_MEDIA_CAPABILITY_VIDEO |
621                                    TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_STUN  |
622                                    TP_CHANNEL_MEDIA_CAPABILITY_NAT_TRAVERSAL_GTALK_P2P,
623                                 G_MAXUINT);
624         g_ptr_array_add (capabilities, g_value_get_boxed (&cap));
625
626         tp_cli_connection_interface_capabilities_call_advertise_capabilities (
627                 connection, -1,
628                 capabilities, &remove,
629                 dispatcher_connection_advertise_capabilities_cb,
630                 NULL, NULL, G_OBJECT (dispatcher));
631         /* FIXME: Is that leaked? */
632 }
633
634 static void
635 dispatcher_update_account (EmpathyDispatcher *dispatcher,
636                            McAccount         *account)
637 {
638         EmpathyDispatcherPriv *priv = GET_PRIV (dispatcher);
639         TpConnection          *connection;
640
641         connection = g_hash_table_lookup (priv->connections, account);
642         if (connection) {
643                 return;
644         }
645
646         connection = mission_control_get_tpconnection (priv->mc, account, NULL);
647         if (!connection) {
648                 return;
649         }
650
651         g_hash_table_insert (priv->connections, g_object_ref (account), connection);
652         tp_connection_call_when_ready (connection,
653                                        dispatcher_connection_ready_cb,
654                                        dispatcher);
655 }
656
657 static void
658 dispatcher_status_changed_cb (MissionControl           *mc,
659                               TpConnectionStatus        status,
660                               McPresence                presence,
661                               TpConnectionStatusReason  reason,
662                               const gchar              *unique_name,
663                               EmpathyDispatcher            *dispatcher)
664 {
665         McAccount *account;
666
667         account = mc_account_lookup (unique_name);
668         dispatcher_update_account (dispatcher, account);
669         g_object_unref (account);
670 }
671
672 static void
673 dispatcher_finalize (GObject *object)
674 {
675         EmpathyDispatcherPriv *priv = GET_PRIV (object);
676         GSList                *l;
677
678         empathy_disconnect_account_status_changed (priv->token);
679         g_object_unref (priv->mc);
680
681         for (l = priv->tubes; l; l = l->next) {
682                 g_signal_handlers_disconnect_by_func (l->data,
683                                                       dispatcher_tubes_channel_invalidated_cb,
684                                                       object);
685                 g_object_unref (l->data);
686         }
687         g_slist_free (priv->tubes);
688
689         g_hash_table_destroy (priv->connections);
690
691   g_object_unref (priv->chatroom_mgr);
692 }
693
694 static void
695 empathy_dispatcher_class_init (EmpathyDispatcherClass *klass)
696 {
697         GObjectClass *object_class = G_OBJECT_CLASS (klass);
698
699         object_class->finalize = dispatcher_finalize;
700
701         signals[DISPATCH_CHANNEL] =
702                 g_signal_new ("dispatch-channel",
703                               G_TYPE_FROM_CLASS (klass),
704                               G_SIGNAL_RUN_LAST,
705                               0,
706                               NULL, NULL,
707                               g_cclosure_marshal_VOID__OBJECT,
708                               G_TYPE_NONE,
709                               1, TP_TYPE_CHANNEL);
710         signals[FILTER_CHANNEL] =
711                 g_signal_new ("filter-channel",
712                               G_TYPE_FROM_CLASS (klass),
713                               G_SIGNAL_RUN_LAST,
714                               0,
715                               NULL, NULL,
716                               g_cclosure_marshal_VOID__OBJECT,
717                               G_TYPE_NONE,
718                               1, TP_TYPE_CHANNEL);
719         signals[FILTER_TUBE] =
720                 g_signal_new ("filter-tube",
721                               G_TYPE_FROM_CLASS (klass),
722                               G_SIGNAL_RUN_LAST,
723                               0,
724                               NULL, NULL,
725                               g_cclosure_marshal_VOID__BOXED,
726                               G_TYPE_NONE,
727                               1, EMPATHY_TYPE_DISPATCHER_TUBE);
728
729         g_type_class_add_private (object_class, sizeof (EmpathyDispatcherPriv));
730 }
731
732 static void
733 empathy_dispatcher_init (EmpathyDispatcher *dispatcher)
734 {
735         GList                 *accounts, *l;
736         EmpathyDispatcherPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (dispatcher,
737                 EMPATHY_TYPE_DISPATCHER, EmpathyDispatcherPriv);
738
739         dispatcher->priv = priv;
740         priv->mc = empathy_mission_control_new ();
741         priv->token = empathy_connect_to_account_status_changed (priv->mc,
742                 G_CALLBACK (dispatcher_status_changed_cb),
743                 dispatcher, NULL);
744
745         priv->connections = g_hash_table_new_full (empathy_account_hash,
746                                                    empathy_account_equal,
747                                                    g_object_unref,
748                                                    g_object_unref);
749         accounts = mc_accounts_list_by_enabled (TRUE);
750         for (l = accounts; l; l = l->next) {
751                 dispatcher_update_account (dispatcher, l->data);
752                 g_object_unref (l->data);
753         }
754         g_list_free (accounts);
755
756   priv->chatroom_mgr = empathy_chatroom_manager_new (NULL);
757 }
758
759 EmpathyDispatcher *
760 empathy_dispatcher_new (void)
761 {
762         if (!dispatcher) {
763                 dispatcher = g_object_new (EMPATHY_TYPE_DISPATCHER, NULL);
764                 g_object_add_weak_pointer (G_OBJECT (dispatcher), (gpointer) &dispatcher);
765         } else {
766                 g_object_ref (dispatcher);
767         }
768
769         return dispatcher;
770 }
771
772 typedef struct {
773         const gchar *channel_type;
774         guint        handle_type;
775         guint        handle;
776 } DispatcherRequestData;
777
778 static void
779 dispatcher_request_channel_cb (TpConnection *connection,
780                                const gchar  *object_path,
781                                const GError *error,
782                                gpointer      user_data,
783                                GObject      *weak_object)
784 {
785         DispatcherRequestData *data = (DispatcherRequestData*) user_data;
786
787         if (error) {
788                 DEBUG ("Error: %s", error->message);
789                 return;
790         }
791
792         if (dispatcher) {
793                 TpChannel *channel;
794
795                 channel = tp_channel_new (connection, object_path,
796                                           data->channel_type,
797                                           data->handle_type,
798                                           data->handle, NULL);
799
800                 g_signal_emit (dispatcher, signals[DISPATCH_CHANNEL], 0, channel);
801         }
802 }
803
804 void
805 empathy_dispatcher_call_with_contact (EmpathyContact *contact)
806 {
807         MissionControl        *mc;
808         McAccount             *account;
809         TpConnection          *connection;
810         gchar                 *object_path;
811         TpChannel             *channel;
812         EmpathyContactFactory *factory;
813         EmpathyTpGroup        *group;
814         EmpathyContact        *self_contact;
815         GError                *error = NULL;
816
817         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
818
819         mc = empathy_mission_control_new ();
820         account = empathy_contact_get_account (contact);
821         connection = mission_control_get_tpconnection (mc, account, NULL);
822         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
823         g_object_unref (mc);
824
825         /* We abuse of suppress_handler, TRUE means OUTGOING. The channel
826          * will be catched in EmpathyFilter */
827         if (!tp_cli_connection_run_request_channel (connection, -1,
828                                                     TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
829                                                     TP_HANDLE_TYPE_NONE,
830                                                     0,
831                                                     TRUE,
832                                                     &object_path,
833                                                     &error,
834                                                     NULL)) {
835                 DEBUG ("Couldn't request channel: %s",
836                         error ? error->message : "No error given");
837                 g_clear_error (&error);
838                 g_object_unref (connection);
839                 return;
840         }
841
842         channel = tp_channel_new (connection,
843                                   object_path, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA,
844                                   TP_HANDLE_TYPE_NONE, 0, NULL);
845
846         group = empathy_tp_group_new (channel);
847         empathy_run_until_ready (group);
848
849         factory = empathy_contact_factory_new ();
850         self_contact = empathy_contact_factory_get_user (factory, account);
851         empathy_contact_run_until_ready (self_contact,
852                                          EMPATHY_CONTACT_READY_HANDLE,
853                                          NULL);
854
855         empathy_tp_group_add_member (group, contact, "");
856         empathy_tp_group_add_member (group, self_contact, "");  
857
858         g_object_unref (factory);
859         g_object_unref (self_contact);
860         g_object_unref (group);
861         g_object_unref (connection);
862         g_object_unref (channel);
863         g_free (object_path);
864 }
865
866 void
867 empathy_dispatcher_call_with_contact_id (McAccount *account, const gchar *contact_id)
868 {
869         EmpathyContactFactory *factory;
870         EmpathyContact        *contact;
871
872         factory = empathy_contact_factory_new ();
873         contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
874         empathy_contact_run_until_ready (contact, EMPATHY_CONTACT_READY_HANDLE, NULL);
875
876         empathy_dispatcher_call_with_contact (contact);
877
878         g_object_unref (contact);
879         g_object_unref (factory);
880 }
881
882 void
883 empathy_dispatcher_chat_with_contact (EmpathyContact  *contact)
884 {
885         MissionControl        *mc;
886         McAccount             *account;
887         TpConnection          *connection;
888         DispatcherRequestData *data;
889
890         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
891
892         mc = empathy_mission_control_new ();
893         account = empathy_contact_get_account (contact);
894         connection = mission_control_get_tpconnection (mc, account, NULL);
895         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
896         g_object_unref (mc);
897
898         /* We abuse of suppress_handler, TRUE means OUTGOING. */
899         data = g_new (DispatcherRequestData, 1);
900         data->channel_type = TP_IFACE_CHANNEL_TYPE_TEXT;
901         data->handle_type = TP_HANDLE_TYPE_CONTACT;
902         data->handle = empathy_contact_get_handle (contact);
903         tp_cli_connection_call_request_channel (connection, -1,
904                                                 data->channel_type,
905                                                 data->handle_type,
906                                                 data->handle,
907                                                 TRUE,
908                                                 dispatcher_request_channel_cb,
909                                                 data, g_free,
910                                                 NULL);
911         g_object_unref (connection);
912 }
913
914 void
915 empathy_dispatcher_chat_with_contact_id (McAccount   *account,
916                                          const gchar *contact_id)
917 {
918         EmpathyContactFactory *factory;
919         EmpathyContact        *contact;
920
921         factory = empathy_contact_factory_new ();
922         contact = empathy_contact_factory_get_from_id (factory, account, contact_id);
923         empathy_contact_run_until_ready (contact, EMPATHY_CONTACT_READY_HANDLE, NULL);
924
925         empathy_dispatcher_chat_with_contact (contact);
926
927         g_object_unref (contact);
928         g_object_unref (factory);
929 }
930
931 typedef struct {
932         GFile *gfile;
933         TpHandle handle;
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         empathy_tp_file_set_gfile (tp_file, request->gfile, NULL);
962         empathy_tp_file_offer (tp_file);
963
964         g_object_unref (request->gfile);
965         g_slice_free (FileChannelRequest, request);
966         g_object_unref (channel);
967 }
968
969 void
970 empathy_dispatcher_send_file (EmpathyContact *contact,
971                               GFile          *gfile)
972 {
973         MissionControl     *mc;
974         McAccount          *account;
975         TpConnection       *connection;
976         guint               handle;
977         FileChannelRequest *request;
978         GHashTable         *args;
979         GValue             *value;
980         GFileInfo          *info;
981         gchar              *filename;
982         GTimeVal            last_modif;
983         GError             *error = NULL;
984
985         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
986         g_return_if_fail (G_IS_FILE (gfile));
987
988         info = g_file_query_info (gfile,
989                                   G_FILE_ATTRIBUTE_STANDARD_SIZE ","
990                                   G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE ","
991                                   G_FILE_ATTRIBUTE_TIME_MODIFIED,
992                                   0, NULL, &error);
993
994         if (error) {
995                 DEBUG ("Can't get info about the file: %s", error->message);
996                 g_clear_error (&error);
997                 return;
998         }
999
1000         mc = empathy_mission_control_new ();
1001         account = empathy_contact_get_account (contact);
1002         connection = mission_control_get_tpconnection (mc, account, NULL);
1003         handle = empathy_contact_get_handle (contact);
1004
1005         request = g_slice_new0 (FileChannelRequest);
1006         request->gfile = g_object_ref (gfile);
1007         request->handle = handle;
1008
1009         filename = g_file_get_basename (request->gfile);
1010         tp_connection_run_until_ready (connection, FALSE, NULL, NULL);
1011
1012         DEBUG ("Sending %s from a stream to %s (size %llu, content-type %s)",
1013                filename, empathy_contact_get_name (contact),
1014                g_file_info_get_size (info),
1015                g_file_info_get_content_type (info));
1016
1017         args = g_hash_table_new_full (g_str_hash, g_str_equal, NULL,
1018                                       (GDestroyNotify) tp_g_value_slice_free);
1019
1020         /* org.freedesktop.Telepathy.Channel.ChannelType */
1021         value = tp_g_value_slice_new (G_TYPE_STRING);
1022         g_value_set_string (value, EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER);
1023         g_hash_table_insert (args, TP_IFACE_CHANNEL ".ChannelType", value);
1024
1025         /* org.freedesktop.Telepathy.Channel.TargetHandleType */
1026         value = tp_g_value_slice_new (G_TYPE_UINT);
1027         g_value_set_uint (value, TP_HANDLE_TYPE_CONTACT);
1028         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandleType", value);
1029
1030         /* org.freedesktop.Telepathy.Channel.TargetHandle */
1031         value = tp_g_value_slice_new (G_TYPE_UINT);
1032         g_value_set_uint (value, handle);
1033         g_hash_table_insert (args, TP_IFACE_CHANNEL ".TargetHandle", value);
1034
1035         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.ContentType */
1036         value = tp_g_value_slice_new (G_TYPE_STRING);
1037         g_value_set_string (value, g_file_info_get_content_type (info));
1038         g_hash_table_insert (args,
1039                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".ContentType", value);
1040
1041         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Filename */
1042         value = tp_g_value_slice_new (G_TYPE_STRING);
1043         g_value_set_string (value, g_filename_display_basename (filename));
1044         g_hash_table_insert (args,
1045                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Filename", value);
1046
1047         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Size */
1048         value = tp_g_value_slice_new (G_TYPE_UINT64);
1049         g_value_set_uint64 (value, g_file_info_get_size (info));
1050         g_hash_table_insert (args,
1051                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Size", value);
1052
1053         /* org.freedesktop.Telepathy.Channel.Type.FileTransfer.Date */
1054         g_file_info_get_modification_time (info, &last_modif);
1055         value = tp_g_value_slice_new (G_TYPE_UINT64);
1056         g_value_set_uint64 (value, last_modif.tv_sec);
1057         g_hash_table_insert (args,
1058                 EMP_IFACE_CHANNEL_TYPE_FILE_TRANSFER ".Date", value);
1059
1060         /* FIXME: Description ? */
1061         /* FIXME: ContentHashType and ContentHash ? */
1062
1063         tp_cli_connection_interface_requests_call_create_channel (connection, -1,
1064                 args, file_channel_create_cb, request, NULL, NULL);
1065
1066         g_hash_table_destroy (args);
1067         g_free (filename);
1068         g_object_unref (mc);
1069         g_object_unref (connection);
1070 }
1071