]> git.0d.be Git - empathy.git/blob - libempathy/empathy-tp-chat.c
use the TpChannel:chat-state-changed signal
[empathy.git] / libempathy / empathy-tp-chat.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2007-2008 Collabora Ltd.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  *
19  * Authors: Xavier Claessens <xclaesse@gmail.com>
20  */
21
22 #include <config.h>
23
24 #include <string.h>
25
26 #include <telepathy-glib/telepathy-glib.h>
27
28 #include <extensions/extensions.h>
29
30 #include "empathy-tp-chat.h"
31 #include "empathy-tp-contact-factory.h"
32 #include "empathy-contact-list.h"
33 #include "empathy-marshal.h"
34 #include "empathy-request-util.h"
35 #include "empathy-time.h"
36 #include "empathy-utils.h"
37
38 #define DEBUG_FLAG EMPATHY_DEBUG_TP | EMPATHY_DEBUG_CHAT
39 #include "empathy-debug.h"
40
41 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyTpChat)
42 typedef struct {
43         gboolean               dispose_has_run;
44         TpAccount             *account;
45         TpConnection          *connection;
46         EmpathyContact        *user;
47         EmpathyContact        *remote_contact;
48         GList                 *members;
49         TpChannel             *channel;
50         /* Queue of messages not signalled yet */
51         GQueue                *messages_queue;
52         /* Queue of messages signalled but not acked yet */
53         GQueue                *pending_messages_queue;
54         gboolean               had_properties_list;
55         GPtrArray             *properties;
56         TpChannelPasswordFlags password_flags;
57         /* TRUE if we fetched the password flag of the channel or if it's not needed
58          * (channel doesn't implement the Password interface) */
59         gboolean               got_password_flags;
60         gboolean               ready;
61         gboolean               can_upgrade_to_muc;
62 } EmpathyTpChatPriv;
63
64 static void tp_chat_iface_init         (EmpathyContactListIface *iface);
65
66 enum {
67         PROP_0,
68         PROP_ACCOUNT,
69         PROP_CHANNEL,
70         PROP_REMOTE_CONTACT,
71         PROP_PASSWORD_NEEDED,
72         PROP_READY,
73 };
74
75 enum {
76         MESSAGE_RECEIVED,
77         SEND_ERROR,
78         CHAT_STATE_CHANGED,
79         PROPERTY_CHANGED,
80         DESTROY,
81         LAST_SIGNAL
82 };
83
84 static guint signals[LAST_SIGNAL];
85
86 G_DEFINE_TYPE_WITH_CODE (EmpathyTpChat, empathy_tp_chat, G_TYPE_OBJECT,
87                          G_IMPLEMENT_INTERFACE (EMPATHY_TYPE_CONTACT_LIST,
88                                                 tp_chat_iface_init));
89
90 static void acknowledge_messages (EmpathyTpChat *chat, GArray *ids);
91
92 static void
93 tp_chat_invalidated_cb (TpProxy       *proxy,
94                         guint          domain,
95                         gint           code,
96                         gchar         *message,
97                         EmpathyTpChat *chat)
98 {
99         DEBUG ("Channel invalidated: %s", message);
100         g_signal_emit (chat, signals[DESTROY], 0);
101 }
102
103 static void
104 tp_chat_async_cb (TpChannel *proxy,
105                   const GError *error,
106                   gpointer user_data,
107                   GObject *weak_object)
108 {
109         if (error) {
110                 DEBUG ("Error %s: %s", (gchar *) user_data, error->message);
111         }
112 }
113
114 static void
115 create_conference_cb (GObject *source,
116                       GAsyncResult *result,
117                       gpointer user_data)
118 {
119         GError *error = NULL;
120
121         if (!tp_account_channel_request_create_channel_finish (
122                         TP_ACCOUNT_CHANNEL_REQUEST (source), result, &error)) {
123                 DEBUG ("Failed to create conference channel: %s", error->message);
124                 g_error_free (error);
125         }
126 }
127
128 static void
129 tp_chat_add (EmpathyContactList *list,
130              EmpathyContact     *contact,
131              const gchar        *message)
132 {
133         EmpathyTpChatPriv *priv = GET_PRIV (list);
134
135         if (tp_proxy_has_interface_by_id (priv->channel,
136                 TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
137                 TpHandle           handle;
138                 GArray             handles = {(gchar *) &handle, 1};
139
140                 g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
141                 g_return_if_fail (EMPATHY_IS_CONTACT (contact));
142
143                 handle = empathy_contact_get_handle (contact);
144                 tp_cli_channel_interface_group_call_add_members (priv->channel,
145                         -1, &handles, NULL, NULL, NULL, NULL, NULL);
146         } else if (priv->can_upgrade_to_muc) {
147                 TpAccountChannelRequest *req;
148                 GHashTable        *props;
149                 const char        *object_path;
150                 GPtrArray          channels = { (gpointer *) &object_path, 1 };
151                 const char        *invitees[2] = { NULL, };
152
153                 invitees[0] = empathy_contact_get_id (contact);
154                 object_path = tp_proxy_get_object_path (priv->channel);
155
156                 props = tp_asv_new (
157                     TP_PROP_CHANNEL_CHANNEL_TYPE, G_TYPE_STRING,
158                         TP_IFACE_CHANNEL_TYPE_TEXT,
159                     TP_PROP_CHANNEL_TARGET_HANDLE_TYPE, G_TYPE_UINT,
160                         TP_HANDLE_TYPE_NONE,
161                     TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_CHANNELS,
162                         TP_ARRAY_TYPE_OBJECT_PATH_LIST, &channels,
163                     TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_INVITEE_IDS,
164                         G_TYPE_STRV, invitees,
165                     /* FIXME: InvitationMessage ? */
166                     NULL);
167
168                 req = tp_account_channel_request_new (priv->account, props,
169                         TP_USER_ACTION_TIME_NOT_USER_ACTION);
170
171                 /* Although this is a MUC, it's anonymous, so CreateChannel is
172                  * valid. */
173                 tp_account_channel_request_create_channel_async (req, EMPATHY_CHAT_BUS_NAME,
174                         NULL, create_conference_cb, NULL);
175
176                 g_object_unref (req);
177                 g_hash_table_unref (props);
178         } else {
179                 g_warning ("Cannot add to this channel");
180         }
181 }
182
183 static void
184 tp_chat_remove (EmpathyContactList *list,
185                 EmpathyContact     *contact,
186                 const gchar        *message)
187 {
188         EmpathyTpChatPriv *priv = GET_PRIV (list);
189         TpHandle           handle;
190         GArray             handles = {(gchar *) &handle, 1};
191
192         g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
193         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
194
195         handle = empathy_contact_get_handle (contact);
196         tp_cli_channel_interface_group_call_remove_members (priv->channel, -1,
197                                                             &handles, NULL,
198                                                             NULL, NULL, NULL,
199                                                             NULL);
200 }
201
202 static GList *
203 tp_chat_get_members (EmpathyContactList *list)
204 {
205         EmpathyTpChatPriv *priv = GET_PRIV (list);
206         GList             *members = NULL;
207
208         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (list), NULL);
209
210         if (priv->members) {
211                 members = g_list_copy (priv->members);
212                 g_list_foreach (members, (GFunc) g_object_ref, NULL);
213         } else {
214                 members = g_list_prepend (members, g_object_ref (priv->user));
215                 if (priv->remote_contact != NULL)
216                         members = g_list_prepend (members, g_object_ref (priv->remote_contact));
217         }
218
219         return members;
220 }
221
222 static void
223 check_ready (EmpathyTpChat *chat)
224 {
225         EmpathyTpChatPriv *priv = GET_PRIV (chat);
226
227         if (priv->ready)
228                 return;
229
230         if (g_queue_get_length (priv->messages_queue) > 0)
231                 return;
232
233         DEBUG ("Ready");
234
235         priv->ready = TRUE;
236         g_object_notify (G_OBJECT (chat), "ready");
237 }
238
239 static void
240 tp_chat_emit_queued_messages (EmpathyTpChat *chat)
241 {
242         EmpathyTpChatPriv *priv = GET_PRIV (chat);
243         EmpathyMessage    *message;
244
245         /* Check if we can now emit some queued messages */
246         while ((message = g_queue_peek_head (priv->messages_queue)) != NULL) {
247                 if (empathy_message_get_sender (message) == NULL) {
248                         break;
249                 }
250
251                 DEBUG ("Queued message ready");
252                 g_queue_pop_head (priv->messages_queue);
253                 g_queue_push_tail (priv->pending_messages_queue, message);
254                 g_signal_emit (chat, signals[MESSAGE_RECEIVED], 0, message);
255         }
256
257         check_ready (chat);
258 }
259
260 static void
261 tp_chat_got_sender_cb (TpConnection            *connection,
262                        EmpathyContact          *contact,
263                        const GError            *error,
264                        gpointer                 message,
265                        GObject                 *chat)
266 {
267         EmpathyTpChatPriv *priv = GET_PRIV (chat);
268
269         if (error) {
270                 DEBUG ("Error: %s", error->message);
271                 /* Do not block the message queue, just drop this message */
272                 g_queue_remove (priv->messages_queue, message);
273         } else {
274                 empathy_message_set_sender (message, contact);
275         }
276
277         tp_chat_emit_queued_messages (EMPATHY_TP_CHAT (chat));
278 }
279
280 static void
281 tp_chat_build_message (EmpathyTpChat *chat,
282                        TpMessage     *msg,
283                        gboolean       incoming)
284 {
285         EmpathyTpChatPriv *priv;
286         EmpathyMessage    *message;
287         TpContact *sender;
288
289         priv = GET_PRIV (chat);
290
291         message = empathy_message_new_from_tp_message (msg, incoming);
292         /* FIXME: this is actually a lie for incoming messages. */
293         empathy_message_set_receiver (message, priv->user);
294
295         g_queue_push_tail (priv->messages_queue, message);
296
297         sender = tp_signalled_message_get_sender (msg);
298         g_assert (sender != NULL);
299
300         if (tp_contact_get_handle (sender) == 0) {
301                 empathy_message_set_sender (message, priv->user);
302                 tp_chat_emit_queued_messages (chat);
303         } else {
304                 empathy_tp_contact_factory_get_from_handle (priv->connection,
305                         tp_contact_get_handle (sender),
306                         tp_chat_got_sender_cb,
307                         message, NULL, G_OBJECT (chat));
308         }
309 }
310
311 static void
312 handle_delivery_report (EmpathyTpChat *self,
313                 TpMessage *message)
314 {
315         EmpathyTpChatPriv *priv = GET_PRIV (self);
316         TpDeliveryStatus delivery_status;
317         const GHashTable *header;
318         TpChannelTextSendError delivery_error;
319         gboolean valid;
320         GPtrArray *echo;
321         const gchar *message_body = NULL;
322
323         header = tp_message_peek (message, 0);
324         if (header == NULL)
325                 goto out;
326
327         delivery_status = tp_asv_get_uint32 (header, "delivery-status", &valid);
328         if (!valid || delivery_status != TP_DELIVERY_STATUS_PERMANENTLY_FAILED)
329                 goto out;
330
331         delivery_error = tp_asv_get_uint32 (header, "delivery-error", &valid);
332         if (!valid)
333                 delivery_error = TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN;
334
335         /* TODO: ideally we should use tp-glib API giving us the echoed message as a
336          * TpMessage. (fdo #35884) */
337         echo = tp_asv_get_boxed (header, "delivery-echo",
338                 TP_ARRAY_TYPE_MESSAGE_PART_LIST);
339         if (echo != NULL && echo->len >= 1) {
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         g_signal_emit (self, signals[SEND_ERROR], 0, message_body, delivery_error);
348
349 out:
350         tp_text_channel_ack_message_async (TP_TEXT_CHANNEL (priv->channel),
351                 message, NULL, NULL);
352 }
353
354 static void
355 handle_incoming_message (EmpathyTpChat *self,
356                          TpMessage *message,
357                          gboolean pending)
358 {
359         EmpathyTpChatPriv *priv = GET_PRIV (self);
360         gchar *message_body;
361
362         if (tp_message_is_delivery_report (message)) {
363                 handle_delivery_report (self, message);
364                 return;
365         }
366
367         message_body = tp_message_to_text (message, NULL);
368
369         DEBUG ("Message %s (channel %s): %s",
370                 pending ? "pending" : "received",
371                 tp_proxy_get_object_path (priv->channel), message_body);
372
373         if (message_body == NULL) {
374                 DEBUG ("Empty message with NonTextContent, ignoring and acking.");
375
376                 tp_text_channel_ack_message_async (TP_TEXT_CHANNEL (priv->channel),
377                         message, NULL, NULL);
378                 return;
379         }
380
381         tp_chat_build_message (self, message, TRUE);
382
383         g_free (message_body);
384 }
385
386 static void
387 message_received_cb (TpTextChannel   *channel,
388                      TpMessage *message,
389                      EmpathyTpChat *chat)
390 {
391         handle_incoming_message (chat, message, FALSE);
392 }
393
394 static void
395 message_sent_cb (TpTextChannel   *channel,
396                  TpMessage *message,
397                  TpMessageSendingFlags flags,
398                  gchar              *token,
399                  EmpathyTpChat      *chat)
400 {
401         gchar *message_body;
402
403         message_body = tp_message_to_text (message, NULL);
404
405         DEBUG ("Message sent: %s", message_body);
406
407         tp_chat_build_message (chat, message, FALSE);
408
409         g_free (message_body);
410 }
411
412 static TpChannelTextSendError
413 error_to_text_send_error (GError *error)
414 {
415         if (error->domain != TP_ERRORS)
416                 return TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN;
417
418         switch (error->code) {
419                 case TP_ERROR_OFFLINE:
420                         return TP_CHANNEL_TEXT_SEND_ERROR_OFFLINE;
421                 case TP_ERROR_INVALID_HANDLE:
422                         return TP_CHANNEL_TEXT_SEND_ERROR_INVALID_CONTACT;
423                 case TP_ERROR_PERMISSION_DENIED:
424                         return TP_CHANNEL_TEXT_SEND_ERROR_PERMISSION_DENIED;
425                 case TP_ERROR_NOT_IMPLEMENTED:
426                         return TP_CHANNEL_TEXT_SEND_ERROR_NOT_IMPLEMENTED;
427         }
428
429         return TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN;
430 }
431
432 static void
433 message_send_cb (GObject *source,
434                  GAsyncResult *result,
435                  gpointer      user_data)
436 {
437         EmpathyTpChat *chat = user_data;
438         TpTextChannel *channel = (TpTextChannel *) source;
439         GError *error = NULL;
440
441         if (!tp_text_channel_send_message_finish (channel, result, NULL, &error)) {
442                 DEBUG ("Error: %s", error->message);
443
444                 /* FIXME: we should use the body of the message as first argument of the
445                  * signal but can't easily get it as we just get a user_data pointer. Once
446                  * we'll have rebased EmpathyTpChat on top of TpTextChannel we'll be able
447                  * to use the user_data pointer to pass the message and fix this. */
448                 g_signal_emit (chat, signals[SEND_ERROR], 0,
449                                NULL, error_to_text_send_error (error));
450
451                 g_error_free (error);
452         }
453 }
454
455 typedef struct {
456         EmpathyTpChat *chat;
457         TpChannelChatState state;
458 } StateChangedData;
459
460 static void
461 tp_chat_state_changed_got_contact_cb (TpConnection            *connection,
462                                       EmpathyContact          *contact,
463                                       const GError            *error,
464                                       gpointer                 user_data,
465                                       GObject                 *chat)
466 {
467         TpChannelChatState state;
468
469         if (error) {
470                 DEBUG ("Error: %s", error->message);
471                 return;
472         }
473
474         state = GPOINTER_TO_UINT (user_data);
475         DEBUG ("Chat state changed for %s (%d): %d",
476                 empathy_contact_get_alias (contact),
477                 empathy_contact_get_handle (contact), state);
478
479         g_signal_emit (chat, signals[CHAT_STATE_CHANGED], 0, contact, state);
480 }
481
482 static void
483 tp_chat_state_changed_cb (TpChannel *channel,
484                           TpHandle   handle,
485                           TpChannelChatState state,
486                           EmpathyTpChat *chat)
487 {
488         EmpathyTpChatPriv *priv = GET_PRIV (chat);
489
490         empathy_tp_contact_factory_get_from_handle (priv->connection, handle,
491                 tp_chat_state_changed_got_contact_cb, GUINT_TO_POINTER (state),
492                 NULL, G_OBJECT (chat));
493 }
494
495 static void
496 list_pending_messages (EmpathyTpChat *self)
497 {
498         EmpathyTpChatPriv *priv = GET_PRIV (self);
499         GList *messages, *l;
500
501         g_assert (priv->channel != NULL);
502
503         messages = tp_text_channel_get_pending_messages (
504                 TP_TEXT_CHANNEL (priv->channel));
505
506         for (l = messages; l != NULL; l = g_list_next (l)) {
507                 TpMessage *message = l->data;
508
509                 handle_incoming_message (self, message, FALSE);
510         }
511
512         g_list_free (messages);
513 }
514
515 static void
516 tp_chat_property_flags_changed_cb (TpProxy         *proxy,
517                                    const GPtrArray *properties,
518                                    gpointer         user_data,
519                                    GObject         *chat)
520 {
521         EmpathyTpChatPriv *priv = GET_PRIV (chat);
522         guint              i, j;
523
524         if (priv->channel == NULL)
525                 return;
526
527         if (!priv->had_properties_list || !properties) {
528                 return;
529         }
530
531         for (i = 0; i < properties->len; i++) {
532                 GValueArray           *prop_struct;
533                 EmpathyTpChatProperty *property;
534                 guint                  id;
535                 guint                  flags;
536
537                 prop_struct = g_ptr_array_index (properties, i);
538                 id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
539                 flags = g_value_get_uint (g_value_array_get_nth (prop_struct, 1));
540
541                 for (j = 0; j < priv->properties->len; j++) {
542                         property = g_ptr_array_index (priv->properties, j);
543                         if (property->id == id) {
544                                 property->flags = flags;
545                                 DEBUG ("property %s flags changed: %d",
546                                         property->name, property->flags);
547                                 break;
548                         }
549                 }
550         }
551 }
552
553 static void
554 tp_chat_properties_changed_cb (TpProxy         *proxy,
555                                const GPtrArray *properties,
556                                gpointer         user_data,
557                                GObject         *chat)
558 {
559         EmpathyTpChatPriv *priv = GET_PRIV (chat);
560         guint              i, j;
561
562         if (priv->channel == NULL)
563                 return;
564
565         if (!priv->had_properties_list || !properties) {
566                 return;
567         }
568
569         for (i = 0; i < properties->len; i++) {
570                 GValueArray           *prop_struct;
571                 EmpathyTpChatProperty *property;
572                 guint                  id;
573                 GValue                *src_value;
574
575                 prop_struct = g_ptr_array_index (properties, i);
576                 id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
577                 src_value = g_value_get_boxed (g_value_array_get_nth (prop_struct, 1));
578
579                 for (j = 0; j < priv->properties->len; j++) {
580                         property = g_ptr_array_index (priv->properties, j);
581                         if (property->id == id) {
582                                 if (property->value) {
583                                         g_value_copy (src_value, property->value);
584                                 } else {
585                                         property->value = tp_g_value_slice_dup (src_value);
586                                 }
587
588                                 DEBUG ("property %s changed", property->name);
589                                 g_signal_emit (chat, signals[PROPERTY_CHANGED], 0,
590                                                property->name, property->value);
591                                 break;
592                         }
593                 }
594         }
595 }
596
597 static void
598 tp_chat_get_properties_cb (TpProxy         *proxy,
599                            const GPtrArray *properties,
600                            const GError    *error,
601                            gpointer         user_data,
602                            GObject         *chat)
603 {
604         if (error) {
605                 DEBUG ("Error getting properties: %s", error->message);
606                 return;
607         }
608
609         tp_chat_properties_changed_cb (proxy, properties, user_data, chat);
610 }
611
612 static void
613 tp_chat_list_properties_cb (TpProxy         *proxy,
614                             const GPtrArray *properties,
615                             const GError    *error,
616                             gpointer         user_data,
617                             GObject         *chat)
618 {
619         EmpathyTpChatPriv *priv = GET_PRIV (chat);
620         GArray            *ids;
621         guint              i;
622
623         if (priv->channel == NULL)
624                 return;
625
626         priv->had_properties_list = TRUE;
627
628         if (error) {
629                 DEBUG ("Error listing properties: %s", error->message);
630                 return;
631         }
632
633         ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), properties->len);
634         priv->properties = g_ptr_array_sized_new (properties->len);
635         for (i = 0; i < properties->len; i++) {
636                 GValueArray           *prop_struct;
637                 EmpathyTpChatProperty *property;
638
639                 prop_struct = g_ptr_array_index (properties, i);
640                 property = g_slice_new0 (EmpathyTpChatProperty);
641                 property->id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
642                 property->name = g_value_dup_string (g_value_array_get_nth (prop_struct, 1));
643                 property->flags = g_value_get_uint (g_value_array_get_nth (prop_struct, 3));
644
645                 DEBUG ("Adding property name=%s id=%d flags=%d",
646                         property->name, property->id, property->flags);
647                 g_ptr_array_add (priv->properties, property);
648                 if (property->flags & TP_PROPERTY_FLAG_READ) {
649                         g_array_append_val (ids, property->id);
650                 }
651         }
652
653         tp_cli_properties_interface_call_get_properties (proxy, -1,
654                                                          ids,
655                                                          tp_chat_get_properties_cb,
656                                                          NULL, NULL,
657                                                          chat);
658
659         g_array_free (ids, TRUE);
660 }
661
662 void
663 empathy_tp_chat_set_property (EmpathyTpChat *chat,
664                               const gchar   *name,
665                               const GValue  *value)
666 {
667         EmpathyTpChatPriv     *priv = GET_PRIV (chat);
668         EmpathyTpChatProperty *property;
669         guint                  i;
670
671         if (!priv->had_properties_list) {
672                 return;
673         }
674
675         for (i = 0; i < priv->properties->len; i++) {
676                 property = g_ptr_array_index (priv->properties, i);
677                 if (!tp_strdiff (property->name, name)) {
678                         GPtrArray   *properties;
679                         GValueArray *prop;
680                         GValue       id = {0, };
681                         GValue       dest_value = {0, };
682
683                         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
684                                 break;
685                         }
686
687                         g_value_init (&id, G_TYPE_UINT);
688                         g_value_init (&dest_value, G_TYPE_VALUE);
689                         g_value_set_uint (&id, property->id);
690                         g_value_set_boxed (&dest_value, value);
691
692                         prop = g_value_array_new (2);
693                         g_value_array_append (prop, &id);
694                         g_value_array_append (prop, &dest_value);
695
696                         properties = g_ptr_array_sized_new (1);
697                         g_ptr_array_add (properties, prop);
698
699                         DEBUG ("Set property %s", name);
700                         tp_cli_properties_interface_call_set_properties (priv->channel, -1,
701                                                                          properties,
702                                                                          (tp_cli_properties_interface_callback_for_set_properties)
703                                                                          tp_chat_async_cb,
704                                                                          "Seting property", NULL,
705                                                                          G_OBJECT (chat));
706
707                         g_ptr_array_free (properties, TRUE);
708                         g_value_array_free (prop);
709
710                         break;
711                 }
712         }
713 }
714
715 EmpathyTpChatProperty *
716 empathy_tp_chat_get_property (EmpathyTpChat *chat,
717                               const gchar   *name)
718 {
719         EmpathyTpChatPriv     *priv = GET_PRIV (chat);
720         EmpathyTpChatProperty *property;
721         guint                  i;
722
723         if (!priv->had_properties_list) {
724                 return NULL;
725         }
726
727         for (i = 0; i < priv->properties->len; i++) {
728                 property = g_ptr_array_index (priv->properties, i);
729                 if (!tp_strdiff (property->name, name)) {
730                         return property;
731                 }
732         }
733
734         return NULL;
735 }
736
737 GPtrArray *
738 empathy_tp_chat_get_properties (EmpathyTpChat *chat)
739 {
740         EmpathyTpChatPriv *priv = GET_PRIV (chat);
741
742         return priv->properties;
743 }
744
745 static void
746 tp_chat_dispose (GObject *object)
747 {
748         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
749         EmpathyTpChatPriv *priv = GET_PRIV (self);
750
751         if (priv->dispose_has_run)
752                 return;
753
754         priv->dispose_has_run = TRUE;
755
756         tp_clear_object (&priv->account);
757
758         if (priv->connection != NULL)
759                 g_object_unref (priv->connection);
760         priv->connection = NULL;
761
762         if (priv->channel != NULL) {
763                 g_signal_handlers_disconnect_by_func (priv->channel,
764                         tp_chat_invalidated_cb, self);
765                 g_object_unref (priv->channel);
766         }
767         priv->channel = NULL;
768
769         if (priv->remote_contact != NULL)
770                 g_object_unref (priv->remote_contact);
771         priv->remote_contact = NULL;
772
773         if (priv->user != NULL)
774                 g_object_unref (priv->user);
775         priv->user = NULL;
776
777         g_queue_foreach (priv->messages_queue, (GFunc) g_object_unref, NULL);
778         g_queue_clear (priv->messages_queue);
779
780         g_queue_foreach (priv->pending_messages_queue,
781                 (GFunc) g_object_unref, NULL);
782         g_queue_clear (priv->pending_messages_queue);
783
784         if (G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose)
785                 G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose (object);
786 }
787
788 static void
789 tp_chat_finalize (GObject *object)
790 {
791         EmpathyTpChatPriv *priv = GET_PRIV (object);
792         guint              i;
793
794         DEBUG ("Finalize: %p", object);
795
796         if (priv->properties) {
797                 for (i = 0; i < priv->properties->len; i++) {
798                         EmpathyTpChatProperty *property;
799
800                         property = g_ptr_array_index (priv->properties, i);
801                         g_free (property->name);
802                         if (property->value) {
803                                 tp_g_value_slice_free (property->value);
804                         }
805                         g_slice_free (EmpathyTpChatProperty, property);
806                 }
807                 g_ptr_array_free (priv->properties, TRUE);
808         }
809
810         g_queue_free (priv->messages_queue);
811         g_queue_free (priv->pending_messages_queue);
812
813         G_OBJECT_CLASS (empathy_tp_chat_parent_class)->finalize (object);
814 }
815
816 static void
817 check_almost_ready (EmpathyTpChat *chat)
818 {
819         EmpathyTpChatPriv *priv = GET_PRIV (chat);
820
821         if (priv->ready)
822                 return;
823
824         if (priv->user == NULL)
825                 return;
826
827         if (!priv->got_password_flags)
828                 return;
829
830         /* We need either the members (room) or the remote contact (private chat).
831          * If the chat is protected by a password we can't get these information so
832          * consider the chat as ready so it can be presented to the user. */
833         if (!empathy_tp_chat_password_needed (chat) && priv->members == NULL &&
834             priv->remote_contact == NULL)
835                 return;
836
837         /* We use the default factory so this feature should have been prepared */
838         g_assert (tp_proxy_is_prepared (priv->channel,
839                 TP_TEXT_CHANNEL_FEATURE_INCOMING_MESSAGES));
840
841         tp_g_signal_connect_object (priv->channel, "message-received",
842                 G_CALLBACK (message_received_cb), chat, 0);
843
844         list_pending_messages (chat);
845
846         tp_g_signal_connect_object (priv->channel, "message-sent",
847                 G_CALLBACK (message_sent_cb), chat, 0);
848
849         tp_g_signal_connect_object (priv->channel, "chat-state-changed",
850                 G_CALLBACK (tp_chat_state_changed_cb), chat, 0);
851
852         check_ready (chat);
853 }
854
855 static void
856 tp_chat_update_remote_contact (EmpathyTpChat *chat)
857 {
858         EmpathyTpChatPriv *priv = GET_PRIV (chat);
859         EmpathyContact *contact = NULL;
860         TpHandle self_handle;
861         TpHandleType handle_type;
862         GList *l;
863
864         /* If this is a named chatroom, never pretend it is a private chat */
865         tp_channel_get_handle (priv->channel, &handle_type);
866         if (handle_type == TP_HANDLE_TYPE_ROOM) {
867                 return;
868         }
869
870         /* This is an MSN chat, but it's the new style where 1-1 chats don't
871          * have the group interface. If it has the conference interface, then
872          * it is indeed a MUC. */
873         if (tp_proxy_has_interface_by_id (priv->channel,
874                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_CONFERENCE)) {
875                 return;
876         }
877
878         /* This is an MSN-like chat where anyone can join the chat at anytime.
879          * If there is only one non-self contact member, we are in a private
880          * chat and we set the "remote-contact" property to that contact. If
881          * there are more, set the "remote-contact" property to NULL and the
882          * UI will display a contact list. */
883         self_handle = tp_channel_group_get_self_handle (priv->channel);
884         for (l = priv->members; l; l = l->next) {
885                 /* Skip self contact if member */
886                 if (empathy_contact_get_handle (l->data) == self_handle) {
887                         continue;
888                 }
889
890                 /* We have more than one remote contact, break */
891                 if (contact != NULL) {
892                         contact = NULL;
893                         break;
894                 }
895
896                 /* If we didn't find yet a remote contact, keep this one */
897                 contact = l->data;
898         }
899
900         if (priv->remote_contact == contact) {
901                 return;
902         }
903
904         DEBUG ("Changing remote contact from %p to %p",
905                 priv->remote_contact, contact);
906
907         if (priv->remote_contact) {
908                 g_object_unref (priv->remote_contact);
909         }
910
911         priv->remote_contact = contact ? g_object_ref (contact) : NULL;
912         g_object_notify (G_OBJECT (chat), "remote-contact");
913 }
914
915 static void
916 tp_chat_got_added_contacts_cb (TpConnection            *connection,
917                                guint                    n_contacts,
918                                EmpathyContact * const * contacts,
919                                guint                    n_failed,
920                                const TpHandle          *failed,
921                                const GError            *error,
922                                gpointer                 user_data,
923                                GObject                 *chat)
924 {
925         EmpathyTpChatPriv *priv = GET_PRIV (chat);
926         guint i;
927         const TpIntSet *members;
928         TpHandle handle;
929         EmpathyContact *contact;
930
931         if (error) {
932                 DEBUG ("Error: %s", error->message);
933                 return;
934         }
935
936         members = tp_channel_group_get_members (priv->channel);
937         for (i = 0; i < n_contacts; i++) {
938                 contact = contacts[i];
939                 handle = empathy_contact_get_handle (contact);
940
941                 /* Make sure the contact is still member */
942                 if (tp_intset_is_member (members, handle)) {
943                         priv->members = g_list_prepend (priv->members,
944                                 g_object_ref (contact));
945                         g_signal_emit_by_name (chat, "members-changed",
946                                                contact, NULL, 0, NULL, TRUE);
947                 }
948         }
949
950         tp_chat_update_remote_contact (EMPATHY_TP_CHAT (chat));
951         check_almost_ready (EMPATHY_TP_CHAT (chat));
952 }
953
954 static EmpathyContact *
955 chat_lookup_contact (EmpathyTpChat *chat,
956                      TpHandle       handle,
957                      gboolean       remove_)
958 {
959         EmpathyTpChatPriv *priv = GET_PRIV (chat);
960         GList *l;
961
962         for (l = priv->members; l; l = l->next) {
963                 EmpathyContact *c = l->data;
964
965                 if (empathy_contact_get_handle (c) != handle) {
966                         continue;
967                 }
968
969                 if (remove_) {
970                         /* Caller takes the reference. */
971                         priv->members = g_list_delete_link (priv->members, l);
972                 } else {
973                         g_object_ref (c);
974                 }
975
976                 return c;
977         }
978
979         return NULL;
980 }
981
982 typedef struct
983 {
984     TpHandle old_handle;
985     guint reason;
986     gchar *message;
987 } ContactRenameData;
988
989 static ContactRenameData *
990 contact_rename_data_new (TpHandle handle,
991                          guint reason,
992                          const gchar* message)
993 {
994         ContactRenameData *data = g_new (ContactRenameData, 1);
995         data->old_handle = handle;
996         data->reason = reason;
997         data->message = g_strdup (message);
998
999         return data;
1000 }
1001
1002 static void
1003 contact_rename_data_free (ContactRenameData* data)
1004 {
1005         g_free (data->message);
1006         g_free (data);
1007 }
1008
1009 static void
1010 tp_chat_got_renamed_contacts_cb (TpConnection            *connection,
1011                                  guint                    n_contacts,
1012                                  EmpathyContact * const * contacts,
1013                                  guint                    n_failed,
1014                                  const TpHandle          *failed,
1015                                  const GError            *error,
1016                                  gpointer                 user_data,
1017                                  GObject                 *chat)
1018 {
1019         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1020         const TpIntSet *members;
1021         TpHandle handle;
1022         EmpathyContact *old = NULL, *new = NULL;
1023         ContactRenameData *rename_data = (ContactRenameData *) user_data;
1024
1025         if (error) {
1026                 DEBUG ("Error: %s", error->message);
1027                 return;
1028         }
1029
1030         /* renamed members can only be delivered one at a time */
1031         g_warn_if_fail (n_contacts == 1);
1032
1033         new = contacts[0];
1034
1035         members = tp_channel_group_get_members (priv->channel);
1036         handle = empathy_contact_get_handle (new);
1037
1038         old = chat_lookup_contact (EMPATHY_TP_CHAT (chat),
1039                                    rename_data->old_handle, TRUE);
1040
1041         /* Make sure the contact is still member */
1042         if (tp_intset_is_member (members, handle)) {
1043                 priv->members = g_list_prepend (priv->members,
1044                         g_object_ref (new));
1045
1046                 if (old != NULL) {
1047                         g_signal_emit_by_name (chat, "member-renamed",
1048                                                old, new, rename_data->reason,
1049                                                rename_data->message);
1050                         g_object_unref (old);
1051                 }
1052         }
1053
1054         if (priv->user == old) {
1055                 /* We change our nick */
1056                 tp_clear_object (&priv->user);
1057                 priv->user = g_object_ref (new);
1058         }
1059
1060         tp_chat_update_remote_contact (EMPATHY_TP_CHAT (chat));
1061         check_almost_ready (EMPATHY_TP_CHAT (chat));
1062 }
1063
1064
1065 static void
1066 tp_chat_group_members_changed_cb (TpChannel     *self,
1067                                   gchar         *message,
1068                                   GArray        *added,
1069                                   GArray        *removed,
1070                                   GArray        *local_pending,
1071                                   GArray        *remote_pending,
1072                                   guint          actor,
1073                                   guint          reason,
1074                                   EmpathyTpChat *chat)
1075 {
1076         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1077         EmpathyContact *contact;
1078         EmpathyContact *actor_contact = NULL;
1079         guint i;
1080         ContactRenameData *rename_data;
1081         TpHandle old_handle;
1082
1083         /* Contact renamed */
1084         if (reason == TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED) {
1085                 /* there can only be a single 'added' and a single 'removed' handle */
1086                 if (removed->len != 1 || added->len != 1) {
1087                         g_warning ("RENAMED with %u added, %u removed (expected 1, 1)",
1088                                 added->len, removed->len);
1089                         return;
1090                 }
1091
1092                 old_handle = g_array_index (removed, guint, 0);
1093
1094                 rename_data = contact_rename_data_new (old_handle, reason, message);
1095                 empathy_tp_contact_factory_get_from_handles (priv->connection,
1096                         added->len, (TpHandle *) added->data,
1097                         tp_chat_got_renamed_contacts_cb,
1098                         rename_data, (GDestroyNotify) contact_rename_data_free,
1099                         G_OBJECT (chat));
1100                 return;
1101         }
1102
1103         if (actor != 0) {
1104                 actor_contact = chat_lookup_contact (chat, actor, FALSE);
1105                 if (actor_contact == NULL) {
1106                         /* FIXME: handle this a tad more gracefully: perhaps
1107                          * the actor was a server op. We could use the
1108                          * contact-ids detail of MembersChangedDetailed.
1109                          */
1110                         DEBUG ("actor %u not a channel member", actor);
1111                 }
1112         }
1113
1114         /* Remove contacts that are not members anymore */
1115         for (i = 0; i < removed->len; i++) {
1116                 contact = chat_lookup_contact (chat,
1117                         g_array_index (removed, TpHandle, i), TRUE);
1118
1119                 if (contact != NULL) {
1120                         g_signal_emit_by_name (chat, "members-changed", contact,
1121                                                actor_contact, reason, message,
1122                                                FALSE);
1123                         g_object_unref (contact);
1124                 }
1125         }
1126
1127         /* Request added contacts */
1128         if (added->len > 0) {
1129                 empathy_tp_contact_factory_get_from_handles (priv->connection,
1130                         added->len, (TpHandle *) added->data,
1131                         tp_chat_got_added_contacts_cb, NULL, NULL,
1132                         G_OBJECT (chat));
1133         }
1134
1135         tp_chat_update_remote_contact (chat);
1136
1137         if (actor_contact != NULL) {
1138                 g_object_unref (actor_contact);
1139         }
1140 }
1141
1142 static void
1143 tp_chat_got_remote_contact_cb (TpConnection            *connection,
1144                                EmpathyContact          *contact,
1145                                const GError            *error,
1146                                gpointer                 user_data,
1147                                GObject                 *chat)
1148 {
1149         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1150
1151         if (error) {
1152                 DEBUG ("Error: %s", error->message);
1153                 empathy_tp_chat_leave (EMPATHY_TP_CHAT (chat), "");
1154                 return;
1155         }
1156
1157         priv->remote_contact = g_object_ref (contact);
1158         g_object_notify (chat, "remote-contact");
1159
1160         check_almost_ready (EMPATHY_TP_CHAT (chat));
1161 }
1162
1163 static void
1164 tp_chat_got_self_contact_cb (TpConnection            *connection,
1165                              EmpathyContact          *contact,
1166                              const GError            *error,
1167                              gpointer                 user_data,
1168                              GObject                 *chat)
1169 {
1170         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1171
1172         if (error) {
1173                 DEBUG ("Error: %s", error->message);
1174                 empathy_tp_chat_leave (EMPATHY_TP_CHAT (chat), "");
1175                 return;
1176         }
1177
1178         priv->user = g_object_ref (contact);
1179         empathy_contact_set_is_user (priv->user, TRUE);
1180         check_almost_ready (EMPATHY_TP_CHAT (chat));
1181 }
1182
1183 static void
1184 password_flags_changed_cb (TpChannel *channel,
1185     guint added,
1186     guint removed,
1187     gpointer user_data,
1188     GObject *weak_object)
1189 {
1190         EmpathyTpChat *self = EMPATHY_TP_CHAT (weak_object);
1191         EmpathyTpChatPriv *priv = GET_PRIV (self);
1192         gboolean was_needed, needed;
1193
1194         was_needed = empathy_tp_chat_password_needed (self);
1195
1196         priv->password_flags |= added;
1197         priv->password_flags ^= removed;
1198
1199         needed = empathy_tp_chat_password_needed (self);
1200
1201         if (was_needed != needed)
1202                 g_object_notify (G_OBJECT (self), "password-needed");
1203 }
1204
1205 static void
1206 got_password_flags_cb (TpChannel *proxy,
1207                              guint password_flags,
1208                              const GError *error,
1209                              gpointer user_data,
1210                              GObject *weak_object)
1211 {
1212         EmpathyTpChat *self = EMPATHY_TP_CHAT (weak_object);
1213         EmpathyTpChatPriv *priv = GET_PRIV (self);
1214
1215         priv->got_password_flags = TRUE;
1216         priv->password_flags = password_flags;
1217
1218         check_almost_ready (EMPATHY_TP_CHAT (self));
1219 }
1220
1221 static GObject *
1222 tp_chat_constructor (GType                  type,
1223                      guint                  n_props,
1224                      GObjectConstructParam *props)
1225 {
1226         GObject           *chat;
1227         EmpathyTpChatPriv *priv;
1228         TpHandle           handle;
1229
1230         chat = G_OBJECT_CLASS (empathy_tp_chat_parent_class)->constructor (type, n_props, props);
1231
1232         priv = GET_PRIV (chat);
1233
1234         priv->connection = g_object_ref (tp_account_get_connection (priv->account));
1235         tp_g_signal_connect_object (priv->channel, "invalidated",
1236                           G_CALLBACK (tp_chat_invalidated_cb),
1237                           chat, 0);
1238
1239         g_assert (tp_proxy_is_prepared (priv->connection,
1240                 TP_CONNECTION_FEATURE_CAPABILITIES));
1241
1242         if (tp_proxy_has_interface_by_id (priv->channel,
1243                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
1244                 const TpIntSet *members;
1245                 GArray *handles;
1246
1247                 /* Get self contact from the group's self handle */
1248                 handle = tp_channel_group_get_self_handle (priv->channel);
1249                 empathy_tp_contact_factory_get_from_handle (priv->connection,
1250                         handle, tp_chat_got_self_contact_cb,
1251                         NULL, NULL, chat);
1252
1253                 /* Get initial member contacts */
1254                 members = tp_channel_group_get_members (priv->channel);
1255                 handles = tp_intset_to_array (members);
1256                 empathy_tp_contact_factory_get_from_handles (priv->connection,
1257                         handles->len, (TpHandle *) handles->data,
1258                         tp_chat_got_added_contacts_cb, NULL, NULL, chat);
1259
1260                 priv->can_upgrade_to_muc = FALSE;
1261
1262                 tp_g_signal_connect_object (priv->channel, "group-members-changed",
1263                         G_CALLBACK (tp_chat_group_members_changed_cb), chat, 0);
1264         } else {
1265                 TpCapabilities *caps;
1266                 GPtrArray *classes;
1267                 guint i;
1268
1269                 /* Get the self contact from the connection's self handle */
1270                 handle = tp_connection_get_self_handle (priv->connection);
1271                 empathy_tp_contact_factory_get_from_handle (priv->connection,
1272                         handle, tp_chat_got_self_contact_cb,
1273                         NULL, NULL, chat);
1274
1275                 /* Get the remote contact */
1276                 handle = tp_channel_get_handle (priv->channel, NULL);
1277                 empathy_tp_contact_factory_get_from_handle (priv->connection,
1278                         handle, tp_chat_got_remote_contact_cb,
1279                         NULL, NULL, chat);
1280
1281                 caps = tp_connection_get_capabilities (priv->connection);
1282                 g_assert (caps != NULL);
1283
1284                 classes = tp_capabilities_get_channel_classes (caps);
1285
1286                 for (i = 0; i < classes->len; i++) {
1287                         GValueArray *array = g_ptr_array_index (classes, i);
1288                         const char **oprops = g_value_get_boxed (
1289                                 g_value_array_get_nth (array, 1));
1290
1291                         if (tp_strv_contains (oprops, TP_PROP_CHANNEL_INTERFACE_CONFERENCE_INITIAL_CHANNELS)) {
1292                                 priv->can_upgrade_to_muc = TRUE;
1293                                 break;
1294                         }
1295                 }
1296         }
1297
1298         if (tp_proxy_has_interface_by_id (priv->channel,
1299                                           TP_IFACE_QUARK_PROPERTIES_INTERFACE)) {
1300                 tp_cli_properties_interface_call_list_properties (priv->channel, -1,
1301                                                                   tp_chat_list_properties_cb,
1302                                                                   NULL, NULL,
1303                                                                   G_OBJECT (chat));
1304                 tp_cli_properties_interface_connect_to_properties_changed (priv->channel,
1305                                                                            tp_chat_properties_changed_cb,
1306                                                                            NULL, NULL,
1307                                                                            G_OBJECT (chat), NULL);
1308                 tp_cli_properties_interface_connect_to_property_flags_changed (priv->channel,
1309                                                                                tp_chat_property_flags_changed_cb,
1310                                                                                NULL, NULL,
1311                                                                                G_OBJECT (chat), NULL);
1312         }
1313
1314         /* Check if the chat is password protected */
1315         if (tp_proxy_has_interface_by_id (priv->channel,
1316                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_PASSWORD)) {
1317                 priv->got_password_flags = FALSE;
1318
1319                 tp_cli_channel_interface_password_connect_to_password_flags_changed
1320                         (priv->channel, password_flags_changed_cb, chat, NULL,
1321                          G_OBJECT (chat), NULL);
1322
1323                 tp_cli_channel_interface_password_call_get_password_flags
1324                         (priv->channel, -1, got_password_flags_cb, chat, NULL, chat);
1325         } else {
1326                 /* No Password interface, so no need to fetch the password flags */
1327                 priv->got_password_flags = TRUE;
1328         }
1329
1330         return chat;
1331 }
1332
1333 static void
1334 tp_chat_get_property (GObject    *object,
1335                       guint       param_id,
1336                       GValue     *value,
1337                       GParamSpec *pspec)
1338 {
1339         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
1340         EmpathyTpChatPriv *priv = GET_PRIV (object);
1341
1342         switch (param_id) {
1343         case PROP_ACCOUNT:
1344                 g_value_set_object (value, priv->account);
1345                 break;
1346         case PROP_CHANNEL:
1347                 g_value_set_object (value, priv->channel);
1348                 break;
1349         case PROP_REMOTE_CONTACT:
1350                 g_value_set_object (value, priv->remote_contact);
1351                 break;
1352         case PROP_READY:
1353                 g_value_set_boolean (value, priv->ready);
1354                 break;
1355         case PROP_PASSWORD_NEEDED:
1356                 g_value_set_boolean (value, empathy_tp_chat_password_needed (self));
1357                 break;
1358         default:
1359                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1360                 break;
1361         };
1362 }
1363
1364 static void
1365 tp_chat_set_property (GObject      *object,
1366                       guint         param_id,
1367                       const GValue *value,
1368                       GParamSpec   *pspec)
1369 {
1370         EmpathyTpChatPriv *priv = GET_PRIV (object);
1371
1372         switch (param_id) {
1373         case PROP_ACCOUNT:
1374                 priv->account = g_value_dup_object (value);
1375                 break;
1376         case PROP_CHANNEL:
1377                 priv->channel = g_value_dup_object (value);
1378                 break;
1379         default:
1380                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1381                 break;
1382         };
1383 }
1384
1385 static void
1386 empathy_tp_chat_class_init (EmpathyTpChatClass *klass)
1387 {
1388         GObjectClass *object_class = G_OBJECT_CLASS (klass);
1389
1390         object_class->dispose = tp_chat_dispose;
1391         object_class->finalize = tp_chat_finalize;
1392         object_class->constructor = tp_chat_constructor;
1393         object_class->get_property = tp_chat_get_property;
1394         object_class->set_property = tp_chat_set_property;
1395
1396         g_object_class_install_property (object_class,
1397                                          PROP_ACCOUNT,
1398                                          g_param_spec_object ("account",
1399                                                               "TpAccount",
1400                                                               "the account associated with the chat",
1401                                                               TP_TYPE_ACCOUNT,
1402                                                               G_PARAM_READWRITE |
1403                                                               G_PARAM_CONSTRUCT_ONLY |
1404                                                               G_PARAM_STATIC_STRINGS));
1405
1406         g_object_class_install_property (object_class,
1407                                          PROP_CHANNEL,
1408                                          g_param_spec_object ("channel",
1409                                                               "telepathy channel",
1410                                                               "The text channel for the chat",
1411                                                               TP_TYPE_CHANNEL,
1412                                                               G_PARAM_READWRITE |
1413                                                               G_PARAM_CONSTRUCT_ONLY));
1414
1415         g_object_class_install_property (object_class,
1416                                          PROP_REMOTE_CONTACT,
1417                                          g_param_spec_object ("remote-contact",
1418                                                               "The remote contact",
1419                                                               "The remote contact if there is no group iface on the channel",
1420                                                               EMPATHY_TYPE_CONTACT,
1421                                                               G_PARAM_READABLE));
1422
1423         g_object_class_install_property (object_class,
1424                                          PROP_READY,
1425                                          g_param_spec_boolean ("ready",
1426                                                                "Is the object ready",
1427                                                                "This object can't be used until this becomes true",
1428                                                                FALSE,
1429                                                                G_PARAM_READABLE));
1430
1431         g_object_class_install_property (object_class,
1432                                          PROP_PASSWORD_NEEDED,
1433                                          g_param_spec_boolean ("password-needed",
1434                                                                "password needed",
1435                                                                "TRUE if a password is needed to join the channel",
1436                                                                FALSE,
1437                                                                G_PARAM_READABLE));
1438
1439         /* Signals */
1440         signals[MESSAGE_RECEIVED] =
1441                 g_signal_new ("message-received",
1442                               G_TYPE_FROM_CLASS (klass),
1443                               G_SIGNAL_RUN_LAST,
1444                               0,
1445                               NULL, NULL,
1446                               g_cclosure_marshal_VOID__OBJECT,
1447                               G_TYPE_NONE,
1448                               1, EMPATHY_TYPE_MESSAGE);
1449
1450         signals[SEND_ERROR] =
1451                 g_signal_new ("send-error",
1452                               G_TYPE_FROM_CLASS (klass),
1453                               G_SIGNAL_RUN_LAST,
1454                               0,
1455                               NULL, NULL,
1456                               _empathy_marshal_VOID__STRING_UINT,
1457                               G_TYPE_NONE,
1458                               2, G_TYPE_STRING, G_TYPE_UINT);
1459
1460         signals[CHAT_STATE_CHANGED] =
1461                 g_signal_new ("chat-state-changed",
1462                               G_TYPE_FROM_CLASS (klass),
1463                               G_SIGNAL_RUN_LAST,
1464                               0,
1465                               NULL, NULL,
1466                               _empathy_marshal_VOID__OBJECT_UINT,
1467                               G_TYPE_NONE,
1468                               2, EMPATHY_TYPE_CONTACT, G_TYPE_UINT);
1469
1470         signals[PROPERTY_CHANGED] =
1471                 g_signal_new ("property-changed",
1472                               G_TYPE_FROM_CLASS (klass),
1473                               G_SIGNAL_RUN_LAST,
1474                               0,
1475                               NULL, NULL,
1476                               _empathy_marshal_VOID__STRING_BOXED,
1477                               G_TYPE_NONE,
1478                               2, G_TYPE_STRING, G_TYPE_VALUE);
1479
1480         signals[DESTROY] =
1481                 g_signal_new ("destroy",
1482                               G_TYPE_FROM_CLASS (klass),
1483                               G_SIGNAL_RUN_LAST,
1484                               0,
1485                               NULL, NULL,
1486                               g_cclosure_marshal_VOID__VOID,
1487                               G_TYPE_NONE,
1488                               0);
1489
1490         g_type_class_add_private (object_class, sizeof (EmpathyTpChatPriv));
1491 }
1492
1493 static void
1494 empathy_tp_chat_init (EmpathyTpChat *chat)
1495 {
1496         EmpathyTpChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
1497                 EMPATHY_TYPE_TP_CHAT, EmpathyTpChatPriv);
1498
1499         chat->priv = priv;
1500         priv->messages_queue = g_queue_new ();
1501         priv->pending_messages_queue = g_queue_new ();
1502 }
1503
1504 static void
1505 tp_chat_iface_init (EmpathyContactListIface *iface)
1506 {
1507         iface->add         = tp_chat_add;
1508         iface->remove      = tp_chat_remove;
1509         iface->get_members = tp_chat_get_members;
1510 }
1511
1512 EmpathyTpChat *
1513 empathy_tp_chat_new (TpAccount *account,
1514                      TpChannel *channel)
1515 {
1516         g_return_val_if_fail (TP_IS_ACCOUNT (account), NULL);
1517         g_return_val_if_fail (TP_IS_TEXT_CHANNEL (channel), NULL);
1518
1519         return g_object_new (EMPATHY_TYPE_TP_CHAT,
1520                              "account", account,
1521                              "channel", channel,
1522                              NULL);
1523 }
1524
1525 const gchar *
1526 empathy_tp_chat_get_id (EmpathyTpChat *chat)
1527 {
1528         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1529         const gchar *id;
1530
1531
1532         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1533
1534         id = tp_channel_get_identifier (priv->channel);
1535         if (!EMP_STR_EMPTY (id))
1536                 return id;
1537         else if (priv->remote_contact)
1538                 return empathy_contact_get_id (priv->remote_contact);
1539         else
1540                 return NULL;
1541
1542 }
1543
1544 EmpathyContact *
1545 empathy_tp_chat_get_remote_contact (EmpathyTpChat *chat)
1546 {
1547         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1548
1549         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1550         g_return_val_if_fail (priv->ready, NULL);
1551
1552         return priv->remote_contact;
1553 }
1554
1555 TpChannel *
1556 empathy_tp_chat_get_channel (EmpathyTpChat *chat)
1557 {
1558         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1559
1560         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1561
1562         return priv->channel;
1563 }
1564
1565 TpAccount *
1566 empathy_tp_chat_get_account (EmpathyTpChat *chat)
1567 {
1568         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1569
1570         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1571
1572         return priv->account;
1573 }
1574
1575 TpConnection *
1576 empathy_tp_chat_get_connection (EmpathyTpChat *chat)
1577 {
1578         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1579
1580         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1581
1582         return tp_channel_borrow_connection (priv->channel);
1583 }
1584 gboolean
1585 empathy_tp_chat_is_ready (EmpathyTpChat *chat)
1586 {
1587         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1588
1589         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), FALSE);
1590
1591         return priv->ready;
1592 }
1593
1594 void
1595 empathy_tp_chat_send (EmpathyTpChat *chat,
1596                       TpMessage *message)
1597 {
1598         EmpathyTpChatPriv        *priv = GET_PRIV (chat);
1599         gchar *message_body;
1600
1601         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1602         g_return_if_fail (TP_IS_CLIENT_MESSAGE (message));
1603         g_return_if_fail (priv->ready);
1604
1605         message_body = tp_message_to_text (message, NULL);
1606
1607         DEBUG ("Sending message: %s", message_body);
1608
1609         tp_text_channel_send_message_async (TP_TEXT_CHANNEL (priv->channel),
1610                 message, 0, message_send_cb, chat);
1611
1612         g_free (message_body);
1613 }
1614
1615 void
1616 empathy_tp_chat_set_state (EmpathyTpChat      *chat,
1617                            TpChannelChatState  state)
1618 {
1619         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1620
1621         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1622         g_return_if_fail (priv->ready);
1623
1624         if (tp_proxy_has_interface_by_id (priv->channel,
1625                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_CHAT_STATE)) {
1626                 DEBUG ("Set state: %d", state);
1627                 tp_cli_channel_interface_chat_state_call_set_chat_state (priv->channel, -1,
1628                                                                          state,
1629                                                                          tp_chat_async_cb,
1630                                                                          "setting chat state",
1631                                                                          NULL,
1632                                                                          G_OBJECT (chat));
1633         }
1634 }
1635
1636
1637 const GList *
1638 empathy_tp_chat_get_pending_messages (EmpathyTpChat *chat)
1639 {
1640         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1641
1642         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1643         g_return_val_if_fail (priv->ready, NULL);
1644
1645         return priv->pending_messages_queue->head;
1646 }
1647
1648 static void
1649 acknowledge_messages (EmpathyTpChat *chat, GArray *ids) {
1650         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1651
1652         tp_cli_channel_type_text_call_acknowledge_pending_messages (
1653                 priv->channel, -1, ids, tp_chat_async_cb,
1654                 "acknowledging received message", NULL, G_OBJECT (chat));
1655 }
1656
1657 void
1658 empathy_tp_chat_acknowledge_message (EmpathyTpChat *chat,
1659                                      EmpathyMessage *message) {
1660         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1661         GArray *message_ids;
1662         GList *m;
1663         guint id;
1664
1665         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1666         g_return_if_fail (priv->ready);
1667
1668         if (!empathy_message_is_incoming (message))
1669                 goto out;
1670
1671         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
1672
1673         id = empathy_message_get_id (message);
1674         g_array_append_val (message_ids, id);
1675         acknowledge_messages (chat, message_ids);
1676         g_array_free (message_ids, TRUE);
1677
1678 out:
1679         m = g_queue_find (priv->pending_messages_queue, message);
1680         g_assert (m != NULL);
1681         g_queue_delete_link (priv->pending_messages_queue, m);
1682         g_object_unref (message);
1683 }
1684
1685 void
1686 empathy_tp_chat_acknowledge_messages (EmpathyTpChat *chat,
1687                                       const GSList *messages) {
1688         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1689         /* Copy messages as the messges list (probably is) our own */
1690         GSList *msgs = g_slist_copy ((GSList *) messages);
1691         GSList *l;
1692         guint length;
1693         GArray *message_ids;
1694
1695         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1696         g_return_if_fail (priv->ready);
1697
1698         length = g_slist_length ((GSList *) messages);
1699
1700         if (length == 0)
1701                 return;
1702
1703         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), length);
1704
1705         for (l = msgs; l != NULL; l = g_slist_next (l)) {
1706                 GList *m;
1707
1708                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1709
1710                 m = g_queue_find (priv->pending_messages_queue, message);
1711                 g_assert (m != NULL);
1712                 g_queue_delete_link (priv->pending_messages_queue, m);
1713
1714                 if (empathy_message_is_incoming (message)) {
1715                         guint id = empathy_message_get_id (message);
1716                         g_array_append_val (message_ids, id);
1717                 }
1718                 g_object_unref (message);
1719         }
1720
1721         if (message_ids->len > 0)
1722                 acknowledge_messages (chat, message_ids);
1723
1724         g_array_free (message_ids, TRUE);
1725         g_slist_free (msgs);
1726 }
1727
1728 void
1729 empathy_tp_chat_acknowledge_all_messages (EmpathyTpChat *chat)
1730 {
1731   empathy_tp_chat_acknowledge_messages (chat,
1732     (GSList *) empathy_tp_chat_get_pending_messages (chat));
1733 }
1734
1735 gboolean
1736 empathy_tp_chat_password_needed (EmpathyTpChat *self)
1737 {
1738         EmpathyTpChatPriv *priv = GET_PRIV (self);
1739
1740         return priv->password_flags & TP_CHANNEL_PASSWORD_FLAG_PROVIDE;
1741 }
1742
1743 static void
1744 provide_password_cb (TpChannel *channel,
1745                                       gboolean correct,
1746                                       const GError *error,
1747                                       gpointer user_data,
1748                                       GObject *weak_object)
1749 {
1750         GSimpleAsyncResult *result = user_data;
1751
1752         if (error != NULL) {
1753                 g_simple_async_result_set_from_error (result, error);
1754         }
1755         else if (!correct) {
1756                 /* The current D-Bus API is a bit weird so re-use the
1757                  * AuthenticationFailed error */
1758                 g_simple_async_result_set_error (result, TP_ERRORS,
1759                                                  TP_ERROR_AUTHENTICATION_FAILED, "Wrong password");
1760         }
1761
1762         g_simple_async_result_complete (result);
1763         g_object_unref (result);
1764 }
1765
1766 void
1767 empathy_tp_chat_provide_password_async (EmpathyTpChat *self,
1768                                                      const gchar *password,
1769                                                      GAsyncReadyCallback callback,
1770                                                      gpointer user_data)
1771 {
1772         EmpathyTpChatPriv *priv = GET_PRIV (self);
1773         GSimpleAsyncResult *result;
1774
1775         result = g_simple_async_result_new (G_OBJECT (self),
1776                                             callback, user_data,
1777                                             empathy_tp_chat_provide_password_finish);
1778
1779         tp_cli_channel_interface_password_call_provide_password
1780                 (priv->channel, -1, password, provide_password_cb, result,
1781                  NULL, G_OBJECT (self));
1782 }
1783
1784 gboolean
1785 empathy_tp_chat_provide_password_finish (EmpathyTpChat *self,
1786                                                       GAsyncResult *result,
1787                                                       GError **error)
1788 {
1789         if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result),
1790                 error))
1791                 return FALSE;
1792
1793         g_return_val_if_fail (g_simple_async_result_is_valid (result,
1794                                                               G_OBJECT (self), empathy_tp_chat_provide_password_finish), FALSE);
1795
1796         return TRUE;
1797 }
1798
1799 /**
1800  * empathy_tp_chat_can_add_contact:
1801  *
1802  * Returns: %TRUE if empathy_contact_list_add() will work for this channel.
1803  * That is if this chat is a 1-to-1 channel that can be upgraded to
1804  * a MUC using the Conference interface or if the channel is a MUC.
1805  */
1806 gboolean
1807 empathy_tp_chat_can_add_contact (EmpathyTpChat *self)
1808 {
1809         EmpathyTpChatPriv *priv;
1810
1811         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), FALSE);
1812
1813         priv = GET_PRIV (self);
1814
1815         return priv->can_upgrade_to_muc ||
1816                 tp_proxy_has_interface_by_id (priv->channel,
1817                         TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP);;
1818 }
1819
1820 static void
1821 tp_channel_leave_async_cb (GObject *source_object,
1822         GAsyncResult *res,
1823         gpointer user_data)
1824 {
1825         GError *error = NULL;
1826
1827         if (!tp_channel_leave_finish (TP_CHANNEL (source_object), res, &error)) {
1828                 DEBUG ("Could not leave channel properly: (%s); closing the channel",
1829                         error->message);
1830                 g_error_free (error);
1831         }
1832 }
1833
1834 void
1835 empathy_tp_chat_leave (EmpathyTpChat *self,
1836                 const gchar *message)
1837 {
1838         EmpathyTpChatPriv *priv = GET_PRIV (self);
1839
1840         tp_channel_leave_async (priv->channel, TP_CHANNEL_GROUP_CHANGE_REASON_NONE,
1841                 message, tp_channel_leave_async_cb, self);
1842 }
1843
1844 static void
1845 add_members_cb (TpChannel *proxy,
1846                 const GError *error,
1847                 gpointer user_data,
1848                 GObject *weak_object)
1849 {
1850         EmpathyTpChatPriv *priv = GET_PRIV (weak_object);
1851
1852         if (error != NULL) {
1853                 DEBUG ("Failed to join chat (%s): %s",
1854                         tp_channel_get_identifier (priv->channel), error->message);
1855         }
1856 }
1857
1858 void
1859 empathy_tp_chat_join (EmpathyTpChat *self)
1860 {
1861         EmpathyTpChatPriv *priv = GET_PRIV (self);
1862         TpHandle self_handle;
1863         GArray *members;
1864
1865         self_handle = tp_channel_group_get_self_handle (priv->channel);
1866
1867         members = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), 1);
1868         g_array_append_val (members, self_handle);
1869
1870         tp_cli_channel_interface_group_call_add_members (priv->channel, -1, members,
1871                 "", add_members_cb, NULL, NULL, G_OBJECT (self));
1872
1873         g_array_free (members, TRUE);
1874 }
1875
1876 gboolean
1877 empathy_tp_chat_is_invited (EmpathyTpChat *self,
1878                             TpHandle *inviter)
1879 {
1880         EmpathyTpChatPriv *priv = GET_PRIV (self);
1881         TpHandle self_handle;
1882
1883         if (!tp_proxy_has_interface (priv->channel, TP_IFACE_CHANNEL_INTERFACE_GROUP))
1884                 return FALSE;
1885
1886         self_handle = tp_channel_group_get_self_handle (priv->channel);
1887         if (self_handle == 0)
1888                 return FALSE;
1889
1890         return tp_channel_group_get_local_pending_info (priv->channel, self_handle,
1891                 inviter, NULL, NULL);
1892 }
1893
1894 TpChannelChatState
1895 empathy_tp_chat_get_chat_state (EmpathyTpChat *chat,
1896                             EmpathyContact *contact)
1897 {
1898         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1899         return tp_channel_get_chat_state (priv->channel,
1900                 empathy_contact_get_handle (contact));
1901 }
1902
1903 EmpathyContact *
1904 empathy_tp_chat_get_self_contact (EmpathyTpChat *self)
1905 {
1906         EmpathyTpChatPriv *priv = GET_PRIV (self);
1907
1908         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (self), NULL);
1909
1910         return priv->user;
1911 }