]> git.0d.be Git - empathy.git/blob - libempathy/empathy-tp-chat.c
factor out empathy_message_new_from_tp_message
[empathy.git] / libempathy / empathy-tp-chat.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 <telepathy-glib/telepathy-glib.h>
27
28 #include <extensions/extensions.h>
29
30 #include "empathy-tp-chat.h"
31 #include "empathy-tp-contact-factory.h"
32 #include "empathy-contact-list.h"
33 #include "empathy-marshal.h"
34 #include "empathy-request-util.h"
35 #include "empathy-time.h"
36 #include "empathy-utils.h"
37
38 #define DEBUG_FLAG EMPATHY_DEBUG_TP | EMPATHY_DEBUG_CHAT
39 #include "empathy-debug.h"
40
41 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyTpChat)
42 typedef struct {
43         gboolean               dispose_has_run;
44         TpAccount             *account;
45         TpConnection          *connection;
46         EmpathyContact        *user;
47         EmpathyContact        *remote_contact;
48         GList                 *members;
49         TpChannel             *channel;
50         /* Queue of messages not signalled yet */
51         GQueue                *messages_queue;
52         /* Queue of messages signalled but not acked yet */
53         GQueue                *pending_messages_queue;
54         gboolean               had_properties_list;
55         GPtrArray             *properties;
56         TpChannelPasswordFlags password_flags;
57         /* TRUE if we fetched the password flag of the channel or if it's not needed
58          * (channel doesn't implement the Password interface) */
59         gboolean               got_password_flags;
60         gboolean               ready;
61         gboolean               can_upgrade_to_muc;
62 } EmpathyTpChatPriv;
63
64 static void tp_chat_iface_init         (EmpathyContactListIface *iface);
65
66 enum {
67         PROP_0,
68         PROP_ACCOUNT,
69         PROP_CHANNEL,
70         PROP_REMOTE_CONTACT,
71         PROP_PASSWORD_NEEDED,
72         PROP_READY,
73 };
74
75 enum {
76         MESSAGE_RECEIVED,
77         SEND_ERROR,
78         CHAT_STATE_CHANGED,
79         PROPERTY_CHANGED,
80         DESTROY,
81         LAST_SIGNAL
82 };
83
84 static guint signals[LAST_SIGNAL];
85
86 G_DEFINE_TYPE_WITH_CODE (EmpathyTpChat, empathy_tp_chat, G_TYPE_OBJECT,
87                          G_IMPLEMENT_INTERFACE (EMPATHY_TYPE_CONTACT_LIST,
88                                                 tp_chat_iface_init));
89
90 static void acknowledge_messages (EmpathyTpChat *chat, GArray *ids);
91
92 static void
93 tp_chat_invalidated_cb (TpProxy       *proxy,
94                         guint          domain,
95                         gint           code,
96                         gchar         *message,
97                         EmpathyTpChat *chat)
98 {
99         DEBUG ("Channel invalidated: %s", message);
100         g_signal_emit (chat, signals[DESTROY], 0);
101 }
102
103 static void
104 tp_chat_async_cb (TpChannel *proxy,
105                   const GError *error,
106                   gpointer user_data,
107                   GObject *weak_object)
108 {
109         if (error) {
110                 DEBUG ("Error %s: %s", (gchar *) user_data, error->message);
111         }
112 }
113
114 static void
115 create_conference_cb (GObject *source,
116                       GAsyncResult *result,
117                       gpointer user_data)
118 {
119         GError *error = NULL;
120
121         if (!tp_account_channel_request_create_channel_finish (
122                         TP_ACCOUNT_CHANNEL_REQUEST (source), result, &error)) {
123                 DEBUG ("Failed to create conference channel: %s", error->message);
124                 g_error_free (error);
125         }
126 }
127
128 static void
129 tp_chat_add (EmpathyContactList *list,
130              EmpathyContact     *contact,
131              const gchar        *message)
132 {
133         EmpathyTpChatPriv *priv = GET_PRIV (list);
134
135         if (tp_proxy_has_interface_by_id (priv->channel,
136                 TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
137                 TpHandle           handle;
138                 GArray             handles = {(gchar *) &handle, 1};
139
140                 g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
141                 g_return_if_fail (EMPATHY_IS_CONTACT (contact));
142
143                 handle = empathy_contact_get_handle (contact);
144                 tp_cli_channel_interface_group_call_add_members (priv->channel,
145                         -1, &handles, NULL, NULL, NULL, NULL, NULL);
146         } else if (priv->can_upgrade_to_muc) {
147                 TpAccountChannelRequest *req;
148                 GHashTable        *props;
149                 const char        *object_path;
150                 GPtrArray          channels = { (gpointer *) &object_path, 1 };
151                 const char        *invitees[2] = { NULL, };
152
153                 invitees[0] = empathy_contact_get_id (contact);
154                 object_path = tp_proxy_get_object_path (priv->channel);
155
156                 props = tp_asv_new (
157                     TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
158                         TP_IFACE_CHANNEL_TYPE_TEXT,
159                     TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT,
160                         TP_HANDLE_TYPE_NONE,
161                     TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_CHANNELS,
162                         TP_ARRAY_TYPE_OBJECT_PATH_LIST, &channels,
163                     TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_INVITEE_IDS,
164                         G_TYPE_STRV, invitees,
165                     /* FIXME: InvitationMessage ? */
166                     NULL);
167
168                 req = tp_account_channel_request_new (priv->account, props,
169                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
170
171                 /* Although this is a MUC, it's anonymous, so CreateChannel is
172                  * valid. */
173                 tp_account_channel_request_create_channel_async (req, EMPATHY_CHAT_BUS_NAME,
174                         NULL, create_conference_cb, NULL);
175
176                 g_object_unref (req);
177                 g_hash_table_unref (props);
178         } else {
179                 g_warning ("Cannot add to this channel");
180         }
181 }
182
183 static void
184 tp_chat_remove (EmpathyContactList *list,
185                 EmpathyContact     *contact,
186                 const gchar        *message)
187 {
188         EmpathyTpChatPriv *priv = GET_PRIV (list);
189         TpHandle           handle;
190         GArray             handles = {(gchar *) &handle, 1};
191
192         g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
193         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
194
195         handle = empathy_contact_get_handle (contact);
196         tp_cli_channel_interface_group_call_remove_members (priv->channel, -1,
197                                                             &handles, NULL,
198                                                             NULL, NULL, NULL,
199                                                             NULL);
200 }
201
202 static GList *
203 tp_chat_get_members (EmpathyContactList *list)
204 {
205         EmpathyTpChatPriv *priv = GET_PRIV (list);
206         GList             *members = NULL;
207
208         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (list), NULL);
209
210         if (priv->members) {
211                 members = g_list_copy (priv->members);
212                 g_list_foreach (members, (GFunc) g_object_ref, NULL);
213         } else {
214                 members = g_list_prepend (members, g_object_ref (priv->user));
215                 if (priv->remote_contact != NULL)
216                         members = g_list_prepend (members, g_object_ref (priv->remote_contact));
217         }
218
219         return members;
220 }
221
222 static void
223 check_ready (EmpathyTpChat *chat)
224 {
225         EmpathyTpChatPriv *priv = GET_PRIV (chat);
226
227         if (priv->ready)
228                 return;
229
230         if (g_queue_get_length (priv->messages_queue) > 0)
231                 return;
232
233         DEBUG ("Ready");
234
235         priv->ready = TRUE;
236         g_object_notify (G_OBJECT (chat), "ready");
237 }
238
239 static void
240 tp_chat_emit_queued_messages (EmpathyTpChat *chat)
241 {
242         EmpathyTpChatPriv *priv = GET_PRIV (chat);
243         EmpathyMessage    *message;
244
245         /* Check if we can now emit some queued messages */
246         while ((message = g_queue_peek_head (priv->messages_queue)) != NULL) {
247                 if (empathy_message_get_sender (message) == NULL) {
248                         break;
249                 }
250
251                 DEBUG ("Queued message ready");
252                 g_queue_pop_head (priv->messages_queue);
253                 g_queue_push_tail (priv->pending_messages_queue, message);
254                 g_signal_emit (chat, signals[MESSAGE_RECEIVED], 0, message);
255         }
256
257         check_ready (chat);
258 }
259
260 static void
261 tp_chat_got_sender_cb (TpConnection            *connection,
262                        EmpathyContact          *contact,
263                        const GError            *error,
264                        gpointer                 message,
265                        GObject                 *chat)
266 {
267         EmpathyTpChatPriv *priv = GET_PRIV (chat);
268
269         if (error) {
270                 DEBUG ("Error: %s", error->message);
271                 /* Do not block the message queue, just drop this message */
272                 g_queue_remove (priv->messages_queue, message);
273         } else {
274                 empathy_message_set_sender (message, contact);
275         }
276
277         tp_chat_emit_queued_messages (EMPATHY_TP_CHAT (chat));
278 }
279
280 static void
281 tp_chat_build_message (EmpathyTpChat *chat,
282                        TpMessage     *msg,
283                        gboolean       incoming)
284 {
285         EmpathyTpChatPriv *priv;
286         EmpathyMessage    *message;
287         TpContact *sender;
288
289         priv = GET_PRIV (chat);
290
291         message = empathy_message_new_from_tp_message (msg, incoming);
292         /* FIXME: this is actually a lie for incoming messages. */
293         empathy_message_set_receiver (message, priv->user);
294
295         g_queue_push_tail (priv->messages_queue, message);
296
297         sender = tp_signalled_message_get_sender (msg);
298         g_assert (sender != NULL);
299
300         if (tp_contact_get_handle (sender) == 0) {
301                 empathy_message_set_sender (message, priv->user);
302                 tp_chat_emit_queued_messages (chat);
303         } else {
304                 empathy_tp_contact_factory_get_from_handle (priv->connection,
305                         tp_contact_get_handle (sender),
306                         tp_chat_got_sender_cb,
307                         message, NULL, G_OBJECT (chat));
308         }
309 }
310
311 static void
312 message_received_cb (TpTextChannel   *channel,
313                      TpMessage *message,
314                      EmpathyTpChat *chat)
315 {
316         EmpathyTpChatPriv *priv = GET_PRIV (chat);
317         gchar *message_body;
318
319         message_body = tp_message_to_text (message, NULL);
320
321         DEBUG ("Message received from channel %s: %s",
322                 tp_proxy_get_object_path (channel), message_body);
323
324         if (message_body == NULL) {
325                 DEBUG ("Empty message with NonTextContent, ignoring and acking.");
326
327                 tp_text_channel_ack_message_async (TP_TEXT_CHANNEL (priv->channel),
328                         message, NULL, NULL);
329                 return;
330         }
331
332         tp_chat_build_message (chat, message, TRUE);
333
334         g_free (message_body);
335 }
336
337 static void
338 message_sent_cb (TpTextChannel   *channel,
339                  TpMessage *message,
340                  TpMessageSendingFlags flags,
341                  gchar              *token,
342                  EmpathyTpChat      *chat)
343 {
344         gchar *message_body;
345
346         message_body = tp_message_to_text (message, NULL);
347
348         DEBUG ("Message sent: %s", message_body);
349
350         tp_chat_build_message (chat, message, FALSE);
351
352         g_free (message_body);
353 }
354
355 static void
356 tp_chat_send_error_cb (TpChannel   *channel,
357                        guint        error_code,
358                        guint        timestamp,
359                        guint        message_type,
360                        const gchar *message_body,
361                        gpointer     user_data,
362                        GObject     *chat)
363 {
364         EmpathyTpChatPriv *priv = GET_PRIV (chat);
365
366         if (priv->channel == NULL)
367                 return;
368
369         DEBUG ("Error sending '%s' (%d)", message_body, error_code);
370
371         g_signal_emit (chat, signals[SEND_ERROR], 0, message_body, error_code);
372 }
373
374 static void
375 tp_chat_send_cb (TpChannel    *proxy,
376                  const GError *error,
377                  gpointer      user_data,
378                  GObject      *chat)
379 {
380         EmpathyMessage *message = EMPATHY_MESSAGE (user_data);
381
382         if (error) {
383                 DEBUG ("Error: %s", error->message);
384                 g_signal_emit (chat, signals[SEND_ERROR], 0,
385                                empathy_message_get_body (message),
386                                TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN);
387         }
388 }
389
390 typedef struct {
391         EmpathyTpChat *chat;
392         TpChannelChatState state;
393 } StateChangedData;
394
395 static void
396 tp_chat_state_changed_got_contact_cb (TpConnection            *connection,
397                                       EmpathyContact          *contact,
398                                       const GError            *error,
399                                       gpointer                 user_data,
400                                       GObject                 *chat)
401 {
402         TpChannelChatState state;
403
404         if (error) {
405                 DEBUG ("Error: %s", error->message);
406                 return;
407         }
408
409         state = GPOINTER_TO_UINT (user_data);
410         DEBUG ("Chat state changed for %s (%d): %d",
411                 empathy_contact_get_alias (contact),
412                 empathy_contact_get_handle (contact), state);
413
414         g_signal_emit (chat, signals[CHAT_STATE_CHANGED], 0, contact, state);
415 }
416
417 static void
418 tp_chat_state_changed_cb (TpChannel *channel,
419                           TpHandle   handle,
420                           TpChannelChatState state,
421                           gpointer   user_data,
422                           GObject   *chat)
423 {
424         EmpathyTpChatPriv *priv = GET_PRIV (chat);
425
426         empathy_tp_contact_factory_get_from_handle (priv->connection, handle,
427                 tp_chat_state_changed_got_contact_cb, GUINT_TO_POINTER (state),
428                 NULL, chat);
429 }
430
431 static void
432 list_pending_messages (EmpathyTpChat *self)
433 {
434         EmpathyTpChatPriv *priv = GET_PRIV (self);
435         GList *messages, *l;
436
437         g_assert (priv->channel != NULL);
438
439         messages = tp_text_channel_get_pending_messages (
440                 TP_TEXT_CHANNEL (priv->channel));
441
442         for (l = messages; l != NULL; l = g_list_next (l)) {
443                 TpMessage *message = l->data;
444                 gchar          *message_body;
445
446                 message_body = tp_message_to_text (message, NULL);
447
448                 DEBUG ("Message pending: %s", message_body);
449
450                 if (message_body == NULL) {
451                         DEBUG ("Empty message with NonTextContent, ignoring and acking.");
452
453                         tp_text_channel_ack_message_async (TP_TEXT_CHANNEL (priv->channel),
454                                 message, NULL, NULL);
455                         continue;
456                 }
457
458                 tp_chat_build_message (self, message, TRUE);
459
460                 g_free (message_body);
461         }
462
463         g_list_free (messages);
464 }
465
466 static void
467 tp_chat_property_flags_changed_cb (TpProxy         *proxy,
468                                    const GPtrArray *properties,
469                                    gpointer         user_data,
470                                    GObject         *chat)
471 {
472         EmpathyTpChatPriv *priv = GET_PRIV (chat);
473         guint              i, j;
474
475         if (priv->channel == NULL)
476                 return;
477
478         if (!priv->had_properties_list || !properties) {
479                 return;
480         }
481
482         for (i = 0; i < properties->len; i++) {
483                 GValueArray           *prop_struct;
484                 EmpathyTpChatProperty *property;
485                 guint                  id;
486                 guint                  flags;
487
488                 prop_struct = g_ptr_array_index (properties, i);
489                 id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
490                 flags = g_value_get_uint (g_value_array_get_nth (prop_struct, 1));
491
492                 for (j = 0; j < priv->properties->len; j++) {
493                         property = g_ptr_array_index (priv->properties, j);
494                         if (property->id == id) {
495                                 property->flags = flags;
496                                 DEBUG ("property %s flags changed: %d",
497                                         property->name, property->flags);
498                                 break;
499                         }
500                 }
501         }
502 }
503
504 static void
505 tp_chat_properties_changed_cb (TpProxy         *proxy,
506                                const GPtrArray *properties,
507                                gpointer         user_data,
508                                GObject         *chat)
509 {
510         EmpathyTpChatPriv *priv = GET_PRIV (chat);
511         guint              i, j;
512
513         if (priv->channel == NULL)
514                 return;
515
516         if (!priv->had_properties_list || !properties) {
517                 return;
518         }
519
520         for (i = 0; i < properties->len; i++) {
521                 GValueArray           *prop_struct;
522                 EmpathyTpChatProperty *property;
523                 guint                  id;
524                 GValue                *src_value;
525
526                 prop_struct = g_ptr_array_index (properties, i);
527                 id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
528                 src_value = g_value_get_boxed (g_value_array_get_nth (prop_struct, 1));
529
530                 for (j = 0; j < priv->properties->len; j++) {
531                         property = g_ptr_array_index (priv->properties, j);
532                         if (property->id == id) {
533                                 if (property->value) {
534                                         g_value_copy (src_value, property->value);
535                                 } else {
536                                         property->value = tp_g_value_slice_dup (src_value);
537                                 }
538
539                                 DEBUG ("property %s changed", property->name);
540                                 g_signal_emit (chat, signals[PROPERTY_CHANGED], 0,
541                                                property->name, property->value);
542                                 break;
543                         }
544                 }
545         }
546 }
547
548 static void
549 tp_chat_get_properties_cb (TpProxy         *proxy,
550                            const GPtrArray *properties,
551                            const GError    *error,
552                            gpointer         user_data,
553                            GObject         *chat)
554 {
555         if (error) {
556                 DEBUG ("Error getting properties: %s", error->message);
557                 return;
558         }
559
560         tp_chat_properties_changed_cb (proxy, properties, user_data, chat);
561 }
562
563 static void
564 tp_chat_list_properties_cb (TpProxy         *proxy,
565                             const GPtrArray *properties,
566                             const GError    *error,
567                             gpointer         user_data,
568                             GObject         *chat)
569 {
570         EmpathyTpChatPriv *priv = GET_PRIV (chat);
571         GArray            *ids;
572         guint              i;
573
574         if (priv->channel == NULL)
575                 return;
576
577         priv->had_properties_list = TRUE;
578
579         if (error) {
580                 DEBUG ("Error listing properties: %s", error->message);
581                 return;
582         }
583
584         ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), properties->len);
585         priv->properties = g_ptr_array_sized_new (properties->len);
586         for (i = 0; i < properties->len; i++) {
587                 GValueArray           *prop_struct;
588                 EmpathyTpChatProperty *property;
589
590                 prop_struct = g_ptr_array_index (properties, i);
591                 property = g_slice_new0 (EmpathyTpChatProperty);
592                 property->id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
593                 property->name = g_value_dup_string (g_value_array_get_nth (prop_struct, 1));
594                 property->flags = g_value_get_uint (g_value_array_get_nth (prop_struct, 3));
595
596                 DEBUG ("Adding property name=%s id=%d flags=%d",
597                         property->name, property->id, property->flags);
598                 g_ptr_array_add (priv->properties, property);
599                 if (property->flags & TP_PROPERTY_FLAG_READ) {
600                         g_array_append_val (ids, property->id);
601                 }
602         }
603
604         tp_cli_properties_interface_call_get_properties (proxy, -1,
605                                                          ids,
606                                                          tp_chat_get_properties_cb,
607                                                          NULL, NULL,
608                                                          chat);
609
610         g_array_free (ids, TRUE);
611 }
612
613 void
614 empathy_tp_chat_set_property (EmpathyTpChat *chat,
615                               const gchar   *name,
616                               const GValue  *value)
617 {
618         EmpathyTpChatPriv     *priv = GET_PRIV (chat);
619         EmpathyTpChatProperty *property;
620         guint                  i;
621
622         if (!priv->had_properties_list) {
623                 return;
624         }
625
626         for (i = 0; i < priv->properties->len; i++) {
627                 property = g_ptr_array_index (priv->properties, i);
628                 if (!tp_strdiff (property->name, name)) {
629                         GPtrArray   *properties;
630                         GValueArray *prop;
631                         GValue       id = {0, };
632                         GValue       dest_value = {0, };
633
634                         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
635                                 break;
636                         }
637
638                         g_value_init (&id, G_TYPE_UINT);
639                         g_value_init (&dest_value, G_TYPE_VALUE);
640                         g_value_set_uint (&id, property->id);
641                         g_value_set_boxed (&dest_value, value);
642
643                         prop = g_value_array_new (2);
644                         g_value_array_append (prop, &id);
645                         g_value_array_append (prop, &dest_value);
646
647                         properties = g_ptr_array_sized_new (1);
648                         g_ptr_array_add (properties, prop);
649
650                         DEBUG ("Set property %s", name);
651                         tp_cli_properties_interface_call_set_properties (priv->channel, -1,
652                                                                          properties,
653                                                                          (tp_cli_properties_interface_callback_for_set_properties)
654                                                                          tp_chat_async_cb,
655                                                                          "Seting property", NULL,
656                                                                          G_OBJECT (chat));
657
658                         g_ptr_array_free (properties, TRUE);
659                         g_value_array_free (prop);
660
661                         break;
662                 }
663         }
664 }
665
666 EmpathyTpChatProperty *
667 empathy_tp_chat_get_property (EmpathyTpChat *chat,
668                               const gchar   *name)
669 {
670         EmpathyTpChatPriv     *priv = GET_PRIV (chat);
671         EmpathyTpChatProperty *property;
672         guint                  i;
673
674         if (!priv->had_properties_list) {
675                 return NULL;
676         }
677
678         for (i = 0; i < priv->properties->len; i++) {
679                 property = g_ptr_array_index (priv->properties, i);
680                 if (!tp_strdiff (property->name, name)) {
681                         return property;
682                 }
683         }
684
685         return NULL;
686 }
687
688 GPtrArray *
689 empathy_tp_chat_get_properties (EmpathyTpChat *chat)
690 {
691         EmpathyTpChatPriv *priv = GET_PRIV (chat);
692
693         return priv->properties;
694 }
695
696 static void
697 tp_chat_dispose (GObject *object)
698 {
699         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
700         EmpathyTpChatPriv *priv = GET_PRIV (self);
701
702         if (priv->dispose_has_run)
703                 return;
704
705         priv->dispose_has_run = TRUE;
706
707         tp_clear_object (&priv->account);
708
709         if (priv->connection != NULL)
710                 g_object_unref (priv->connection);
711         priv->connection = NULL;
712
713         if (priv->channel != NULL) {
714                 g_signal_handlers_disconnect_by_func (priv->channel,
715                         tp_chat_invalidated_cb, self);
716                 g_object_unref (priv->channel);
717         }
718         priv->channel = NULL;
719
720         if (priv->remote_contact != NULL)
721                 g_object_unref (priv->remote_contact);
722         priv->remote_contact = NULL;
723
724         if (priv->user != NULL)
725                 g_object_unref (priv->user);
726         priv->user = NULL;
727
728         g_queue_foreach (priv->messages_queue, (GFunc) g_object_unref, NULL);
729         g_queue_clear (priv->messages_queue);
730
731         g_queue_foreach (priv->pending_messages_queue,
732                 (GFunc) g_object_unref, NULL);
733         g_queue_clear (priv->pending_messages_queue);
734
735         if (G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose)
736                 G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose (object);
737 }
738
739 static void
740 tp_chat_finalize (GObject *object)
741 {
742         EmpathyTpChatPriv *priv = GET_PRIV (object);
743         guint              i;
744
745         DEBUG ("Finalize: %p", object);
746
747         if (priv->properties) {
748                 for (i = 0; i < priv->properties->len; i++) {
749                         EmpathyTpChatProperty *property;
750
751                         property = g_ptr_array_index (priv->properties, i);
752                         g_free (property->name);
753                         if (property->value) {
754                                 tp_g_value_slice_free (property->value);
755                         }
756                         g_slice_free (EmpathyTpChatProperty, property);
757                 }
758                 g_ptr_array_free (priv->properties, TRUE);
759         }
760
761         g_queue_free (priv->messages_queue);
762         g_queue_free (priv->pending_messages_queue);
763
764         G_OBJECT_CLASS (empathy_tp_chat_parent_class)->finalize (object);
765 }
766
767 static void
768 check_almost_ready (EmpathyTpChat *chat)
769 {
770         EmpathyTpChatPriv *priv = GET_PRIV (chat);
771
772         if (priv->ready)
773                 return;
774
775         if (priv->user == NULL)
776                 return;
777
778         if (!priv->got_password_flags)
779                 return;
780
781         /* We need either the members (room) or the remote contact (private chat).
782          * If the chat is protected by a password we can't get these information so
783          * consider the chat as ready so it can be presented to the user. */
784         if (!empathy_tp_chat_password_needed (chat) && priv->members == NULL &&
785             priv->remote_contact == NULL)
786                 return;
787
788         /* We use the default factory so this feature should have been prepared */
789         g_assert (tp_proxy_is_prepared (priv->channel,
790                 TP_TEXT_CHANNEL_FEATURE_INCOMING_MESSAGES));
791
792         tp_g_signal_connect_object (priv->channel, "message-received",
793                 G_CALLBACK (message_received_cb), chat, 0);
794
795         list_pending_messages (chat);
796
797         tp_g_signal_connect_object (priv->channel, "message-sent",
798                 G_CALLBACK (message_sent_cb), chat, 0);
799
800         tp_cli_channel_type_text_connect_to_send_error (priv->channel,
801                                                         tp_chat_send_error_cb,
802                                                         NULL, NULL,
803                                                         G_OBJECT (chat), NULL);
804         tp_cli_channel_interface_chat_state_connect_to_chat_state_changed (priv->channel,
805                                                                            tp_chat_state_changed_cb,
806                                                                            NULL, NULL,
807                                                                            G_OBJECT (chat), NULL);
808
809         check_ready (chat);
810 }
811
812 static void
813 tp_chat_update_remote_contact (EmpathyTpChat *chat)
814 {
815         EmpathyTpChatPriv *priv = GET_PRIV (chat);
816         EmpathyContact *contact = NULL;
817         TpHandle self_handle;
818         TpHandleType handle_type;
819         GList *l;
820
821         /* If this is a named chatroom, never pretend it is a private chat */
822         tp_channel_get_handle (priv->channel, &handle_type);
823         if (handle_type == TP_HANDLE_TYPE_ROOM) {
824                 return;
825         }
826
827         /* This is an MSN chat, but it's the new style where 1-1 chats don't
828          * have the group interface. If it has the conference interface, then
829          * it is indeed a MUC. */
830         if (tp_proxy_has_interface_by_id (priv->channel,
831                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_CONFERENCE)) {
832                 return;
833         }
834
835         /* This is an MSN-like chat where anyone can join the chat at anytime.
836          * If there is only one non-self contact member, we are in a private
837          * chat and we set the "remote-contact" property to that contact. If
838          * there are more, set the "remote-contact" property to NULL and the
839          * UI will display a contact list. */
840         self_handle = tp_channel_group_get_self_handle (priv->channel);
841         for (l = priv->members; l; l = l->next) {
842                 /* Skip self contact if member */
843                 if (empathy_contact_get_handle (l->data) == self_handle) {
844                         continue;
845                 }
846
847                 /* We have more than one remote contact, break */
848                 if (contact != NULL) {
849                         contact = NULL;
850                         break;
851                 }
852
853                 /* If we didn't find yet a remote contact, keep this one */
854                 contact = l->data;
855         }
856
857         if (priv->remote_contact == contact) {
858                 return;
859         }
860
861         DEBUG ("Changing remote contact from %p to %p",
862                 priv->remote_contact, contact);
863
864         if (priv->remote_contact) {
865                 g_object_unref (priv->remote_contact);
866         }
867
868         priv->remote_contact = contact ? g_object_ref (contact) : NULL;
869         g_object_notify (G_OBJECT (chat), "remote-contact");
870 }
871
872 static void
873 tp_chat_got_added_contacts_cb (TpConnection            *connection,
874                                guint                    n_contacts,
875                                EmpathyContact * const * contacts,
876                                guint                    n_failed,
877                                const TpHandle          *failed,
878                                const GError            *error,
879                                gpointer                 user_data,
880                                GObject                 *chat)
881 {
882         EmpathyTpChatPriv *priv = GET_PRIV (chat);
883         guint i;
884         const TpIntSet *members;
885         TpHandle handle;
886         EmpathyContact *contact;
887
888         if (error) {
889                 DEBUG ("Error: %s", error->message);
890                 return;
891         }
892
893         members = tp_channel_group_get_members (priv->channel);
894         for (i = 0; i < n_contacts; i++) {
895                 contact = contacts[i];
896                 handle = empathy_contact_get_handle (contact);
897
898                 /* Make sure the contact is still member */
899                 if (tp_intset_is_member (members, handle)) {
900                         priv->members = g_list_prepend (priv->members,
901                                 g_object_ref (contact));
902                         g_signal_emit_by_name (chat, "members-changed",
903                                                contact, NULL, 0, NULL, TRUE);
904                 }
905         }
906
907         tp_chat_update_remote_contact (EMPATHY_TP_CHAT (chat));
908         check_almost_ready (EMPATHY_TP_CHAT (chat));
909 }
910
911 static EmpathyContact *
912 chat_lookup_contact (EmpathyTpChat *chat,
913                      TpHandle       handle,
914                      gboolean       remove_)
915 {
916         EmpathyTpChatPriv *priv = GET_PRIV (chat);
917         GList *l;
918
919         for (l = priv->members; l; l = l->next) {
920                 EmpathyContact *c = l->data;
921
922                 if (empathy_contact_get_handle (c) != handle) {
923                         continue;
924                 }
925
926                 if (remove_) {
927                         /* Caller takes the reference. */
928                         priv->members = g_list_delete_link (priv->members, l);
929                 } else {
930                         g_object_ref (c);
931                 }
932
933                 return c;
934         }
935
936         return NULL;
937 }
938
939 typedef struct
940 {
941     TpHandle old_handle;
942     guint reason;
943     gchar *message;
944 } ContactRenameData;
945
946 static ContactRenameData *
947 contact_rename_data_new (TpHandle handle,
948                          guint reason,
949                          const gchar* message)
950 {
951         ContactRenameData *data = g_new (ContactRenameData, 1);
952         data->old_handle = handle;
953         data->reason = reason;
954         data->message = g_strdup (message);
955
956         return data;
957 }
958
959 static void
960 contact_rename_data_free (ContactRenameData* data)
961 {
962         g_free (data->message);
963         g_free (data);
964 }
965
966 static void
967 tp_chat_got_renamed_contacts_cb (TpConnection            *connection,
968                                  guint                    n_contacts,
969                                  EmpathyContact * const * contacts,
970                                  guint                    n_failed,
971                                  const TpHandle          *failed,
972                                  const GError            *error,
973                                  gpointer                 user_data,
974                                  GObject                 *chat)
975 {
976         EmpathyTpChatPriv *priv = GET_PRIV (chat);
977         const TpIntSet *members;
978         TpHandle handle;
979         EmpathyContact *old = NULL, *new = NULL;
980         ContactRenameData *rename_data = (ContactRenameData *) user_data;
981
982         if (error) {
983                 DEBUG ("Error: %s", error->message);
984                 return;
985         }
986
987         /* renamed members can only be delivered one at a time */
988         g_warn_if_fail (n_contacts == 1);
989
990         new = contacts[0];
991
992         members = tp_channel_group_get_members (priv->channel);
993         handle = empathy_contact_get_handle (new);
994
995         old = chat_lookup_contact (EMPATHY_TP_CHAT (chat),
996                                    rename_data->old_handle, TRUE);
997
998         /* Make sure the contact is still member */
999         if (tp_intset_is_member (members, handle)) {
1000                 priv->members = g_list_prepend (priv->members,
1001                         g_object_ref (new));
1002
1003                 if (old != NULL) {
1004                         g_signal_emit_by_name (chat, "member-renamed",
1005                                                old, new, rename_data->reason,
1006                                                rename_data->message);
1007                         g_object_unref (old);
1008                 }
1009         }
1010
1011         if (priv->user == old) {
1012                 /* We change our nick */
1013                 tp_clear_object (&priv->user);
1014                 priv->user = g_object_ref (new);
1015         }
1016
1017         tp_chat_update_remote_contact (EMPATHY_TP_CHAT (chat));
1018         check_almost_ready (EMPATHY_TP_CHAT (chat));
1019 }
1020
1021
1022 static void
1023 tp_chat_group_members_changed_cb (TpChannel     *self,
1024                                   gchar         *message,
1025                                   GArray        *added,
1026                                   GArray        *removed,
1027                                   GArray        *local_pending,
1028                                   GArray        *remote_pending,
1029                                   guint          actor,
1030                                   guint          reason,
1031                                   EmpathyTpChat *chat)
1032 {
1033         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1034         EmpathyContact *contact;
1035         EmpathyContact *actor_contact = NULL;
1036         guint i;
1037         ContactRenameData *rename_data;
1038         TpHandle old_handle;
1039
1040         /* Contact renamed */
1041         if (reason == TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED) {
1042                 /* there can only be a single 'added' and a single 'removed' handle */
1043                 if (removed->len != 1 || added->len != 1) {
1044                         g_warning ("RENAMED with %u added, %u removed (expected 1, 1)",
1045                                 added->len, removed->len);
1046                         return;
1047                 }
1048
1049                 old_handle = g_array_index (removed, guint, 0);
1050
1051                 rename_data = contact_rename_data_new (old_handle, reason, message);
1052                 empathy_tp_contact_factory_get_from_handles (priv->connection,
1053                         added->len, (TpHandle *) added->data,
1054                         tp_chat_got_renamed_contacts_cb,
1055                         rename_data, (GDestroyNotify) contact_rename_data_free,
1056                         G_OBJECT (chat));
1057                 return;
1058         }
1059
1060         if (actor != 0) {
1061                 actor_contact = chat_lookup_contact (chat, actor, FALSE);
1062                 if (actor_contact == NULL) {
1063                         /* FIXME: handle this a tad more gracefully: perhaps
1064                          * the actor was a server op. We could use the
1065                          * contact-ids detail of MembersChangedDetailed.
1066                          */
1067                         DEBUG ("actor %u not a channel member", actor);
1068                 }
1069         }
1070
1071         /* Remove contacts that are not members anymore */
1072         for (i = 0; i < removed->len; i++) {
1073                 contact = chat_lookup_contact (chat,
1074                         g_array_index (removed, TpHandle, i), TRUE);
1075
1076                 if (contact != NULL) {
1077                         g_signal_emit_by_name (chat, "members-changed", contact,
1078                                                actor_contact, reason, message,
1079                                                FALSE);
1080                         g_object_unref (contact);
1081                 }
1082         }
1083
1084         /* Request added contacts */
1085         if (added->len > 0) {
1086                 empathy_tp_contact_factory_get_from_handles (priv->connection,
1087                         added->len, (TpHandle *) added->data,
1088                         tp_chat_got_added_contacts_cb, NULL, NULL,
1089                         G_OBJECT (chat));
1090         }
1091
1092         tp_chat_update_remote_contact (chat);
1093
1094         if (actor_contact != NULL) {
1095                 g_object_unref (actor_contact);
1096         }
1097 }
1098
1099 static void
1100 tp_chat_got_remote_contact_cb (TpConnection            *connection,
1101                                EmpathyContact          *contact,
1102                                const GError            *error,
1103                                gpointer                 user_data,
1104                                GObject                 *chat)
1105 {
1106         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1107
1108         if (error) {
1109                 DEBUG ("Error: %s", error->message);
1110                 empathy_tp_chat_leave (EMPATHY_TP_CHAT (chat), "");
1111                 return;
1112         }
1113
1114         priv->remote_contact = g_object_ref (contact);
1115         g_object_notify (chat, "remote-contact");
1116
1117         check_almost_ready (EMPATHY_TP_CHAT (chat));
1118 }
1119
1120 static void
1121 tp_chat_got_self_contact_cb (TpConnection            *connection,
1122                              EmpathyContact          *contact,
1123                              const GError            *error,
1124                              gpointer                 user_data,
1125                              GObject                 *chat)
1126 {
1127         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1128
1129         if (error) {
1130                 DEBUG ("Error: %s", error->message);
1131                 empathy_tp_chat_leave (EMPATHY_TP_CHAT (chat), "");
1132                 return;
1133         }
1134
1135         priv->user = g_object_ref (contact);
1136         empathy_contact_set_is_user (priv->user, TRUE);
1137         check_almost_ready (EMPATHY_TP_CHAT (chat));
1138 }
1139
1140 static void
1141 password_flags_changed_cb (TpChannel *channel,
1142     guint added,
1143     guint removed,
1144     gpointer user_data,
1145     GObject *weak_object)
1146 {
1147         EmpathyTpChat *self = EMPATHY_TP_CHAT (weak_object);
1148         EmpathyTpChatPriv *priv = GET_PRIV (self);
1149         gboolean was_needed, needed;
1150
1151         was_needed = empathy_tp_chat_password_needed (self);
1152
1153         priv->password_flags |= added;
1154         priv->password_flags ^= removed;
1155
1156         needed = empathy_tp_chat_password_needed (self);
1157
1158         if (was_needed != needed)
1159                 g_object_notify (G_OBJECT (self), "password-needed");
1160 }
1161
1162 static void
1163 got_password_flags_cb (TpChannel *proxy,
1164                              guint password_flags,
1165                              const GError *error,
1166                              gpointer user_data,
1167                              GObject *weak_object)
1168 {
1169         EmpathyTpChat *self = EMPATHY_TP_CHAT (weak_object);
1170         EmpathyTpChatPriv *priv = GET_PRIV (self);
1171
1172         priv->got_password_flags = TRUE;
1173         priv->password_flags = password_flags;
1174
1175         check_almost_ready (EMPATHY_TP_CHAT (self));
1176 }
1177
1178 static GObject *
1179 tp_chat_constructor (GType                  type,
1180                      guint                  n_props,
1181                      GObjectConstructParam *props)
1182 {
1183         GObject           *chat;
1184         EmpathyTpChatPriv *priv;
1185         TpHandle           handle;
1186
1187         chat = G_OBJECT_CLASS (empathy_tp_chat_parent_class)->constructor (type, n_props, props);
1188
1189         priv = GET_PRIV (chat);
1190
1191         priv->connection = g_object_ref (tp_account_get_connection (priv->account));
1192         tp_g_signal_connect_object (priv->channel, "invalidated",
1193                           G_CALLBACK (tp_chat_invalidated_cb),
1194                           chat, 0);
1195
1196         g_assert (tp_proxy_is_prepared (priv->connection,
1197                 TP_CONNECTION_FEATURE_CAPABILITIES));
1198
1199         if (tp_proxy_has_interface_by_id (priv->channel,
1200                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
1201                 const TpIntSet *members;
1202                 GArray *handles;
1203
1204                 /* Get self contact from the group's self handle */
1205                 handle = tp_channel_group_get_self_handle (priv->channel);
1206                 empathy_tp_contact_factory_get_from_handle (priv->connection,
1207                         handle, tp_chat_got_self_contact_cb,
1208                         NULL, NULL, chat);
1209
1210                 /* Get initial member contacts */
1211                 members = tp_channel_group_get_members (priv->channel);
1212                 handles = tp_intset_to_array (members);
1213                 empathy_tp_contact_factory_get_from_handles (priv->connection,
1214                         handles->len, (TpHandle *) handles->data,
1215                         tp_chat_got_added_contacts_cb, NULL, NULL, chat);
1216
1217                 priv->can_upgrade_to_muc = FALSE;
1218
1219                 tp_g_signal_connect_object (priv->channel, "group-members-changed",
1220                         G_CALLBACK (tp_chat_group_members_changed_cb), chat, 0);
1221         } else {
1222                 TpCapabilities *caps;
1223                 GPtrArray *classes;
1224                 guint i;
1225
1226                 /* Get the self contact from the connection's self handle */
1227                 handle = tp_connection_get_self_handle (priv->connection);
1228                 empathy_tp_contact_factory_get_from_handle (priv->connection,
1229                         handle, tp_chat_got_self_contact_cb,
1230                         NULL, NULL, chat);
1231
1232                 /* Get the remote contact */
1233                 handle = tp_channel_get_handle (priv->channel, NULL);
1234                 empathy_tp_contact_factory_get_from_handle (priv->connection,
1235                         handle, tp_chat_got_remote_contact_cb,
1236                         NULL, NULL, chat);
1237
1238                 caps = tp_connection_get_capabilities (priv->connection);
1239                 g_assert (caps != NULL);
1240
1241                 classes = tp_capabilities_get_channel_classes (caps);
1242
1243                 for (i = 0; i < classes->len; i++) {
1244                         GValueArray *array = g_ptr_array_index (classes, i);
1245                         const char **oprops = g_value_get_boxed (
1246                                 g_value_array_get_nth (array, 1));
1247
1248                         if (tp_strv_contains (oprops, TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_CHANNELS)) {
1249                                 priv->can_upgrade_to_muc = TRUE;
1250                                 break;
1251                         }
1252                 }
1253         }
1254
1255         if (tp_proxy_has_interface_by_id (priv->channel,
1256                                           TP_IFACE_QUARK_PROPERTIES_INTERFACE)) {
1257                 tp_cli_properties_interface_call_list_properties (priv->channel, -1,
1258                                                                   tp_chat_list_properties_cb,
1259                                                                   NULL, NULL,
1260                                                                   G_OBJECT (chat));
1261                 tp_cli_properties_interface_connect_to_properties_changed (priv->channel,
1262                                                                            tp_chat_properties_changed_cb,
1263                                                                            NULL, NULL,
1264                                                                            G_OBJECT (chat), NULL);
1265                 tp_cli_properties_interface_connect_to_property_flags_changed (priv->channel,
1266                                                                                tp_chat_property_flags_changed_cb,
1267                                                                                NULL, NULL,
1268                                                                                G_OBJECT (chat), NULL);
1269         }
1270
1271         /* Check if the chat is password protected */
1272         if (tp_proxy_has_interface_by_id (priv->channel,
1273                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_PASSWORD)) {
1274                 priv->got_password_flags = FALSE;
1275
1276                 tp_cli_channel_interface_password_connect_to_password_flags_changed
1277                         (priv->channel, password_flags_changed_cb, chat, NULL,
1278                          G_OBJECT (chat), NULL);
1279
1280                 tp_cli_channel_interface_password_call_get_password_flags
1281                         (priv->channel, -1, got_password_flags_cb, chat, NULL, chat);
1282         } else {
1283                 /* No Password interface, so no need to fetch the password flags */
1284                 priv->got_password_flags = TRUE;
1285         }
1286
1287         return chat;
1288 }
1289
1290 static void
1291 tp_chat_get_property (GObject    *object,
1292                       guint       param_id,
1293                       GValue     *value,
1294                       GParamSpec *pspec)
1295 {
1296         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
1297         EmpathyTpChatPriv *priv = GET_PRIV (object);
1298
1299         switch (param_id) {
1300         case PROP_ACCOUNT:
1301                 g_value_set_object (value, priv->account);
1302                 break;
1303         case PROP_CHANNEL:
1304                 g_value_set_object (value, priv->channel);
1305                 break;
1306         case PROP_REMOTE_CONTACT:
1307                 g_value_set_object (value, priv->remote_contact);
1308                 break;
1309         case PROP_READY:
1310                 g_value_set_boolean (value, priv->ready);
1311                 break;
1312         case PROP_PASSWORD_NEEDED:
1313                 g_value_set_boolean (value, empathy_tp_chat_password_needed (self));
1314                 break;
1315         default:
1316                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1317                 break;
1318         };
1319 }
1320
1321 static void
1322 tp_chat_set_property (GObject      *object,
1323                       guint         param_id,
1324                       const GValue *value,
1325                       GParamSpec   *pspec)
1326 {
1327         EmpathyTpChatPriv *priv = GET_PRIV (object);
1328
1329         switch (param_id) {
1330         case PROP_ACCOUNT:
1331                 priv->account = g_value_dup_object (value);
1332                 break;
1333         case PROP_CHANNEL:
1334                 priv->channel = g_value_dup_object (value);
1335                 break;
1336         default:
1337                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1338                 break;
1339         };
1340 }
1341
1342 static void
1343 empathy_tp_chat_class_init (EmpathyTpChatClass *klass)
1344 {
1345         GObjectClass *object_class = G_OBJECT_CLASS (klass);
1346
1347         object_class->dispose = tp_chat_dispose;
1348         object_class->finalize = tp_chat_finalize;
1349         object_class->constructor = tp_chat_constructor;
1350         object_class->get_property = tp_chat_get_property;
1351         object_class->set_property = tp_chat_set_property;
1352
1353         g_object_class_install_property (object_class,
1354                                          PROP_ACCOUNT,
1355                                          g_param_spec_object ("account",
1356                                                               "TpAccount",
1357                                                               "the account associated with the chat",
1358                                                               TP_TYPE_ACCOUNT,
1359                                                               G_PARAM_READWRITE |
1360                                                               G_PARAM_CONSTRUCT_ONLY |
1361                                                               G_PARAM_STATIC_STRINGS));
1362
1363         g_object_class_install_property (object_class,
1364                                          PROP_CHANNEL,
1365                                          g_param_spec_object ("channel",
1366                                                               "telepathy channel",
1367                                                               "The text channel for the chat",
1368                                                               TP_TYPE_CHANNEL,
1369                                                               G_PARAM_READWRITE |
1370                                                               G_PARAM_CONSTRUCT_ONLY));
1371
1372         g_object_class_install_property (object_class,
1373                                          PROP_REMOTE_CONTACT,
1374                                          g_param_spec_object ("remote-contact",
1375                                                               "The remote contact",
1376                                                               "The remote contact if there is no group iface on the channel",
1377                                                               EMPATHY_TYPE_CONTACT,
1378                                                               G_PARAM_READABLE));
1379
1380         g_object_class_install_property (object_class,
1381                                          PROP_READY,
1382                                          g_param_spec_boolean ("ready",
1383                                                                "Is the object ready",
1384                                                                "This object can't be used until this becomes true",
1385                                                                FALSE,
1386                                                                G_PARAM_READABLE));
1387
1388         g_object_class_install_property (object_class,
1389                                          PROP_PASSWORD_NEEDED,
1390                                          g_param_spec_boolean ("password-needed",
1391                                                                "password needed",
1392                                                                "TRUE if a password is needed to join the channel",
1393                                                                FALSE,
1394                                                                G_PARAM_READABLE));
1395
1396         /* Signals */
1397         signals[MESSAGE_RECEIVED] =
1398                 g_signal_new ("message-received",
1399                               G_TYPE_FROM_CLASS (klass),
1400                               G_SIGNAL_RUN_LAST,
1401                               0,
1402                               NULL, NULL,
1403                               g_cclosure_marshal_VOID__OBJECT,
1404                               G_TYPE_NONE,
1405                               1, EMPATHY_TYPE_MESSAGE);
1406
1407         signals[SEND_ERROR] =
1408                 g_signal_new ("send-error",
1409                               G_TYPE_FROM_CLASS (klass),
1410                               G_SIGNAL_RUN_LAST,
1411                               0,
1412                               NULL, NULL,
1413                               _empathy_marshal_VOID__STRING_UINT,
1414                               G_TYPE_NONE,
1415                               2, G_TYPE_STRING, G_TYPE_UINT);
1416
1417         signals[CHAT_STATE_CHANGED] =
1418                 g_signal_new ("chat-state-changed",
1419                               G_TYPE_FROM_CLASS (klass),
1420                               G_SIGNAL_RUN_LAST,
1421                               0,
1422                               NULL, NULL,
1423                               _empathy_marshal_VOID__OBJECT_UINT,
1424                               G_TYPE_NONE,
1425                               2, EMPATHY_TYPE_CONTACT, G_TYPE_UINT);
1426
1427         signals[PROPERTY_CHANGED] =
1428                 g_signal_new ("property-changed",
1429                               G_TYPE_FROM_CLASS (klass),
1430                               G_SIGNAL_RUN_LAST,
1431                               0,
1432                               NULL, NULL,
1433                               _empathy_marshal_VOID__STRING_BOXED,
1434                               G_TYPE_NONE,
1435                               2, G_TYPE_STRING, G_TYPE_VALUE);
1436
1437         signals[DESTROY] =
1438                 g_signal_new ("destroy",
1439                               G_TYPE_FROM_CLASS (klass),
1440                               G_SIGNAL_RUN_LAST,
1441                               0,
1442                               NULL, NULL,
1443                               g_cclosure_marshal_VOID__VOID,
1444                               G_TYPE_NONE,
1445                               0);
1446
1447         g_type_class_add_private (object_class, sizeof (EmpathyTpChatPriv));
1448 }
1449
1450 static void
1451 empathy_tp_chat_init (EmpathyTpChat *chat)
1452 {
1453         EmpathyTpChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
1454                 EMPATHY_TYPE_TP_CHAT, EmpathyTpChatPriv);
1455
1456         chat->priv = priv;
1457         priv->messages_queue = g_queue_new ();
1458         priv->pending_messages_queue = g_queue_new ();
1459 }
1460
1461 static void
1462 tp_chat_iface_init (EmpathyContactListIface *iface)
1463 {
1464         iface->add         = tp_chat_add;
1465         iface->remove      = tp_chat_remove;
1466         iface->get_members = tp_chat_get_members;
1467 }
1468
1469 EmpathyTpChat *
1470 empathy_tp_chat_new (TpAccount *account,
1471                      TpChannel *channel)
1472 {
1473         g_return_val_if_fail (TP_IS_ACCOUNT (account), NULL);
1474         g_return_val_if_fail (TP_IS_TEXT_CHANNEL (channel), NULL);
1475
1476         return g_object_new (EMPATHY_TYPE_TP_CHAT,
1477                              "account", account,
1478                              "channel", channel,
1479                              NULL);
1480 }
1481
1482 const gchar *
1483 empathy_tp_chat_get_id (EmpathyTpChat *chat)
1484 {
1485         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1486         const gchar *id;
1487
1488
1489         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1490
1491         id = tp_channel_get_identifier (priv->channel);
1492         if (!EMP_STR_EMPTY (id))
1493                 return id;
1494         else if (priv->remote_contact)
1495                 return empathy_contact_get_id (priv->remote_contact);
1496         else
1497                 return NULL;
1498
1499 }
1500
1501 EmpathyContact *
1502 empathy_tp_chat_get_remote_contact (EmpathyTpChat *chat)
1503 {
1504         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1505
1506         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1507         g_return_val_if_fail (priv->ready, NULL);
1508
1509         return priv->remote_contact;
1510 }
1511
1512 TpChannel *
1513 empathy_tp_chat_get_channel (EmpathyTpChat *chat)
1514 {
1515         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1516
1517         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1518
1519         return priv->channel;
1520 }
1521
1522 TpAccount *
1523 empathy_tp_chat_get_account (EmpathyTpChat *chat)
1524 {
1525         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1526
1527         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1528
1529         return priv->account;
1530 }
1531
1532 TpConnection *
1533 empathy_tp_chat_get_connection (EmpathyTpChat *chat)
1534 {
1535         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1536
1537         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1538
1539         return tp_channel_borrow_connection (priv->channel);
1540 }
1541 gboolean
1542 empathy_tp_chat_is_ready (EmpathyTpChat *chat)
1543 {
1544         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1545
1546         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), FALSE);
1547
1548         return priv->ready;
1549 }
1550
1551 void
1552 empathy_tp_chat_send (EmpathyTpChat *chat,
1553                       EmpathyMessage *message)
1554 {
1555         EmpathyTpChatPriv        *priv = GET_PRIV (chat);
1556         const gchar              *message_body;
1557         TpChannelTextMessageType  message_type;
1558
1559         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1560         g_return_if_fail (EMPATHY_IS_MESSAGE (message));
1561         g_return_if_fail (priv->ready);
1562
1563         message_body = empathy_message_get_body (message);
1564         message_type = empathy_message_get_tptype (message);
1565
1566         DEBUG ("Sending message: %s", message_body);
1567         tp_cli_channel_type_text_call_send (priv->channel, -1,
1568                                             message_type,
1569                                             message_body,
1570                                             tp_chat_send_cb,
1571                                             g_object_ref (message),
1572                                             (GDestroyNotify) g_object_unref,
1573                                             G_OBJECT (chat));
1574 }
1575
1576 void
1577 empathy_tp_chat_set_state (EmpathyTpChat      *chat,
1578                            TpChannelChatState  state)
1579 {
1580         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1581
1582         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1583         g_return_if_fail (priv->ready);
1584
1585         if (tp_proxy_has_interface_by_id (priv->channel,
1586                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_CHAT_STATE)) {
1587                 DEBUG ("Set state: %d", state);
1588                 tp_cli_channel_interface_chat_state_call_set_chat_state (priv->channel, -1,
1589                                                                          state,
1590                                                                          tp_chat_async_cb,
1591                                                                          "setting chat state",
1592                                                                          NULL,
1593                                                                          G_OBJECT (chat));
1594         }
1595 }
1596
1597
1598 const GList *
1599 empathy_tp_chat_get_pending_messages (EmpathyTpChat *chat)
1600 {
1601         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1602
1603         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1604         g_return_val_if_fail (priv->ready, NULL);
1605
1606         return priv->pending_messages_queue->head;
1607 }
1608
1609 static void
1610 acknowledge_messages (EmpathyTpChat *chat, GArray *ids) {
1611         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1612
1613         tp_cli_channel_type_text_call_acknowledge_pending_messages (
1614                 priv->channel, -1, ids, tp_chat_async_cb,
1615                 "acknowledging received message", NULL, G_OBJECT (chat));
1616 }
1617
1618 void
1619 empathy_tp_chat_acknowledge_message (EmpathyTpChat *chat,
1620                                      EmpathyMessage *message) {
1621         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1622         GArray *message_ids;
1623         GList *m;
1624         guint id;
1625
1626         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1627         g_return_if_fail (priv->ready);
1628
1629         if (!empathy_message_is_incoming (message))
1630                 goto out;
1631
1632         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
1633
1634         id = empathy_message_get_id (message);
1635         g_array_append_val (message_ids, id);
1636         acknowledge_messages (chat, message_ids);
1637         g_array_free (message_ids, TRUE);
1638
1639 out:
1640         m = g_queue_find (priv->pending_messages_queue, message);
1641         g_assert (m != NULL);
1642         g_queue_delete_link (priv->pending_messages_queue, m);
1643         g_object_unref (message);
1644 }
1645
1646 void
1647 empathy_tp_chat_acknowledge_messages (EmpathyTpChat *chat,
1648                                       const GSList *messages) {
1649         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1650         /* Copy messages as the messges list (probably is) our own */
1651         GSList *msgs = g_slist_copy ((GSList *) messages);
1652         GSList *l;
1653         guint length;
1654         GArray *message_ids;
1655
1656         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1657         g_return_if_fail (priv->ready);
1658
1659         length = g_slist_length ((GSList *) messages);
1660
1661         if (length == 0)
1662                 return;
1663
1664         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), length);
1665
1666         for (l = msgs; l != NULL; l = g_slist_next (l)) {
1667                 GList *m;
1668
1669                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1670
1671                 m = g_queue_find (priv->pending_messages_queue, message);
1672                 g_assert (m != NULL);
1673                 g_queue_delete_link (priv->pending_messages_queue, m);
1674
1675                 if (empathy_message_is_incoming (message)) {
1676                         guint id = empathy_message_get_id (message);
1677                         g_array_append_val (message_ids, id);
1678                 }
1679                 g_object_unref (message);
1680         }
1681
1682         if (message_ids->len > 0)
1683                 acknowledge_messages (chat, message_ids);
1684
1685         g_array_free (message_ids, TRUE);
1686         g_slist_free (msgs);
1687 }
1688
1689 void
1690 empathy_tp_chat_acknowledge_all_messages (EmpathyTpChat *chat)
1691 {
1692   empathy_tp_chat_acknowledge_messages (chat,
1693     (GSList *) empathy_tp_chat_get_pending_messages (chat));
1694 }
1695
1696 gboolean
1697 empathy_tp_chat_password_needed (EmpathyTpChat *self)
1698 {
1699         EmpathyTpChatPriv *priv = GET_PRIV (self);
1700
1701         return priv->password_flags & TP_CHANNEL_PASSWORD_FLAG_PROVIDE;
1702 }
1703
1704 static void
1705 provide_password_cb (TpChannel *channel,
1706                                       gboolean correct,
1707                                       const GError *error,
1708                                       gpointer user_data,
1709                                       GObject *weak_object)
1710 {
1711         GSimpleAsyncResult *result = user_data;
1712
1713         if (error != NULL) {
1714                 g_simple_async_result_set_from_error (result, error);
1715         }
1716         else if (!correct) {
1717                 /* The current D-Bus API is a bit weird so re-use the
1718                  * AuthenticationFailed error */
1719                 g_simple_async_result_set_error (result, TP_ERRORS,
1720                                                  TP_ERROR_AUTHENTICATION_FAILED, "Wrong password");
1721         }
1722
1723         g_simple_async_result_complete (result);
1724         g_object_unref (result);
1725 }
1726
1727 void
1728 empathy_tp_chat_provide_password_async (EmpathyTpChat *self,
1729                                                      const gchar *password,
1730                                                      GAsyncReadyCallback callback,
1731                                                      gpointer user_data)
1732 {
1733         EmpathyTpChatPriv *priv = GET_PRIV (self);
1734         GSimpleAsyncResult *result;
1735
1736         result = g_simple_async_result_new (G_OBJECT (self),
1737                                             callback, user_data,
1738                                             empathy_tp_chat_provide_password_finish);
1739
1740         tp_cli_channel_interface_password_call_provide_password
1741                 (priv->channel, -1, password, provide_password_cb, result,
1742                  NULL, G_OBJECT (self));
1743 }
1744
1745 gboolean
1746 empathy_tp_chat_provide_password_finish (EmpathyTpChat *self,
1747                                                       GAsyncResult *result,
1748                                                       GError **error)
1749 {
1750         if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result),
1751                 error))
1752                 return FALSE;
1753
1754         g_return_val_if_fail (g_simple_async_result_is_valid (result,
1755                                                               G_OBJECT (self), empathy_tp_chat_provide_password_finish), FALSE);
1756
1757         return TRUE;
1758 }
1759
1760 /**
1761  * empathy_tp_chat_can_add_contact:
1762  *
1763  * Returns: %TRUE if empathy_contact_list_add() will work for this channel.
1764  * That is if this chat is a 1-to-1 channel that can be upgraded to
1765  * a MUC using the Conference interface or if the channel is a MUC.
1766  */
1767 gboolean
1768 empathy_tp_chat_can_add_contact (EmpathyTpChat *self)
1769 {
1770         EmpathyTpChatPriv *priv;
1771
1772         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), FALSE);
1773
1774         priv = GET_PRIV (self);
1775
1776         return priv->can_upgrade_to_muc ||
1777                 tp_proxy_has_interface_by_id (priv->channel,
1778                         TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP);;
1779 }
1780
1781 static void
1782 tp_channel_leave_async_cb (GObject *source_object,
1783         GAsyncResult *res,
1784         gpointer user_data)
1785 {
1786         GError *error = NULL;
1787
1788         if (!tp_channel_leave_finish (TP_CHANNEL (source_object), res, &error)) {
1789                 DEBUG ("Could not leave channel properly: (%s); closing the channel",
1790                         error->message);
1791                 g_error_free (error);
1792         }
1793 }
1794
1795 void
1796 empathy_tp_chat_leave (EmpathyTpChat *self,
1797                 const gchar *message)
1798 {
1799         EmpathyTpChatPriv *priv = GET_PRIV (self);
1800
1801         tp_channel_leave_async (priv->channel, TP_CHANNEL_GROUP_CHANGE_REASON_NONE,
1802                 message, tp_channel_leave_async_cb, self);
1803 }
1804
1805 static void
1806 add_members_cb (TpChannel *proxy,
1807                 const GError *error,
1808                 gpointer user_data,
1809                 GObject *weak_object)
1810 {
1811         EmpathyTpChatPriv *priv = GET_PRIV (weak_object);
1812
1813         if (error != NULL) {
1814                 DEBUG ("Failed to join chat (%s): %s",
1815                         tp_channel_get_identifier (priv->channel), error->message);
1816         }
1817 }
1818
1819 void
1820 empathy_tp_chat_join (EmpathyTpChat *self)
1821 {
1822         EmpathyTpChatPriv *priv = GET_PRIV (self);
1823         TpHandle self_handle;
1824         GArray *members;
1825
1826         self_handle = tp_channel_group_get_self_handle (priv->channel);
1827
1828         members = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), 1);
1829         g_array_append_val (members, self_handle);
1830
1831         tp_cli_channel_interface_group_call_add_members (priv->channel, -1, members,
1832                 "", add_members_cb, NULL, NULL, G_OBJECT (self));
1833
1834         g_array_free (members, TRUE);
1835 }
1836
1837 gboolean
1838 empathy_tp_chat_is_invited (EmpathyTpChat *self,
1839                             TpHandle *inviter)
1840 {
1841         EmpathyTpChatPriv *priv = GET_PRIV (self);
1842         TpHandle self_handle;
1843
1844         if (!tp_proxy_has_interface (priv->channel, TP_IFACE_CHANNEL_INTERFACE_GROUP))
1845                 return FALSE;
1846
1847         self_handle = tp_channel_group_get_self_handle (priv->channel);
1848         if (self_handle == 0)
1849                 return FALSE;
1850
1851         return tp_channel_group_get_local_pending_info (priv->channel, self_handle,
1852                 inviter, NULL, NULL);
1853 }
1854
1855 TpChannelChatState
1856 empathy_tp_chat_get_chat_state (EmpathyTpChat *chat,
1857                             EmpathyContact *contact)
1858 {
1859         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1860         return tp_channel_get_chat_state (priv->channel,
1861                 empathy_contact_get_handle (contact));
1862 }
1863
1864 EmpathyContact *
1865 empathy_tp_chat_get_self_contact (EmpathyTpChat *self)
1866 {
1867         EmpathyTpChatPriv *priv = GET_PRIV (self);
1868
1869         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), NULL);
1870
1871         return priv->user;
1872 }