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