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