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