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