]> git.0d.be Git - empathy.git/blob - libempathy/empathy-tp-chat.c
Merge remote-tracking branch 'jonny/ft'
[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-request-util.h"
34 #include "empathy-time.h"
35 #include "empathy-utils.h"
36
37 #define DEBUG_FLAG EMPATHY_DEBUG_TP | EMPATHY_DEBUG_CHAT
38 #include "empathy-debug.h"
39
40 struct _EmpathyTpChatPrivate {
41         TpAccount             *account;
42         EmpathyContact        *user;
43         EmpathyContact        *remote_contact;
44         GList                 *members;
45         /* Queue of messages not signalled yet */
46         GQueue                *messages_queue;
47         /* Queue of messages signalled but not acked yet */
48         GQueue                *pending_messages_queue;
49
50         /* Subject */
51         gboolean               supports_subject;
52         gboolean               can_set_subject;
53         gchar                 *subject;
54
55         /* Room config (for now, we only track the title and don't support
56          * setting it) */
57         gchar                 *title;
58
59         gboolean               can_upgrade_to_muc;
60
61         GHashTable            *messages_being_sent;
62
63         /* GSimpleAsyncResult used when preparing EMPATHY_TP_CHAT_FEATURE_CORE */
64         GSimpleAsyncResult    *ready_result;
65 };
66
67 static void tp_chat_iface_init         (EmpathyContactListIface *iface);
68
69 enum {
70         PROP_0,
71         PROP_ACCOUNT,
72         PROP_REMOTE_CONTACT,
73         PROP_N_MESSAGES_SENDING,
74         PROP_TITLE,
75         PROP_SUBJECT,
76 };
77
78 enum {
79         MESSAGE_RECEIVED,
80         SEND_ERROR,
81         CHAT_STATE_CHANGED,
82         MESSAGE_ACKNOWLEDGED,
83         LAST_SIGNAL
84 };
85
86 static guint signals[LAST_SIGNAL];
87
88 G_DEFINE_TYPE_WITH_CODE (EmpathyTpChat, empathy_tp_chat, TP_TYPE_TEXT_CHANNEL,
89                          G_IMPLEMENT_INTERFACE (EMPATHY_TYPE_CONTACT_LIST,
90                                                 tp_chat_iface_init));
91
92 static void
93 tp_chat_set_delivery_status (EmpathyTpChat         *self,
94                              const gchar           *token,
95                              EmpathyDeliveryStatus  delivery_status)
96 {
97         TpDeliveryReportingSupportFlags flags =
98                 tp_text_channel_get_delivery_reporting_support (
99                         TP_TEXT_CHANNEL (self));
100
101         /* channel must support receiving failures and successes */
102         if (!tp_str_empty (token) &&
103             flags & TP_DELIVERY_REPORTING_SUPPORT_FLAG_RECEIVE_FAILURES &&
104             flags & TP_DELIVERY_REPORTING_SUPPORT_FLAG_RECEIVE_SUCCESSES) {
105
106                 DEBUG ("Delivery status (%s) = %u", token, delivery_status);
107
108                 switch (delivery_status) {
109                         case EMPATHY_DELIVERY_STATUS_NONE:
110                                 g_hash_table_remove (self->priv->messages_being_sent,
111                                         token);
112                                 break;
113
114                         default:
115                                 g_hash_table_insert (self->priv->messages_being_sent,
116                                         g_strdup (token),
117                                         GUINT_TO_POINTER (delivery_status));
118                                 break;
119                 }
120
121                 g_object_notify (G_OBJECT (self), "n-messages-sending");
122         }
123 }
124
125 static void tp_chat_prepare_ready_async (TpProxy *proxy,
126         const TpProxyFeature *feature,
127         GAsyncReadyCallback callback,
128         gpointer user_data);
129
130 static void
131 tp_chat_async_cb (TpChannel *proxy,
132                   const GError *error,
133                   gpointer user_data,
134                   GObject *weak_object)
135 {
136         if (error) {
137                 DEBUG ("Error %s: %s", (gchar *) user_data, error->message);
138         }
139 }
140
141 static void
142 create_conference_cb (GObject *source,
143                       GAsyncResult *result,
144                       gpointer user_data)
145 {
146         GError *error = NULL;
147
148         if (!tp_account_channel_request_create_channel_finish (
149                         TP_ACCOUNT_CHANNEL_REQUEST (source), result, &error)) {
150                 DEBUG ("Failed to create conference channel: %s", error->message);
151                 g_error_free (error);
152         }
153 }
154
155 static void
156 tp_chat_add (EmpathyContactList *list,
157              EmpathyContact     *contact,
158              const gchar        *message)
159 {
160         EmpathyTpChat *self = (EmpathyTpChat *) list;
161         TpChannel *channel = (TpChannel *) self;
162
163         if (tp_proxy_has_interface_by_id (self,
164                 TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
165                 TpHandle           handle;
166                 GArray             handles = {(gchar *) &handle, 1};
167
168                 g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
169                 g_return_if_fail (EMPATHY_IS_CONTACT (contact));
170
171                 handle = empathy_contact_get_handle (contact);
172                 tp_cli_channel_interface_group_call_add_members (channel,
173                         -1, &handles, NULL, NULL, NULL, NULL, NULL);
174         } else if (self->priv->can_upgrade_to_muc) {
175                 TpAccountChannelRequest *req;
176                 GHashTable        *props;
177                 const char        *object_path;
178                 GPtrArray          channels = { (gpointer *) &object_path, 1 };
179                 const char        *invitees[2] = { NULL, };
180
181                 invitees[0] = empathy_contact_get_id (contact);
182                 object_path = tp_proxy_get_object_path (self);
183
184                 props = tp_asv_new (
185                     TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
186                         TP_IFACE_CHANNEL_TYPE_TEXT,
187                     TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT,
188                         TP_HANDLE_TYPE_NONE,
189                     TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_CHANNELS,
190                         TP_ARRAY_TYPE_OBJECT_PATH_LIST, &channels,
191                     TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_INVITEE_IDS,
192                         G_TYPE_STRV, invitees,
193                     /* FIXME: InvitationMessage ? */
194                     NULL);
195
196                 req = tp_account_channel_request_new (self->priv->account, props,
197                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
198
199                 /* Although this is a MUC, it's anonymous, so CreateChannel is
200                  * valid. */
201                 tp_account_channel_request_create_channel_async (req, EMPATHY_CHAT_BUS_NAME,
202                         NULL, create_conference_cb, NULL);
203
204                 g_object_unref (req);
205                 g_hash_table_unref (props);
206         } else {
207                 g_warning ("Cannot add to this channel");
208         }
209 }
210
211 static void
212 tp_chat_remove (EmpathyContactList *list,
213                 EmpathyContact     *contact,
214                 const gchar        *message)
215 {
216         EmpathyTpChat *self = (EmpathyTpChat *) list;
217         TpHandle           handle;
218         GArray             handles = {(gchar *) &handle, 1};
219
220         g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
221         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
222
223         handle = empathy_contact_get_handle (contact);
224         tp_cli_channel_interface_group_call_remove_members ((TpChannel *) self, -1,
225                                                             &handles, NULL,
226                                                             NULL, NULL, NULL,
227                                                             NULL);
228 }
229
230 static GList *
231 tp_chat_get_members (EmpathyContactList *list)
232 {
233         EmpathyTpChat *self = (EmpathyTpChat *) list;
234         GList             *members = NULL;
235
236         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (list), NULL);
237
238         if (self->priv->members) {
239                 members = g_list_copy (self->priv->members);
240                 g_list_foreach (members, (GFunc) g_object_ref, NULL);
241         } else {
242                 members = g_list_prepend (members, g_object_ref (self->priv->user));
243                 if (self->priv->remote_contact != NULL)
244                         members = g_list_prepend (members, g_object_ref (self->priv->remote_contact));
245         }
246
247         return members;
248 }
249
250 static void
251 check_ready (EmpathyTpChat *self)
252 {
253         if (self->priv->ready_result == NULL)
254                 return;
255
256         if (g_queue_get_length (self->priv->messages_queue) > 0)
257                 return;
258
259         DEBUG ("Ready");
260
261         g_simple_async_result_complete (self->priv->ready_result);
262         tp_clear_object (&self->priv->ready_result);
263 }
264
265 static void
266 tp_chat_emit_queued_messages (EmpathyTpChat *self)
267 {
268         EmpathyMessage    *message;
269
270         /* Check if we can now emit some queued messages */
271         while ((message = g_queue_peek_head (self->priv->messages_queue)) != NULL) {
272                 if (empathy_message_get_sender (message) == NULL) {
273                         break;
274                 }
275
276                 DEBUG ("Queued message ready");
277                 g_queue_pop_head (self->priv->messages_queue);
278                 g_queue_push_tail (self->priv->pending_messages_queue, message);
279                 g_signal_emit (self, signals[MESSAGE_RECEIVED], 0, message);
280         }
281
282         check_ready (self);
283 }
284
285 static void
286 tp_chat_got_sender_cb (TpConnection            *connection,
287                        EmpathyContact          *contact,
288                        const GError            *error,
289                        gpointer                 message,
290                        GObject                 *chat)
291 {
292         EmpathyTpChat *self = (EmpathyTpChat *) chat;
293
294         if (error) {
295                 DEBUG ("Error: %s", error->message);
296                 /* Do not block the message queue, just drop this message */
297                 g_queue_remove (self->priv->messages_queue, message);
298         } else {
299                 empathy_message_set_sender (message, contact);
300         }
301
302         tp_chat_emit_queued_messages (EMPATHY_TP_CHAT (self));
303 }
304
305 static void
306 tp_chat_build_message (EmpathyTpChat *self,
307                        TpMessage     *msg,
308                        gboolean       incoming)
309 {
310         EmpathyMessage    *message;
311         TpContact *sender;
312
313         message = empathy_message_new_from_tp_message (msg, incoming);
314         /* FIXME: this is actually a lie for incoming messages. */
315         empathy_message_set_receiver (message, self->priv->user);
316
317         g_queue_push_tail (self->priv->messages_queue, message);
318
319         sender = tp_signalled_message_get_sender (msg);
320         g_assert (sender != NULL);
321
322         if (tp_contact_get_handle (sender) == 0) {
323                 empathy_message_set_sender (message, self->priv->user);
324                 tp_chat_emit_queued_messages (self);
325         } else {
326                 TpConnection *connection = tp_channel_borrow_connection (
327                         (TpChannel *) self);
328
329                 empathy_tp_contact_factory_get_from_handle (connection,
330                         tp_contact_get_handle (sender),
331                         tp_chat_got_sender_cb,
332                         message, NULL, G_OBJECT (self));
333         }
334 }
335
336 static void
337 handle_delivery_report (EmpathyTpChat *self,
338                 TpMessage *message)
339 {
340         TpDeliveryStatus delivery_status;
341         const GHashTable *header;
342         TpChannelTextSendError delivery_error;
343         gboolean valid;
344         GPtrArray *echo;
345         const gchar *message_body = NULL;
346         const gchar *delivery_dbus_error;
347         const gchar *delivery_token = NULL;
348
349         header = tp_message_peek (message, 0);
350         if (header == NULL)
351                 goto out;
352
353         delivery_token = tp_asv_get_string (header, "delivery-token");
354         delivery_status = tp_asv_get_uint32 (header, "delivery-status", &valid);
355
356         if (!valid) {
357                 goto out;
358         } else if (delivery_status == TP_DELIVERY_STATUS_ACCEPTED) {
359                 DEBUG ("Accepted %s", delivery_token);
360                 tp_chat_set_delivery_status (self, delivery_token,
361                         EMPATHY_DELIVERY_STATUS_ACCEPTED);
362                 goto out;
363         } else if (delivery_status == TP_DELIVERY_STATUS_DELIVERED) {
364                 DEBUG ("Delivered %s", delivery_token);
365                 tp_chat_set_delivery_status (self, delivery_token,
366                         EMPATHY_DELIVERY_STATUS_NONE);
367                 goto out;
368         } else if (delivery_status != TP_DELIVERY_STATUS_PERMANENTLY_FAILED &&
369                    delivery_status != TP_DELIVERY_STATUS_TEMPORARILY_FAILED) {
370                 goto out;
371         }
372
373         delivery_error = tp_asv_get_uint32 (header, "delivery-error", &valid);
374         if (!valid)
375                 delivery_error = TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN;
376
377         delivery_dbus_error = tp_asv_get_string (header, "delivery-dbus-error");
378
379         /* TODO: ideally we should use tp-glib API giving us the echoed message as a
380          * TpMessage. (fdo #35884) */
381         echo = tp_asv_get_boxed (header, "delivery-echo",
382                 TP_ARRAY_TYPE_MESSAGE_PART_LIST);
383         if (echo != NULL && echo->len >= 2) {
384                 const GHashTable *echo_body;
385
386                 echo_body = g_ptr_array_index (echo, 1);
387                 if (echo_body != NULL)
388                         message_body = tp_asv_get_string (echo_body, "content");
389         }
390
391         tp_chat_set_delivery_status (self, delivery_token,
392                         EMPATHY_DELIVERY_STATUS_NONE);
393         g_signal_emit (self, signals[SEND_ERROR], 0, message_body,
394                         delivery_error, delivery_dbus_error);
395
396 out:
397         tp_text_channel_ack_message_async (TP_TEXT_CHANNEL (self),
398                 message, NULL, NULL);
399 }
400
401 static void
402 handle_incoming_message (EmpathyTpChat *self,
403                          TpMessage *message,
404                          gboolean pending)
405 {
406         gchar *message_body;
407
408         if (tp_message_is_delivery_report (message)) {
409                 handle_delivery_report (self, message);
410                 return;
411         }
412
413         message_body = tp_message_to_text (message, NULL);
414
415         DEBUG ("Message %s (channel %s): %s",
416                 pending ? "pending" : "received",
417                 tp_proxy_get_object_path (self), message_body);
418
419         if (message_body == NULL) {
420                 DEBUG ("Empty message with NonTextContent, ignoring and acking.");
421
422                 tp_text_channel_ack_message_async (TP_TEXT_CHANNEL (self),
423                         message, NULL, NULL);
424                 return;
425         }
426
427         tp_chat_build_message (self, message, TRUE);
428
429         g_free (message_body);
430 }
431
432 static void
433 message_received_cb (TpTextChannel   *channel,
434                      TpMessage *message,
435                      EmpathyTpChat *self)
436 {
437         handle_incoming_message (self, message, FALSE);
438 }
439
440 static gboolean
441 find_pending_message_func (gconstpointer a,
442                            gconstpointer b)
443 {
444         EmpathyMessage *msg = (EmpathyMessage *) a;
445         TpMessage *message = (TpMessage *) b;
446
447         if (empathy_message_get_tp_message (msg) == message)
448                 return 0;
449
450         return -1;
451 }
452
453 static void
454 pending_message_removed_cb (TpTextChannel   *channel,
455                             TpMessage *message,
456                             EmpathyTpChat *self)
457 {
458         GList *m;
459
460         m = g_queue_find_custom (self->priv->pending_messages_queue, message,
461                                  find_pending_message_func);
462
463         if (m == NULL)
464                 return;
465
466         g_signal_emit (self, signals[MESSAGE_ACKNOWLEDGED], 0, m->data);
467
468         g_object_unref (m->data);
469         g_queue_delete_link (self->priv->pending_messages_queue, m);
470 }
471
472 static void
473 message_sent_cb (TpTextChannel   *channel,
474                  TpMessage *message,
475                  TpMessageSendingFlags flags,
476                  gchar              *token,
477                  EmpathyTpChat      *self)
478 {
479         gchar *message_body;
480
481         message_body = tp_message_to_text (message, NULL);
482
483         DEBUG ("Message sent: %s", message_body);
484
485         tp_chat_build_message (self, message, FALSE);
486
487         g_free (message_body);
488 }
489
490 static TpChannelTextSendError
491 error_to_text_send_error (GError *error)
492 {
493         if (error->domain != TP_ERRORS)
494                 return TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN;
495
496         switch (error->code) {
497                 case TP_ERROR_OFFLINE:
498                         return TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE;
499                 case TP_ERROR_INVALID_HANDLE:
500                         return TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT;
501                 case TP_ERROR_PERMISSION_DENIED:
502                         return TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED;
503                 case TP_ERROR_NOT_IMPLEMENTED:
504                         return TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED;
505         }
506
507         return TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN;
508 }
509
510 static void
511 message_send_cb (GObject *source,
512                  GAsyncResult *result,
513                  gpointer      user_data)
514 {
515         EmpathyTpChat *self = user_data;
516         TpTextChannel *channel = (TpTextChannel *) source;
517         gchar *token = NULL;
518         GError *error = NULL;
519
520         if (!tp_text_channel_send_message_finish (channel, result, &token, &error)) {
521                 DEBUG ("Error: %s", error->message);
522
523                 /* FIXME: we should use the body of the message as first argument of the
524                  * signal but can't easily get it as we just get a user_data pointer. Once
525                  * we'll have rebased EmpathyTpChat on top of TpTextChannel we'll be able
526                  * to use the user_data pointer to pass the message and fix this. */
527                 g_signal_emit (self, signals[SEND_ERROR], 0,
528                                NULL, error_to_text_send_error (error), NULL);
529
530                 g_error_free (error);
531         }
532
533         tp_chat_set_delivery_status (self, token,
534                 EMPATHY_DELIVERY_STATUS_SENDING);
535         g_free (token);
536 }
537
538 typedef struct {
539         EmpathyTpChat *chat;
540         TpChannelChatState state;
541 } StateChangedData;
542
543 static void
544 tp_chat_state_changed_got_contact_cb (TpConnection            *connection,
545                                       EmpathyContact          *contact,
546                                       const GError            *error,
547                                       gpointer                 user_data,
548                                       GObject                 *chat)
549 {
550         TpChannelChatState state;
551
552         if (error) {
553                 DEBUG ("Error: %s", error->message);
554                 return;
555         }
556
557         state = GPOINTER_TO_UINT (user_data);
558         DEBUG ("Chat state changed for %s (%d): %d",
559                 empathy_contact_get_alias (contact),
560                 empathy_contact_get_handle (contact), state);
561
562         g_signal_emit (chat, signals[CHAT_STATE_CHANGED], 0, contact, state);
563 }
564
565 static void
566 tp_chat_state_changed_cb (TpChannel *channel,
567                           TpHandle   handle,
568                           TpChannelChatState state,
569                           EmpathyTpChat *self)
570 {
571         TpConnection *connection = tp_channel_borrow_connection (
572                 (TpChannel *) self);
573
574         empathy_tp_contact_factory_get_from_handle (connection, handle,
575                 tp_chat_state_changed_got_contact_cb, GUINT_TO_POINTER (state),
576                 NULL, G_OBJECT (self));
577 }
578
579 static void
580 list_pending_messages (EmpathyTpChat *self)
581 {
582         GList *messages, *l;
583
584         messages = tp_text_channel_get_pending_messages (
585                 TP_TEXT_CHANNEL (self));
586
587         for (l = messages; l != NULL; l = g_list_next (l)) {
588                 TpMessage *message = l->data;
589
590                 handle_incoming_message (self, message, FALSE);
591         }
592
593         g_list_free (messages);
594 }
595
596 static void
597 update_subject (EmpathyTpChat *self,
598                 GHashTable *properties)
599 {
600         EmpathyTpChatPrivate *priv = self->priv;
601         gboolean can_set, valid;
602         const gchar *subject;
603
604         can_set = tp_asv_get_boolean (properties, "CanSet", &valid);
605         if (valid) {
606                 priv->can_set_subject = can_set;
607         }
608
609         subject = tp_asv_get_string (properties, "Subject");
610         if (subject != NULL) {
611                 g_free (priv->subject);
612                 priv->subject = g_strdup (subject);
613                 g_object_notify (G_OBJECT (self), "subject");
614         }
615
616         /* TODO: track Actor and Timestamp. */
617 }
618
619 static void
620 tp_chat_get_all_subject_cb (TpProxy      *proxy,
621                             GHashTable   *properties,
622                             const GError *error,
623                             gpointer      user_data G_GNUC_UNUSED,
624                             GObject      *chat)
625 {
626         EmpathyTpChat *self = EMPATHY_TP_CHAT (chat);
627         EmpathyTpChatPrivate *priv = self->priv;
628
629         if (error) {
630                 DEBUG ("Error fetching subject: %s", error->message);
631                 return;
632         }
633
634         priv->supports_subject = TRUE;
635         update_subject (self, properties);
636 }
637
638 static void
639 update_title (EmpathyTpChat *self,
640               GHashTable *properties)
641 {
642         EmpathyTpChatPrivate *priv = self->priv;
643         const gchar *title = tp_asv_get_string (properties, "Title");
644
645         if (title != NULL) {
646                 if (tp_str_empty (title)) {
647                         title = NULL;
648                 }
649
650                 g_free (priv->title);
651                 priv->title = g_strdup (title);
652                 g_object_notify (G_OBJECT (self), "title");
653         }
654 }
655
656 static void
657 tp_chat_get_all_room_config_cb (TpProxy      *proxy,
658                                 GHashTable   *properties,
659                                 const GError *error,
660                                 gpointer      user_data G_GNUC_UNUSED,
661                                 GObject      *chat)
662 {
663         EmpathyTpChat *self = EMPATHY_TP_CHAT (chat);
664
665         if (error) {
666                 DEBUG ("Error fetching room config: %s", error->message);
667                 return;
668         }
669
670         update_title (self, properties);
671 }
672
673 static void
674 tp_chat_dbus_properties_changed_cb (TpProxy *proxy,
675                                     const gchar *interface_name,
676                                     GHashTable *changed,
677                                     const gchar **invalidated,
678                                     gpointer user_data,
679                                     GObject *chat)
680 {
681         EmpathyTpChat *self = EMPATHY_TP_CHAT (chat);
682
683         if (!tp_strdiff (interface_name, TP_IFACE_CHANNEL_INTERFACE_SUBJECT)) {
684                 update_subject (self, changed);
685         }
686
687         if (!tp_strdiff (interface_name, TP_IFACE_CHANNEL_INTERFACE_ROOM_CONFIG)) {
688                 update_title (self, changed);
689         }
690 }
691
692 void
693 empathy_tp_chat_set_subject (EmpathyTpChat *self,
694                              const gchar   *subject)
695 {
696         tp_cli_channel_interface_subject_call_set_subject (TP_CHANNEL (self), -1,
697                                                            subject,
698                                                            tp_chat_async_cb,
699                                                            "while setting subject", NULL,
700                                                            G_OBJECT (self));
701 }
702
703 const gchar *
704 empathy_tp_chat_get_title (EmpathyTpChat *self)
705 {
706         EmpathyTpChatPrivate *priv = self->priv;
707
708         return priv->title;
709 }
710
711 gboolean
712 empathy_tp_chat_supports_subject (EmpathyTpChat *self)
713 {
714         EmpathyTpChatPrivate *priv = self->priv;
715
716         return priv->supports_subject;
717 }
718
719 gboolean
720 empathy_tp_chat_can_set_subject (EmpathyTpChat *self)
721 {
722         EmpathyTpChatPrivate *priv = self->priv;
723
724         return priv->can_set_subject;
725 }
726
727 const gchar *
728 empathy_tp_chat_get_subject (EmpathyTpChat *self)
729 {
730         EmpathyTpChatPrivate *priv = self->priv;
731
732         return priv->subject;
733 }
734
735 static void
736 tp_chat_dispose (GObject *object)
737 {
738         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
739
740         tp_clear_object (&self->priv->account);
741         tp_clear_object (&self->priv->remote_contact);
742         tp_clear_object (&self->priv->user);
743
744         g_queue_foreach (self->priv->messages_queue, (GFunc) g_object_unref, NULL);
745         g_queue_clear (self->priv->messages_queue);
746
747         g_queue_foreach (self->priv->pending_messages_queue,
748                 (GFunc) g_object_unref, NULL);
749         g_queue_clear (self->priv->pending_messages_queue);
750
751         tp_clear_object (&self->priv->ready_result);
752
753         if (G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose)
754                 G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose (object);
755 }
756
757 static void
758 tp_chat_finalize (GObject *object)
759 {
760         EmpathyTpChat *self = (EmpathyTpChat *) object;
761
762         DEBUG ("Finalize: %p", object);
763
764         g_queue_free (self->priv->messages_queue);
765         g_queue_free (self->priv->pending_messages_queue);
766         g_hash_table_unref (self->priv->messages_being_sent);
767
768         g_free (self->priv->title);
769         g_free (self->priv->subject);
770
771         G_OBJECT_CLASS (empathy_tp_chat_parent_class)->finalize (object);
772 }
773
774 static void
775 check_almost_ready (EmpathyTpChat *self)
776 {
777         TpChannel *channel = (TpChannel *) self;
778
779         if (self->priv->ready_result == NULL)
780                 return;
781
782         if (self->priv->user == NULL)
783                 return;
784
785         /* We need either the members (room) or the remote contact (private chat).
786          * If the chat is protected by a password we can't get these information so
787          * consider the chat as ready so it can be presented to the user. */
788         if (!tp_channel_password_needed (channel) && self->priv->members == NULL &&
789             self->priv->remote_contact == NULL)
790                 return;
791
792         g_assert (tp_proxy_is_prepared (self,
793                 TP_TEXT_CHANNEL_FEATURE_INCOMING_MESSAGES));
794
795         tp_g_signal_connect_object (self, "message-received",
796                 G_CALLBACK (message_received_cb), self, 0);
797         tp_g_signal_connect_object (self, "pending-message-removed",
798                 G_CALLBACK (pending_message_removed_cb), self, 0);
799
800         list_pending_messages (self);
801
802         tp_g_signal_connect_object (self, "message-sent",
803                 G_CALLBACK (message_sent_cb), self, 0);
804
805         tp_g_signal_connect_object (self, "chat-state-changed",
806                 G_CALLBACK (tp_chat_state_changed_cb), self, 0);
807
808         check_ready (self);
809 }
810
811 static void
812 tp_chat_got_added_contacts_cb (TpConnection            *connection,
813                                guint                    n_contacts,
814                                EmpathyContact * const * contacts,
815                                guint                    n_failed,
816                                const TpHandle          *failed,
817                                const GError            *error,
818                                gpointer                 user_data,
819                                GObject                 *chat)
820 {
821         EmpathyTpChat *self = (EmpathyTpChat *) chat;
822         guint i;
823         const TpIntSet *members;
824         TpHandle handle;
825         EmpathyContact *contact;
826
827         if (error) {
828                 DEBUG ("Error: %s", error->message);
829                 return;
830         }
831
832         members = tp_channel_group_get_members ((TpChannel *) self);
833         for (i = 0; i < n_contacts; i++) {
834                 contact = contacts[i];
835                 handle = empathy_contact_get_handle (contact);
836
837                 /* Make sure the contact is still member */
838                 if (tp_intset_is_member (members, handle)) {
839                         self->priv->members = g_list_prepend (self->priv->members,
840                                 g_object_ref (contact));
841                         g_signal_emit_by_name (chat, "members-changed",
842                                                contact, NULL, 0, NULL, TRUE);
843                 }
844         }
845
846         check_almost_ready (EMPATHY_TP_CHAT (chat));
847 }
848
849 static EmpathyContact *
850 chat_lookup_contact (EmpathyTpChat *self,
851                      TpHandle       handle,
852                      gboolean       remove_)
853 {
854         GList *l;
855
856         for (l = self->priv->members; l; l = l->next) {
857                 EmpathyContact *c = l->data;
858
859                 if (empathy_contact_get_handle (c) != handle) {
860                         continue;
861                 }
862
863                 if (remove_) {
864                         /* Caller takes the reference. */
865                         self->priv->members = g_list_delete_link (self->priv->members, l);
866                 } else {
867                         g_object_ref (c);
868                 }
869
870                 return c;
871         }
872
873         return NULL;
874 }
875
876 typedef struct
877 {
878     TpHandle old_handle;
879     guint reason;
880     gchar *message;
881 } ContactRenameData;
882
883 static ContactRenameData *
884 contact_rename_data_new (TpHandle handle,
885                          guint reason,
886                          const gchar* message)
887 {
888         ContactRenameData *data = g_new (ContactRenameData, 1);
889         data->old_handle = handle;
890         data->reason = reason;
891         data->message = g_strdup (message);
892
893         return data;
894 }
895
896 static void
897 contact_rename_data_free (ContactRenameData* data)
898 {
899         g_free (data->message);
900         g_free (data);
901 }
902
903 static void
904 tp_chat_got_renamed_contacts_cb (TpConnection            *connection,
905                                  guint                    n_contacts,
906                                  EmpathyContact * const * contacts,
907                                  guint                    n_failed,
908                                  const TpHandle          *failed,
909                                  const GError            *error,
910                                  gpointer                 user_data,
911                                  GObject                 *chat)
912 {
913         EmpathyTpChat *self = (EmpathyTpChat *) chat;
914         const TpIntSet *members;
915         TpHandle handle;
916         EmpathyContact *old = NULL, *new = NULL;
917         ContactRenameData *rename_data = (ContactRenameData *) user_data;
918
919         if (error) {
920                 DEBUG ("Error: %s", error->message);
921                 return;
922         }
923
924         /* renamed members can only be delivered one at a time */
925         g_warn_if_fail (n_contacts == 1);
926
927         new = contacts[0];
928
929         members = tp_channel_group_get_members ((TpChannel *) self);
930         handle = empathy_contact_get_handle (new);
931
932         old = chat_lookup_contact (self, rename_data->old_handle, TRUE);
933
934         /* Make sure the contact is still member */
935         if (tp_intset_is_member (members, handle)) {
936                 self->priv->members = g_list_prepend (self->priv->members,
937                         g_object_ref (new));
938
939                 if (old != NULL) {
940                         g_signal_emit_by_name (self, "member-renamed",
941                                                old, new, rename_data->reason,
942                                                rename_data->message);
943                         g_object_unref (old);
944                 }
945         }
946
947         if (self->priv->user == old) {
948                 /* We change our nick */
949                 tp_clear_object (&self->priv->user);
950                 self->priv->user = g_object_ref (new);
951         }
952
953         check_almost_ready (self);
954 }
955
956
957 static void
958 tp_chat_group_members_changed_cb (TpChannel     *channel,
959                                   gchar         *message,
960                                   GArray        *added,
961                                   GArray        *removed,
962                                   GArray        *local_pending,
963                                   GArray        *remote_pending,
964                                   guint          actor,
965                                   guint          reason,
966                                   EmpathyTpChat *self)
967 {
968         EmpathyContact *contact;
969         EmpathyContact *actor_contact = NULL;
970         guint i;
971         ContactRenameData *rename_data;
972         TpHandle old_handle;
973         TpConnection *connection = tp_channel_borrow_connection (
974                 (TpChannel *) self);
975
976         /* Contact renamed */
977         if (reason == TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED) {
978                 /* there can only be a single 'added' and a single 'removed' handle */
979                 if (removed->len != 1 || added->len != 1) {
980                         g_warning ("RENAMED with %u added, %u removed (expected 1, 1)",
981                                 added->len, removed->len);
982                         return;
983                 }
984
985                 old_handle = g_array_index (removed, guint, 0);
986
987                 rename_data = contact_rename_data_new (old_handle, reason, message);
988                 empathy_tp_contact_factory_get_from_handles (connection,
989                         added->len, (TpHandle *) added->data,
990                         tp_chat_got_renamed_contacts_cb,
991                         rename_data, (GDestroyNotify) contact_rename_data_free,
992                         G_OBJECT (self));
993                 return;
994         }
995
996         if (actor != 0) {
997                 actor_contact = chat_lookup_contact (self, actor, FALSE);
998                 if (actor_contact == NULL) {
999                         /* FIXME: handle this a tad more gracefully: perhaps
1000                          * the actor was a server op. We could use the
1001                          * contact-ids detail of MembersChangedDetailed.
1002                          */
1003                         DEBUG ("actor %u not a channel member", actor);
1004                 }
1005         }
1006
1007         /* Remove contacts that are not members anymore */
1008         for (i = 0; i < removed->len; i++) {
1009                 contact = chat_lookup_contact (self,
1010                         g_array_index (removed, TpHandle, i), TRUE);
1011
1012                 if (contact != NULL) {
1013                         g_signal_emit_by_name (self, "members-changed", contact,
1014                                                actor_contact, reason, message,
1015                                                FALSE);
1016                         g_object_unref (contact);
1017                 }
1018         }
1019
1020         /* Request added contacts */
1021         if (added->len > 0) {
1022                 empathy_tp_contact_factory_get_from_handles (connection,
1023                         added->len, (TpHandle *) added->data,
1024                         tp_chat_got_added_contacts_cb, NULL, NULL,
1025                         G_OBJECT (self));
1026         }
1027
1028         if (actor_contact != NULL) {
1029                 g_object_unref (actor_contact);
1030         }
1031 }
1032
1033 static void
1034 tp_chat_got_remote_contact_cb (TpConnection            *connection,
1035                                EmpathyContact          *contact,
1036                                const GError            *error,
1037                                gpointer                 user_data,
1038                                GObject                 *chat)
1039 {
1040         EmpathyTpChat *self = (EmpathyTpChat *) chat;
1041
1042         if (error) {
1043                 DEBUG ("Error: %s", error->message);
1044                 empathy_tp_chat_leave (self, "");
1045                 return;
1046         }
1047
1048         self->priv->remote_contact = g_object_ref (contact);
1049         g_object_notify (chat, "remote-contact");
1050
1051         check_almost_ready (self);
1052 }
1053
1054 static void
1055 tp_chat_got_self_contact_cb (TpConnection            *connection,
1056                              EmpathyContact          *contact,
1057                              const GError            *error,
1058                              gpointer                 user_data,
1059                              GObject                 *chat)
1060 {
1061         EmpathyTpChat *self = (EmpathyTpChat *) chat;
1062
1063         if (error) {
1064                 DEBUG ("Error: %s", error->message);
1065                 empathy_tp_chat_leave (self, "");
1066                 return;
1067         }
1068
1069         self->priv->user = g_object_ref (contact);
1070         empathy_contact_set_is_user (self->priv->user, TRUE);
1071         check_almost_ready (self);
1072 }
1073
1074 static void
1075 tp_chat_get_property (GObject    *object,
1076                       guint       param_id,
1077                       GValue     *value,
1078                       GParamSpec *pspec)
1079 {
1080         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
1081
1082         switch (param_id) {
1083         case PROP_ACCOUNT:
1084                 g_value_set_object (value, self->priv->account);
1085                 break;
1086         case PROP_REMOTE_CONTACT:
1087                 g_value_set_object (value, self->priv->remote_contact);
1088                 break;
1089         case PROP_N_MESSAGES_SENDING:
1090                 g_value_set_uint (value,
1091                         g_hash_table_size (self->priv->messages_being_sent));
1092                 break;
1093         case PROP_TITLE:
1094                 g_value_set_string (value,
1095                         empathy_tp_chat_get_title (self));
1096                 break;
1097         case PROP_SUBJECT:
1098                 g_value_set_string (value,
1099                         empathy_tp_chat_get_subject (self));
1100                 break;
1101         default:
1102                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1103                 break;
1104         };
1105 }
1106
1107 static void
1108 tp_chat_set_property (GObject      *object,
1109                       guint         param_id,
1110                       const GValue *value,
1111                       GParamSpec   *pspec)
1112 {
1113         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
1114
1115         switch (param_id) {
1116         case PROP_ACCOUNT:
1117                 self->priv->account = g_value_dup_object (value);
1118                 break;
1119         default:
1120                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1121                 break;
1122         };
1123 }
1124
1125 enum {
1126         FEAT_READY,
1127         N_FEAT
1128 };
1129
1130 static const TpProxyFeature *
1131 tp_chat_list_features (TpProxyClass *cls G_GNUC_UNUSED)
1132 {
1133         static TpProxyFeature features[N_FEAT + 1] = { { 0 } };
1134   static GQuark need[2] = {0, 0};
1135
1136         if (G_LIKELY (features[0].name != 0))
1137                 return features;
1138
1139         features[FEAT_READY].name = EMPATHY_TP_CHAT_FEATURE_READY;
1140         need[0] = TP_TEXT_CHANNEL_FEATURE_INCOMING_MESSAGES;
1141         features[FEAT_READY].depends_on = need;
1142         features[FEAT_READY].prepare_async =
1143                 tp_chat_prepare_ready_async;
1144
1145         /* assert that the terminator at the end is there */
1146         g_assert (features[N_FEAT].name == 0);
1147
1148         return features;
1149 }
1150
1151 static void
1152 empathy_tp_chat_class_init (EmpathyTpChatClass *klass)
1153 {
1154         GObjectClass *object_class = G_OBJECT_CLASS (klass);
1155         TpProxyClass *proxy_class = TP_PROXY_CLASS (klass);
1156
1157         object_class->dispose = tp_chat_dispose;
1158         object_class->finalize = tp_chat_finalize;
1159         object_class->get_property = tp_chat_get_property;
1160         object_class->set_property = tp_chat_set_property;
1161
1162         proxy_class->list_features = tp_chat_list_features;
1163
1164         g_object_class_install_property (object_class,
1165                                          PROP_ACCOUNT,
1166                                          g_param_spec_object ("account",
1167                                                               "TpAccount",
1168                                                               "the account associated with the chat",
1169                                                               TP_TYPE_ACCOUNT,
1170                                                               G_PARAM_READWRITE |
1171                                                               G_PARAM_CONSTRUCT_ONLY |
1172                                                               G_PARAM_STATIC_STRINGS));
1173
1174         g_object_class_install_property (object_class,
1175                                          PROP_REMOTE_CONTACT,
1176                                          g_param_spec_object ("remote-contact",
1177                                                               "The remote contact",
1178                                                               "The remote contact if there is no group iface on the channel",
1179                                                               EMPATHY_TYPE_CONTACT,
1180                                                               G_PARAM_READABLE));
1181
1182         g_object_class_install_property (object_class,
1183                                          PROP_N_MESSAGES_SENDING,
1184                                          g_param_spec_uint ("n-messages-sending",
1185                                                             "Num Messages Sending",
1186                                                             "The number of messages being sent",
1187                                                             0, G_MAXUINT, 0,
1188                                                             G_PARAM_READABLE));
1189
1190         g_object_class_install_property (object_class,
1191                                          PROP_TITLE,
1192                                          g_param_spec_string ("title",
1193                                                               "Title",
1194                                                               "A human-readable name for the room, if any",
1195                                                               NULL,
1196                                                               G_PARAM_READABLE |
1197                                                               G_PARAM_STATIC_STRINGS));
1198
1199         g_object_class_install_property (object_class,
1200                                          PROP_SUBJECT,
1201                                          g_param_spec_string ("subject",
1202                                                               "Subject",
1203                                                               "The room's current subject, if any",
1204                                                               NULL,
1205                                                               G_PARAM_READABLE |
1206                                                               G_PARAM_STATIC_STRINGS));
1207
1208         /* Signals */
1209         signals[MESSAGE_RECEIVED] =
1210                 g_signal_new ("message-received-empathy",
1211                               G_TYPE_FROM_CLASS (klass),
1212                               G_SIGNAL_RUN_LAST,
1213                               0,
1214                               NULL, NULL,
1215                               g_cclosure_marshal_generic,
1216                               G_TYPE_NONE,
1217                               1, EMPATHY_TYPE_MESSAGE);
1218
1219         signals[SEND_ERROR] =
1220                 g_signal_new ("send-error",
1221                               G_TYPE_FROM_CLASS (klass),
1222                               G_SIGNAL_RUN_LAST,
1223                               0,
1224                               NULL, NULL,
1225                               g_cclosure_marshal_generic,
1226                               G_TYPE_NONE,
1227                               3, G_TYPE_STRING, G_TYPE_UINT, G_TYPE_STRING);
1228
1229         signals[CHAT_STATE_CHANGED] =
1230                 g_signal_new ("chat-state-changed-empathy",
1231                               G_TYPE_FROM_CLASS (klass),
1232                               G_SIGNAL_RUN_LAST,
1233                               0,
1234                               NULL, NULL,
1235                               g_cclosure_marshal_generic,
1236                               G_TYPE_NONE,
1237                               2, EMPATHY_TYPE_CONTACT, G_TYPE_UINT);
1238
1239         signals[MESSAGE_ACKNOWLEDGED] =
1240                 g_signal_new ("message-acknowledged",
1241                               G_TYPE_FROM_CLASS (klass),
1242                               G_SIGNAL_RUN_LAST,
1243                               0,
1244                               NULL, NULL,
1245                               g_cclosure_marshal_generic,
1246                               G_TYPE_NONE,
1247                               1, EMPATHY_TYPE_MESSAGE);
1248
1249         g_type_class_add_private (object_class, sizeof (EmpathyTpChatPrivate));
1250 }
1251
1252 static void
1253 empathy_tp_chat_init (EmpathyTpChat *self)
1254 {
1255         self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self,
1256                 EMPATHY_TYPE_TP_CHAT, EmpathyTpChatPrivate);
1257
1258         self->priv->messages_queue = g_queue_new ();
1259         self->priv->pending_messages_queue = g_queue_new ();
1260         self->priv->messages_being_sent = g_hash_table_new_full (
1261                 g_str_hash, g_str_equal, g_free, NULL);
1262 }
1263
1264 static void
1265 tp_chat_iface_init (EmpathyContactListIface *iface)
1266 {
1267         iface->add         = tp_chat_add;
1268         iface->remove      = tp_chat_remove;
1269         iface->get_members = tp_chat_get_members;
1270 }
1271
1272 EmpathyTpChat *
1273 empathy_tp_chat_new (
1274                      TpSimpleClientFactory *factory,
1275                      TpAccount *account,
1276                      TpConnection *conn,
1277                      const gchar *object_path,
1278                      const GHashTable *immutable_properties)
1279 {
1280         TpProxy *conn_proxy = (TpProxy *) conn;
1281
1282         g_return_val_if_fail (TP_IS_ACCOUNT (account), NULL);
1283         g_return_val_if_fail (TP_IS_CONNECTION (conn), NULL);
1284         g_return_val_if_fail (immutable_properties != NULL, NULL);
1285
1286         return g_object_new (EMPATHY_TYPE_TP_CHAT,
1287                              "factory", factory,
1288                              "account", account,
1289                              "connection", conn,
1290                              "dbus-daemon", conn_proxy->dbus_daemon,
1291                              "bus-name", conn_proxy->bus_name,
1292                              "object-path", object_path,
1293                              "channel-properties", immutable_properties,
1294                              NULL);
1295 }
1296
1297 const gchar *
1298 empathy_tp_chat_get_id (EmpathyTpChat *self)
1299 {
1300         const gchar *id;
1301
1302         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), NULL);
1303
1304         id = tp_channel_get_identifier ((TpChannel *) self);
1305         if (!EMP_STR_EMPTY (id))
1306                 return id;
1307         else if (self->priv->remote_contact)
1308                 return empathy_contact_get_id (self->priv->remote_contact);
1309         else
1310                 return NULL;
1311
1312 }
1313
1314 EmpathyContact *
1315 empathy_tp_chat_get_remote_contact (EmpathyTpChat *self)
1316 {
1317         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), NULL);
1318
1319         return self->priv->remote_contact;
1320 }
1321
1322 TpAccount *
1323 empathy_tp_chat_get_account (EmpathyTpChat *self)
1324 {
1325         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), NULL);
1326
1327         return self->priv->account;
1328 }
1329
1330 void
1331 empathy_tp_chat_send (EmpathyTpChat *self,
1332                       TpMessage *message)
1333 {
1334         gchar *message_body;
1335
1336         g_return_if_fail (EMPATHY_IS_TP_CHAT (self));
1337         g_return_if_fail (TP_IS_CLIENT_MESSAGE (message));
1338
1339         message_body = tp_message_to_text (message, NULL);
1340
1341         DEBUG ("Sending message: %s", message_body);
1342
1343         tp_text_channel_send_message_async (TP_TEXT_CHANNEL (self),
1344                 message, TP_MESSAGE_SENDING_FLAG_REPORT_DELIVERY,
1345                 message_send_cb, self);
1346
1347         g_free (message_body);
1348 }
1349
1350 const GList *
1351 empathy_tp_chat_get_pending_messages (EmpathyTpChat *self)
1352 {
1353         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), NULL);
1354
1355         return self->priv->pending_messages_queue->head;
1356 }
1357
1358 void
1359 empathy_tp_chat_acknowledge_message (EmpathyTpChat *self,
1360                                      EmpathyMessage *message) {
1361         TpMessage *tp_msg;
1362
1363         g_return_if_fail (EMPATHY_IS_TP_CHAT (self));
1364
1365         if (!empathy_message_is_incoming (message))
1366                 return;
1367
1368         tp_msg = empathy_message_get_tp_message (message);
1369         tp_text_channel_ack_message_async (TP_TEXT_CHANNEL (self),
1370                                            tp_msg, NULL, NULL);
1371 }
1372
1373 /**
1374  * empathy_tp_chat_can_add_contact:
1375  *
1376  * Returns: %TRUE if empathy_contact_list_add() will work for this channel.
1377  * That is if this chat is a 1-to-1 channel that can be upgraded to
1378  * a MUC using the Conference interface or if the channel is a MUC.
1379  */
1380 gboolean
1381 empathy_tp_chat_can_add_contact (EmpathyTpChat *self)
1382 {
1383         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), FALSE);
1384
1385         return self->priv->can_upgrade_to_muc ||
1386                 tp_proxy_has_interface_by_id (self,
1387                         TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP);;
1388 }
1389
1390 static void
1391 tp_channel_leave_async_cb (GObject *source_object,
1392         GAsyncResult *res,
1393         gpointer user_data)
1394 {
1395         GError *error = NULL;
1396
1397         if (!tp_channel_leave_finish (TP_CHANNEL (source_object), res, &error)) {
1398                 DEBUG ("Could not leave channel properly: (%s); closing the channel",
1399                         error->message);
1400                 g_error_free (error);
1401         }
1402 }
1403
1404 void
1405 empathy_tp_chat_leave (EmpathyTpChat *self,
1406                 const gchar *message)
1407 {
1408         TpChannel *channel = (TpChannel *) self;
1409
1410         DEBUG ("Leaving channel %s with message \"%s\"",
1411                 tp_channel_get_identifier (channel), message);
1412
1413         tp_channel_leave_async (channel, TP_CHANNEL_GROUP_CHANGE_REASON_NONE,
1414                 message, tp_channel_leave_async_cb, self);
1415 }
1416
1417 static void
1418 add_members_cb (TpChannel *proxy,
1419                 const GError *error,
1420                 gpointer user_data,
1421                 GObject *weak_object)
1422 {
1423         EmpathyTpChat *self = (EmpathyTpChat *) weak_object;
1424
1425         if (error != NULL) {
1426                 DEBUG ("Failed to join chat (%s): %s",
1427                         tp_channel_get_identifier ((TpChannel *) self), error->message);
1428         }
1429 }
1430
1431 void
1432 empathy_tp_chat_join (EmpathyTpChat *self)
1433 {
1434         TpHandle self_handle;
1435         GArray *members;
1436
1437         self_handle = tp_channel_group_get_self_handle ((TpChannel *) self);
1438
1439         members = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), 1);
1440         g_array_append_val (members, self_handle);
1441
1442         tp_cli_channel_interface_group_call_add_members ((TpChannel *) self, -1, members,
1443                 "", add_members_cb, NULL, NULL, G_OBJECT (self));
1444
1445         g_array_unref (members);
1446 }
1447
1448 gboolean
1449 empathy_tp_chat_is_invited (EmpathyTpChat *self,
1450                             TpHandle *inviter)
1451 {
1452         TpHandle self_handle;
1453
1454         if (!tp_proxy_has_interface (self, TP_IFACE_CHANNEL_INTERFACE_GROUP))
1455                 return FALSE;
1456
1457         self_handle = tp_channel_group_get_self_handle ((TpChannel *) self);
1458         if (self_handle == 0)
1459                 return FALSE;
1460
1461         return tp_channel_group_get_local_pending_info ((TpChannel *) self, self_handle,
1462                 inviter, NULL, NULL);
1463 }
1464
1465 TpChannelChatState
1466 empathy_tp_chat_get_chat_state (EmpathyTpChat *self,
1467                             EmpathyContact *contact)
1468 {
1469         return tp_channel_get_chat_state ((TpChannel *) self,
1470                 empathy_contact_get_handle (contact));
1471 }
1472
1473 EmpathyContact *
1474 empathy_tp_chat_get_self_contact (EmpathyTpChat *self)
1475 {
1476         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), NULL);
1477
1478         return self->priv->user;
1479 }
1480
1481 GQuark
1482 empathy_tp_chat_get_feature_ready (void)
1483 {
1484         return g_quark_from_static_string ("empathy-tp-chat-feature-ready");
1485 }
1486
1487 static void
1488 tp_chat_prepare_ready_async (TpProxy *proxy,
1489         const TpProxyFeature *feature,
1490         GAsyncReadyCallback callback,
1491         gpointer user_data)
1492 {
1493         EmpathyTpChat *self = (EmpathyTpChat *) proxy;
1494         TpChannel *channel = (TpChannel *) proxy;
1495         TpConnection *connection;
1496         gboolean listen_for_dbus_properties_changed = FALSE;
1497
1498         g_assert (self->priv->ready_result == NULL);
1499         self->priv->ready_result = g_simple_async_result_new (G_OBJECT (self),
1500                 callback, user_data, tp_chat_prepare_ready_async);
1501
1502         connection = tp_channel_borrow_connection (channel);
1503
1504         if (tp_proxy_has_interface_by_id (self,
1505                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
1506                 const TpIntSet *members;
1507                 GArray *handles;
1508                 TpHandle handle;
1509
1510                 /* Get self contact from the group's self handle */
1511                 handle = tp_channel_group_get_self_handle (channel);
1512                 empathy_tp_contact_factory_get_from_handle (connection,
1513                         handle, tp_chat_got_self_contact_cb,
1514                         NULL, NULL, G_OBJECT (self));
1515
1516                 /* Get initial member contacts */
1517                 members = tp_channel_group_get_members (channel);
1518                 handles = tp_intset_to_array (members);
1519                 empathy_tp_contact_factory_get_from_handles (connection,
1520                         handles->len, (TpHandle *) handles->data,
1521                         tp_chat_got_added_contacts_cb, NULL, NULL, G_OBJECT (self));
1522
1523                 self->priv->can_upgrade_to_muc = FALSE;
1524
1525                 tp_g_signal_connect_object (self, "group-members-changed",
1526                         G_CALLBACK (tp_chat_group_members_changed_cb), self, 0);
1527         } else {
1528                 TpCapabilities *caps;
1529                 GPtrArray *classes;
1530                 guint i;
1531                 TpHandle handle;
1532
1533                 /* Get the self contact from the connection's self handle */
1534                 handle = tp_connection_get_self_handle (connection);
1535                 empathy_tp_contact_factory_get_from_handle (connection,
1536                         handle, tp_chat_got_self_contact_cb,
1537                         NULL, NULL, G_OBJECT (self));
1538
1539                 /* Get the remote contact */
1540                 handle = tp_channel_get_handle (channel, NULL);
1541                 empathy_tp_contact_factory_get_from_handle (connection,
1542                         handle, tp_chat_got_remote_contact_cb,
1543                         NULL, NULL, G_OBJECT (self));
1544
1545                 caps = tp_connection_get_capabilities (connection);
1546                 g_assert (caps != NULL);
1547
1548                 classes = tp_capabilities_get_channel_classes (caps);
1549
1550                 for (i = 0; i < classes->len; i++) {
1551                         GValueArray *array = g_ptr_array_index (classes, i);
1552                         const char **oprops = g_value_get_boxed (
1553                                 g_value_array_get_nth (array, 1));
1554
1555                         if (tp_strv_contains (oprops, TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_CHANNELS)) {
1556                                 self->priv->can_upgrade_to_muc = TRUE;
1557                                 break;
1558                         }
1559                 }
1560         }
1561
1562         if (tp_proxy_has_interface_by_id (self,
1563                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_SUBJECT)) {
1564                 tp_cli_dbus_properties_call_get_all (channel, -1,
1565                                                      TP_IFACE_CHANNEL_INTERFACE_SUBJECT,
1566                                                      tp_chat_get_all_subject_cb,
1567                                                      NULL, NULL,
1568                                                      G_OBJECT (self));
1569                 listen_for_dbus_properties_changed = TRUE;
1570         }
1571
1572         if (tp_proxy_has_interface_by_id (self,
1573                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_ROOM_CONFIG)) {
1574                 tp_cli_dbus_properties_call_get_all (channel, -1,
1575                                                      TP_IFACE_CHANNEL_INTERFACE_ROOM_CONFIG,
1576                                                      tp_chat_get_all_room_config_cb,
1577                                                      NULL, NULL,
1578                                                      G_OBJECT (self));
1579                 listen_for_dbus_properties_changed = TRUE;
1580         }
1581
1582         if (listen_for_dbus_properties_changed) {
1583                 tp_cli_dbus_properties_connect_to_properties_changed (channel,
1584                                                                       tp_chat_dbus_properties_changed_cb,
1585                                                                       NULL, NULL,
1586                                                                       G_OBJECT (self), NULL);
1587         }
1588 }