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