]> git.0d.be Git - empathy.git/blob - libempathy/empathy-tp-chat.c
coding style fixes
[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/channel.h>
27 #include <telepathy-glib/dbus.h>
28 #include <telepathy-glib/util.h>
29 #include <telepathy-glib/interfaces.h>
30
31 #include "empathy-tp-chat.h"
32 #include "empathy-tp-contact-factory.h"
33 #include "empathy-contact-monitor.h"
34 #include "empathy-contact-list.h"
35 #include "empathy-marshal.h"
36 #include "empathy-time.h"
37 #include "empathy-utils.h"
38
39 #define DEBUG_FLAG EMPATHY_DEBUG_TP | EMPATHY_DEBUG_CHAT
40 #include "empathy-debug.h"
41
42 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyTpChat)
43 typedef struct {
44         gboolean               dispose_has_run;
45         EmpathyTpContactFactory *factory;
46         EmpathyContactMonitor *contact_monitor;
47         EmpathyContact        *user;
48         EmpathyContact        *remote_contact;
49         GList                 *members;
50         TpChannel             *channel;
51         gboolean               listing_pending_messages;
52         /* Queue of messages not signalled yet */
53         GQueue                *messages_queue;
54         /* Queue of messages signalled but not acked yet */
55         GQueue                *pending_messages_queue;
56         gboolean               had_properties_list;
57         GPtrArray             *properties;
58         TpChannelPasswordFlags password_flags;
59         /* TRUE if we fetched the password flag of the channel or if it's not needed
60          * (channel doesn't implement the Password interface) */
61         gboolean               got_password_flags;
62         gboolean               ready;
63 } EmpathyTpChatPriv;
64
65 static void tp_chat_iface_init         (EmpathyContactListIface *iface);
66
67 enum {
68         PROP_0,
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 tp_chat_add (EmpathyContactList *list,
116              EmpathyContact     *contact,
117              const gchar        *message)
118 {
119         EmpathyTpChatPriv *priv = GET_PRIV (list);
120         TpHandle           handle;
121         GArray             handles = {(gchar *) &handle, 1};
122
123         g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
124         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
125
126         handle = empathy_contact_get_handle (contact);
127         tp_cli_channel_interface_group_call_add_members (priv->channel, -1,
128                                                          &handles, NULL,
129                                                          NULL, NULL, NULL,
130                                                          NULL);
131 }
132
133 static void
134 tp_chat_remove (EmpathyContactList *list,
135                 EmpathyContact     *contact,
136                 const gchar        *message)
137 {
138         EmpathyTpChatPriv *priv = GET_PRIV (list);
139         TpHandle           handle;
140         GArray             handles = {(gchar *) &handle, 1};
141
142         g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
143         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
144
145         handle = empathy_contact_get_handle (contact);
146         tp_cli_channel_interface_group_call_remove_members (priv->channel, -1,
147                                                             &handles, NULL,
148                                                             NULL, NULL, NULL,
149                                                             NULL);
150 }
151
152 static GList *
153 tp_chat_get_members (EmpathyContactList *list)
154 {
155         EmpathyTpChatPriv *priv = GET_PRIV (list);
156         GList             *members = NULL;
157
158         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (list), NULL);
159
160         if (priv->members) {
161                 members = g_list_copy (priv->members);
162                 g_list_foreach (members, (GFunc) g_object_ref, NULL);
163         } else {
164                 members = g_list_prepend (members, g_object_ref (priv->user));
165                 if (priv->remote_contact != NULL)
166                         members = g_list_prepend (members, g_object_ref (priv->remote_contact));
167         }
168
169         return members;
170 }
171
172 static EmpathyContactMonitor *
173 tp_chat_get_monitor (EmpathyContactList *list)
174 {
175         EmpathyTpChatPriv *priv;
176
177         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (list), NULL);
178
179         priv = GET_PRIV (list);
180
181         if (priv->contact_monitor == NULL) {
182                 priv->contact_monitor = empathy_contact_monitor_new_for_iface (list);
183         }
184
185         return priv->contact_monitor;
186 }
187
188 static void
189 tp_chat_emit_queued_messages (EmpathyTpChat *chat)
190 {
191         EmpathyTpChatPriv *priv = GET_PRIV (chat);
192         EmpathyMessage    *message;
193
194         /* Check if we can now emit some queued messages */
195         while ((message = g_queue_peek_head (priv->messages_queue)) != NULL) {
196                 if (empathy_message_get_sender (message) == NULL) {
197                         break;
198                 }
199
200                 DEBUG ("Queued message ready");
201                 g_queue_pop_head (priv->messages_queue);
202                 g_queue_push_tail (priv->pending_messages_queue, message);
203                 g_signal_emit (chat, signals[MESSAGE_RECEIVED], 0, message);
204         }
205 }
206
207 static void
208 tp_chat_got_sender_cb (EmpathyTpContactFactory *factory,
209                        EmpathyContact          *contact,
210                        const GError            *error,
211                        gpointer                 message,
212                        GObject                 *chat)
213 {
214         EmpathyTpChatPriv *priv = GET_PRIV (chat);
215
216         if (error) {
217                 DEBUG ("Error: %s", error->message);
218                 /* Do not block the message queue, just drop this message */
219                 g_queue_remove (priv->messages_queue, message);
220         } else {
221                 empathy_message_set_sender (message, contact);
222         }
223
224         tp_chat_emit_queued_messages (EMPATHY_TP_CHAT (chat));
225 }
226
227 static void
228 tp_chat_build_message (EmpathyTpChat *chat,
229                        gboolean       incoming,
230                        guint          id,
231                        guint          type,
232                        guint          timestamp,
233                        guint          from_handle,
234                        const gchar   *message_body)
235 {
236         EmpathyTpChatPriv *priv;
237         EmpathyMessage    *message;
238
239         priv = GET_PRIV (chat);
240
241         message = empathy_message_new (message_body);
242         empathy_message_set_tptype (message, type);
243         empathy_message_set_receiver (message, priv->user);
244         empathy_message_set_timestamp (message, timestamp);
245         empathy_message_set_id (message, id);
246         empathy_message_set_incoming (message, incoming);
247
248         g_queue_push_tail (priv->messages_queue, message);
249
250         if (from_handle == 0) {
251                 empathy_message_set_sender (message, priv->user);
252                 tp_chat_emit_queued_messages (chat);
253         } else {
254                 empathy_tp_contact_factory_get_from_handle (priv->factory,
255                         from_handle,
256                         tp_chat_got_sender_cb,
257                         message, NULL, G_OBJECT (chat));
258         }
259 }
260
261 static void
262 tp_chat_received_cb (TpChannel   *channel,
263                      guint        message_id,
264                      guint        timestamp,
265                      guint        from_handle,
266                      guint        message_type,
267                      guint        message_flags,
268                      const gchar *message_body,
269                      gpointer     user_data,
270                      GObject     *chat_)
271 {
272         EmpathyTpChat *chat = EMPATHY_TP_CHAT (chat_);
273         EmpathyTpChatPriv *priv = GET_PRIV (chat);
274
275         if (priv->channel == NULL)
276                 return;
277
278         if (priv->listing_pending_messages) {
279                 return;
280         }
281
282         DEBUG ("Message received: %s", message_body);
283
284         if (message_flags & TP_CHANNEL_TEXT_MESSAGE_FLAG_NON_TEXT_CONTENT &&
285             !tp_strdiff (message_body, "")) {
286                 GArray *ids;
287
288                 DEBUG ("Empty message with NonTextContent, ignoring and acking.");
289
290                 ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
291                 g_array_append_val (ids, message_id);
292                 acknowledge_messages (chat, ids);
293                 g_array_free (ids, TRUE);
294
295                 return;
296         }
297
298         tp_chat_build_message (chat,
299                                TRUE,
300                                message_id,
301                                message_type,
302                                timestamp,
303                                from_handle,
304                                message_body);
305 }
306
307 static void
308 tp_chat_sent_cb (TpChannel   *channel,
309                  guint        timestamp,
310                  guint        message_type,
311                  const gchar *message_body,
312                  gpointer     user_data,
313                  GObject     *chat_)
314 {
315         EmpathyTpChat *chat = EMPATHY_TP_CHAT (chat_);
316         EmpathyTpChatPriv *priv = GET_PRIV (chat);
317
318         if (priv->channel == NULL)
319                 return;
320
321         DEBUG ("Message sent: %s", message_body);
322
323         tp_chat_build_message (chat,
324                                FALSE,
325                                0,
326                                message_type,
327                                timestamp,
328                                0,
329                                message_body);
330 }
331
332 static void
333 tp_chat_send_error_cb (TpChannel   *channel,
334                        guint        error_code,
335                        guint        timestamp,
336                        guint        message_type,
337                        const gchar *message_body,
338                        gpointer     user_data,
339                        GObject     *chat)
340 {
341         EmpathyTpChatPriv *priv = GET_PRIV (chat);
342
343         if (priv->channel == NULL)
344                 return;
345
346         DEBUG ("Error sending '%s' (%d)", message_body, error_code);
347
348         g_signal_emit (chat, signals[SEND_ERROR], 0, message_body, error_code);
349 }
350
351 static void
352 tp_chat_send_cb (TpChannel    *proxy,
353                  const GError *error,
354                  gpointer      user_data,
355                  GObject      *chat)
356 {
357         EmpathyMessage *message = EMPATHY_MESSAGE (user_data);
358
359         if (error) {
360                 DEBUG ("Error: %s", error->message);
361                 g_signal_emit (chat, signals[SEND_ERROR], 0,
362                                empathy_message_get_body (message),
363                                TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN);
364         }
365 }
366
367 typedef struct {
368         EmpathyTpChat *chat;
369         TpChannelChatState state;
370 } StateChangedData;
371
372 static void
373 tp_chat_state_changed_got_contact_cb (EmpathyTpContactFactory *factory,
374                                       EmpathyContact          *contact,
375                                       const GError            *error,
376                                       gpointer                 user_data,
377                                       GObject                 *chat)
378 {
379         TpChannelChatState state;
380
381         if (error) {
382                 DEBUG ("Error: %s", error->message);
383                 return;
384         }
385
386         state = GPOINTER_TO_UINT (user_data);
387         DEBUG ("Chat state changed for %s (%d): %d",
388                 empathy_contact_get_name (contact),
389                 empathy_contact_get_handle (contact), state);
390
391         g_signal_emit (chat, signals[CHAT_STATE_CHANGED], 0, contact, state);
392 }
393
394 static void
395 tp_chat_state_changed_cb (TpChannel *channel,
396                           TpHandle   handle,
397                           TpChannelChatState state,
398                           gpointer   user_data,
399                           GObject   *chat)
400 {
401         EmpathyTpChatPriv *priv = GET_PRIV (chat);
402
403         empathy_tp_contact_factory_get_from_handle (priv->factory, handle,
404                 tp_chat_state_changed_got_contact_cb, GUINT_TO_POINTER (state),
405                 NULL, chat);
406 }
407
408 static void
409 tp_chat_list_pending_messages_cb (TpChannel       *channel,
410                                   const GPtrArray *messages_list,
411                                   const GError    *error,
412                                   gpointer         user_data,
413                                   GObject         *chat_)
414 {
415         EmpathyTpChat     *chat = EMPATHY_TP_CHAT (chat_);
416         EmpathyTpChatPriv *priv = GET_PRIV (chat);
417         guint              i;
418         GArray            *empty_non_text_content_ids = NULL;
419
420         priv->listing_pending_messages = FALSE;
421
422         if (priv->channel == NULL)
423                 return;
424
425         if (error) {
426                 DEBUG ("Error listing pending messages: %s", error->message);
427                 return;
428         }
429
430         for (i = 0; i < messages_list->len; i++) {
431                 GValueArray    *message_struct;
432                 const gchar    *message_body;
433                 guint           message_id;
434                 guint           timestamp;
435                 guint           from_handle;
436                 guint           message_type;
437                 guint           message_flags;
438
439                 message_struct = g_ptr_array_index (messages_list, i);
440
441                 message_id = g_value_get_uint (g_value_array_get_nth (message_struct, 0));
442                 timestamp = g_value_get_uint (g_value_array_get_nth (message_struct, 1));
443                 from_handle = g_value_get_uint (g_value_array_get_nth (message_struct, 2));
444                 message_type = g_value_get_uint (g_value_array_get_nth (message_struct, 3));
445                 message_flags = g_value_get_uint (g_value_array_get_nth (message_struct, 4));
446                 message_body = g_value_get_string (g_value_array_get_nth (message_struct, 5));
447
448                 DEBUG ("Message pending: %s", message_body);
449
450                 if (message_flags & TP_CHANNEL_TEXT_MESSAGE_FLAG_NON_TEXT_CONTENT &&
451                     !tp_strdiff (message_body, "")) {
452                         DEBUG ("Empty message with NonTextContent, ignoring and acking.");
453
454                         if (empty_non_text_content_ids == NULL) {
455                                 empty_non_text_content_ids = g_array_new (FALSE, FALSE, sizeof (guint));
456                         }
457
458                         g_array_append_val (empty_non_text_content_ids, message_id);
459                         continue;
460                 }
461
462                 tp_chat_build_message (chat,
463                                        TRUE,
464                                        message_id,
465                                        message_type,
466                                        timestamp,
467                                        from_handle,
468                                        message_body);
469         }
470
471         if (empty_non_text_content_ids != NULL) {
472                 acknowledge_messages (chat, empty_non_text_content_ids);
473                 g_array_free (empty_non_text_content_ids, TRUE);
474         }
475 }
476
477 static void
478 tp_chat_property_flags_changed_cb (TpProxy         *proxy,
479                                    const GPtrArray *properties,
480                                    gpointer         user_data,
481                                    GObject         *chat)
482 {
483         EmpathyTpChatPriv *priv = GET_PRIV (chat);
484         guint              i, j;
485
486         if (priv->channel == NULL)
487                 return;
488
489         if (!priv->had_properties_list || !properties) {
490                 return;
491         }
492
493         for (i = 0; i < properties->len; i++) {
494                 GValueArray           *prop_struct;
495                 EmpathyTpChatProperty *property;
496                 guint                  id;
497                 guint                  flags;
498
499                 prop_struct = g_ptr_array_index (properties, i);
500                 id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
501                 flags = g_value_get_uint (g_value_array_get_nth (prop_struct, 1));
502
503                 for (j = 0; j < priv->properties->len; j++) {
504                         property = g_ptr_array_index (priv->properties, j);
505                         if (property->id == id) {
506                                 property->flags = flags;
507                                 DEBUG ("property %s flags changed: %d",
508                                         property->name, property->flags);
509                                 break;
510                         }
511                 }
512         }
513 }
514
515 static void
516 tp_chat_properties_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                 GValue                *src_value;
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                 src_value = g_value_get_boxed (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                                 if (property->value) {
545                                         g_value_copy (src_value, property->value);
546                                 } else {
547                                         property->value = tp_g_value_slice_dup (src_value);
548                                 }
549
550                                 DEBUG ("property %s changed", property->name);
551                                 g_signal_emit (chat, signals[PROPERTY_CHANGED], 0,
552                                                property->name, property->value);
553                                 break;
554                         }
555                 }
556         }
557 }
558
559 static void
560 tp_chat_get_properties_cb (TpProxy         *proxy,
561                            const GPtrArray *properties,
562                            const GError    *error,
563                            gpointer         user_data,
564                            GObject         *chat)
565 {
566         if (error) {
567                 DEBUG ("Error getting properties: %s", error->message);
568                 return;
569         }
570
571         tp_chat_properties_changed_cb (proxy, properties, user_data, chat);
572 }
573
574 static void
575 tp_chat_list_properties_cb (TpProxy         *proxy,
576                             const GPtrArray *properties,
577                             const GError    *error,
578                             gpointer         user_data,
579                             GObject         *chat)
580 {
581         EmpathyTpChatPriv *priv = GET_PRIV (chat);
582         GArray            *ids;
583         guint              i;
584
585         if (priv->channel == NULL)
586                 return;
587
588         priv->had_properties_list = TRUE;
589
590         if (error) {
591                 DEBUG ("Error listing properties: %s", error->message);
592                 return;
593         }
594
595         ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), properties->len);
596         priv->properties = g_ptr_array_sized_new (properties->len);
597         for (i = 0; i < properties->len; i++) {
598                 GValueArray           *prop_struct;
599                 EmpathyTpChatProperty *property;
600
601                 prop_struct = g_ptr_array_index (properties, i);
602                 property = g_slice_new0 (EmpathyTpChatProperty);
603                 property->id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
604                 property->name = g_value_dup_string (g_value_array_get_nth (prop_struct, 1));
605                 property->flags = g_value_get_uint (g_value_array_get_nth (prop_struct, 3));
606
607                 DEBUG ("Adding property name=%s id=%d flags=%d",
608                         property->name, property->id, property->flags);
609                 g_ptr_array_add (priv->properties, property);
610                 if (property->flags & TP_PROPERTY_FLAG_READ) {
611                         g_array_append_val (ids, property->id);
612                 }
613         }
614
615         tp_cli_properties_interface_call_get_properties (proxy, -1,
616                                                          ids,
617                                                          tp_chat_get_properties_cb,
618                                                          NULL, NULL,
619                                                          chat);
620
621         g_array_free (ids, TRUE);
622 }
623
624 void
625 empathy_tp_chat_set_property (EmpathyTpChat *chat,
626                               const gchar   *name,
627                               const GValue  *value)
628 {
629         EmpathyTpChatPriv     *priv = GET_PRIV (chat);
630         EmpathyTpChatProperty *property;
631         guint                  i;
632
633         if (!priv->had_properties_list) {
634                 return;
635         }
636
637         for (i = 0; i < priv->properties->len; i++) {
638                 property = g_ptr_array_index (priv->properties, i);
639                 if (!tp_strdiff (property->name, name)) {
640                         GPtrArray   *properties;
641                         GValueArray *prop;
642                         GValue       id = {0, };
643                         GValue       dest_value = {0, };
644
645                         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
646                                 break;
647                         }
648
649                         g_value_init (&id, G_TYPE_UINT);
650                         g_value_init (&dest_value, G_TYPE_VALUE);
651                         g_value_set_uint (&id, property->id);
652                         g_value_set_boxed (&dest_value, value);
653
654                         prop = g_value_array_new (2);
655                         g_value_array_append (prop, &id);
656                         g_value_array_append (prop, &dest_value);
657
658                         properties = g_ptr_array_sized_new (1);
659                         g_ptr_array_add (properties, prop);
660
661                         DEBUG ("Set property %s", name);
662                         tp_cli_properties_interface_call_set_properties (priv->channel, -1,
663                                                                          properties,
664                                                                          (tp_cli_properties_interface_callback_for_set_properties)
665                                                                          tp_chat_async_cb,
666                                                                          "Seting property", NULL,
667                                                                          G_OBJECT (chat));
668
669                         g_ptr_array_free (properties, TRUE);
670                         g_value_array_free (prop);
671
672                         break;
673                 }
674         }
675 }
676
677 EmpathyTpChatProperty *
678 empathy_tp_chat_get_property (EmpathyTpChat *chat,
679                               const gchar   *name)
680 {
681         EmpathyTpChatPriv     *priv = GET_PRIV (chat);
682         EmpathyTpChatProperty *property;
683         guint                  i;
684
685         if (!priv->had_properties_list) {
686                 return NULL;
687         }
688
689         for (i = 0; i < priv->properties->len; i++) {
690                 property = g_ptr_array_index (priv->properties, i);
691                 if (!tp_strdiff (property->name, name)) {
692                         return property;
693                 }
694         }
695
696         return NULL;
697 }
698
699 GPtrArray *
700 empathy_tp_chat_get_properties (EmpathyTpChat *chat)
701 {
702         EmpathyTpChatPriv *priv = GET_PRIV (chat);
703
704         return priv->properties;
705 }
706
707 static void
708 tp_chat_dispose (GObject *object)
709 {
710         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
711         EmpathyTpChatPriv *priv = GET_PRIV (self);
712
713         if (priv->dispose_has_run)
714                 return;
715
716         priv->dispose_has_run = TRUE;
717
718         if (priv->channel != NULL) {
719                 g_signal_handlers_disconnect_by_func (priv->channel,
720                         tp_chat_invalidated_cb, self);
721                 g_object_unref (priv->channel);
722         }
723         priv->channel = NULL;
724
725         if (priv->remote_contact != NULL)
726                 g_object_unref (priv->remote_contact);
727         priv->remote_contact = NULL;
728
729         if (priv->factory != NULL)
730                 g_object_unref (priv->factory);
731         priv->factory = NULL;
732
733         if (priv->user != NULL)
734                 g_object_unref (priv->user);
735         priv->user = NULL;
736
737         if (priv->contact_monitor)
738                 g_object_unref (priv->contact_monitor);
739         priv->contact_monitor = NULL;
740
741         g_queue_foreach (priv->messages_queue, (GFunc) g_object_unref, NULL);
742         g_queue_clear (priv->messages_queue);
743
744         g_queue_foreach (priv->pending_messages_queue,
745                 (GFunc) g_object_unref, NULL);
746         g_queue_clear (priv->pending_messages_queue);
747
748         if (G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose)
749                 G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose (object);
750 }
751
752 static void
753 tp_chat_finalize (GObject *object)
754 {
755         EmpathyTpChatPriv *priv = GET_PRIV (object);
756         guint              i;
757
758         DEBUG ("Finalize: %p", object);
759
760         if (priv->properties) {
761                 for (i = 0; i < priv->properties->len; i++) {
762                         EmpathyTpChatProperty *property;
763
764                         property = g_ptr_array_index (priv->properties, i);
765                         g_free (property->name);
766                         if (property->value) {
767                                 tp_g_value_slice_free (property->value);
768                         }
769                         g_slice_free (EmpathyTpChatProperty, property);
770                 }
771                 g_ptr_array_free (priv->properties, TRUE);
772         }
773
774         g_queue_free (priv->messages_queue);
775         g_queue_free (priv->pending_messages_queue);
776
777         G_OBJECT_CLASS (empathy_tp_chat_parent_class)->finalize (object);
778 }
779
780 static void
781 tp_chat_check_if_ready (EmpathyTpChat *chat)
782 {
783         EmpathyTpChatPriv *priv = GET_PRIV (chat);
784
785         if (priv->ready)
786                 return;
787
788         if (priv->user == NULL)
789                 return;
790
791         if (!priv->got_password_flags)
792                 return;
793
794         /* We need either the members (room) or the remote contact (private chat).
795          * If the chat is protected by a password we can't get these information so
796          * consider the chat as ready so it can be presented to the user. */
797         if (!empathy_tp_chat_password_needed (chat) && priv->members == NULL &&
798             priv->remote_contact == NULL)
799                 return;
800
801         DEBUG ("Ready!");
802
803         tp_cli_channel_type_text_connect_to_received (priv->channel,
804                                                       tp_chat_received_cb,
805                                                       NULL, NULL,
806                                                       G_OBJECT (chat), NULL);
807         priv->listing_pending_messages = TRUE;
808         tp_cli_channel_type_text_call_list_pending_messages (priv->channel, -1,
809                                                              FALSE,
810                                                              tp_chat_list_pending_messages_cb,
811                                                              NULL, NULL,
812                                                              G_OBJECT (chat));
813
814         tp_cli_channel_type_text_connect_to_sent (priv->channel,
815                                                   tp_chat_sent_cb,
816                                                   NULL, NULL,
817                                                   G_OBJECT (chat), NULL);
818         tp_cli_channel_type_text_connect_to_send_error (priv->channel,
819                                                         tp_chat_send_error_cb,
820                                                         NULL, NULL,
821                                                         G_OBJECT (chat), NULL);
822         tp_cli_channel_interface_chat_state_connect_to_chat_state_changed (priv->channel,
823                                                                            tp_chat_state_changed_cb,
824                                                                            NULL, NULL,
825                                                                            G_OBJECT (chat), NULL);
826         priv->ready = TRUE;
827         g_object_notify (G_OBJECT (chat), "ready");
828 }
829
830 static void
831 tp_chat_update_remote_contact (EmpathyTpChat *chat)
832 {
833         EmpathyTpChatPriv *priv = GET_PRIV (chat);
834         EmpathyContact *contact = NULL;
835         TpHandle self_handle;
836         TpHandleType handle_type;
837         GList *l;
838
839         /* If this is a named chatroom, never pretend it is a private chat */
840         tp_channel_get_handle (priv->channel, &handle_type);
841         if (handle_type == TP_HANDLE_TYPE_ROOM) {
842                 return;
843         }
844
845         /* This is an MSN-like chat where anyone can join the chat at anytime.
846          * If there is only one non-self contact member, we are in a private
847          * chat and we set the "remote-contact" property to that contact. If
848          * there are more, set the "remote-contact" property to NULL and the
849          * UI will display a contact list. */
850         self_handle = tp_channel_group_get_self_handle (priv->channel);
851         for (l = priv->members; l; l = l->next) {
852                 /* Skip self contact if member */
853                 if (empathy_contact_get_handle (l->data) == self_handle) {
854                         continue;
855                 }
856
857                 /* We have more than one remote contact, break */
858                 if (contact != NULL) {
859                         contact = NULL;
860                         break;
861                 }
862
863                 /* If we didn't find yet a remote contact, keep this one */
864                 contact = l->data;
865         }
866
867         if (priv->remote_contact == contact) {
868                 return;
869         }
870
871         DEBUG ("Changing remote contact from %p to %p",
872                 priv->remote_contact, contact);
873
874         if (priv->remote_contact) {
875                 g_object_unref (priv->remote_contact);
876         }
877
878         priv->remote_contact = contact ? g_object_ref (contact) : NULL;
879         g_object_notify (G_OBJECT (chat), "remote-contact");
880 }
881
882 static void
883 tp_chat_got_added_contacts_cb (EmpathyTpContactFactory *factory,
884                                guint                    n_contacts,
885                                EmpathyContact * const * contacts,
886                                guint                    n_failed,
887                                const TpHandle          *failed,
888                                const GError            *error,
889                                gpointer                 user_data,
890                                GObject                 *chat)
891 {
892         EmpathyTpChatPriv *priv = GET_PRIV (chat);
893         guint i;
894         const TpIntSet *members;
895         TpHandle handle;
896         EmpathyContact *contact;
897
898         if (error) {
899                 DEBUG ("Error: %s", error->message);
900                 return;
901         }
902
903         members = tp_channel_group_get_members (priv->channel);
904         for (i = 0; i < n_contacts; i++) {
905                 contact = contacts[i];
906                 handle = empathy_contact_get_handle (contact);
907
908                 /* Make sure the contact is still member */
909                 if (tp_intset_is_member (members, handle)) {
910                         priv->members = g_list_prepend (priv->members,
911                                 g_object_ref (contact));
912                         g_signal_emit_by_name (chat, "members-changed",
913                                                contact, NULL, 0, NULL, TRUE);
914                 }
915         }
916
917         tp_chat_update_remote_contact (EMPATHY_TP_CHAT (chat));
918         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
919 }
920
921 static EmpathyContact *
922 chat_lookup_contact (EmpathyTpChat *chat,
923                      TpHandle       handle,
924                      gboolean       remove_)
925 {
926         EmpathyTpChatPriv *priv = GET_PRIV (chat);
927         GList *l;
928
929         for (l = priv->members; l; l = l->next) {
930                 EmpathyContact *c = l->data;
931
932                 if (empathy_contact_get_handle (c) != handle) {
933                         continue;
934                 }
935
936                 if (remove_) {
937                         /* Caller takes the reference. */
938                         priv->members = g_list_delete_link (priv->members, l);
939                 } else {
940                         g_object_ref (c);
941                 }
942
943                 return c;
944         }
945
946         return NULL;
947 }
948
949 typedef struct
950 {
951     TpHandle old_handle;
952     guint reason;
953     const gchar *message;
954 } ContactRenameData;
955
956 static ContactRenameData *
957 contact_rename_data_new (TpHandle handle,
958                          guint reason,
959                          const gchar* message)
960 {
961         ContactRenameData *data = g_new (ContactRenameData, 1);
962         data->old_handle = handle;
963         data->reason = reason;
964         data->message = message;
965
966         return data;
967 }
968
969 static void
970 contact_rename_data_free (ContactRenameData* data)
971 {
972     g_free (data);
973 }
974
975 static void
976 tp_chat_got_renamed_contacts_cb (EmpathyTpContactFactory *factory,
977                                  guint                    n_contacts,
978                                  EmpathyContact * const * contacts,
979                                  guint                    n_failed,
980                                  const TpHandle          *failed,
981                                  const GError            *error,
982                                  gpointer                 user_data,
983                                  GObject                 *chat)
984 {
985         EmpathyTpChatPriv *priv = GET_PRIV (chat);
986         const TpIntSet *members;
987         TpHandle handle;
988         EmpathyContact *old = NULL, *new = NULL;
989         ContactRenameData *rename_data = (ContactRenameData *) user_data;
990
991         if (error) {
992                 DEBUG ("Error: %s", error->message);
993                 return;
994         }
995
996         /* renamed members can only be delivered one at a time */
997         g_warn_if_fail (n_contacts == 1);
998
999         new = contacts[0];
1000
1001         members = tp_channel_group_get_members (priv->channel);
1002         handle = empathy_contact_get_handle (new);
1003
1004         old = chat_lookup_contact (EMPATHY_TP_CHAT (chat),
1005                                    rename_data->old_handle, TRUE);
1006
1007         /* Make sure the contact is still member */
1008         if (tp_intset_is_member (members, handle)) {
1009                 priv->members = g_list_prepend (priv->members,
1010                         g_object_ref (new));
1011
1012                 if (old != NULL) {
1013                         g_signal_emit_by_name (chat, "member-renamed",
1014                                                old, new, rename_data->reason,
1015                                                rename_data->message);
1016                         g_object_unref (old);
1017                 }
1018         }
1019
1020         tp_chat_update_remote_contact (EMPATHY_TP_CHAT (chat));
1021         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
1022 }
1023
1024
1025 static void
1026 tp_chat_group_members_changed_cb (TpChannel     *self,
1027                                   gchar         *message,
1028                                   GArray        *added,
1029                                   GArray        *removed,
1030                                   GArray        *local_pending,
1031                                   GArray        *remote_pending,
1032                                   guint          actor,
1033                                   guint          reason,
1034                                   EmpathyTpChat *chat)
1035 {
1036         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1037         EmpathyContact *contact;
1038         EmpathyContact *actor_contact = NULL;
1039         guint i;
1040         ContactRenameData *rename_data;
1041         TpHandle old_handle;
1042
1043         /* Contact renamed */
1044         if (reason == TP_CHANNEL_GROUP_CHANGE_REASON_RENAMED) {
1045                 /* there can only be a single 'added' and a single 'removed' handle */
1046                 g_warn_if_fail (removed->len == 1);
1047                 g_warn_if_fail (added->len == 1);
1048
1049                 old_handle = g_array_index (removed, guint, 0);
1050
1051                 rename_data = contact_rename_data_new (old_handle, reason, message);
1052                 empathy_tp_contact_factory_get_from_handles (priv->factory,
1053                         added->len, (TpHandle *) added->data,
1054                         tp_chat_got_renamed_contacts_cb,
1055                         rename_data, (GDestroyNotify) contact_rename_data_free,
1056                         G_OBJECT (chat));
1057                 return;
1058         }
1059
1060         if (actor != 0) {
1061                 actor_contact = chat_lookup_contact (chat, actor, FALSE);
1062                 if (actor_contact == NULL) {
1063                         /* FIXME: handle this a tad more gracefully: perhaps
1064                          * the actor was a server op. We could use the
1065                          * contact-ids detail of MembersChangedDetailed.
1066                          */
1067                         DEBUG ("actor %u not a channel member", actor);
1068                 }
1069         }
1070
1071         /* Remove contacts that are not members anymore */
1072         for (i = 0; i < removed->len; i++) {
1073                 contact = chat_lookup_contact (chat,
1074                         g_array_index (removed, TpHandle, i), TRUE);
1075
1076                 if (contact != NULL) {
1077                         g_signal_emit_by_name (chat, "members-changed", contact,
1078                                                actor_contact, reason, message,
1079                                                FALSE);
1080                         g_object_unref (contact);
1081                 }
1082         }
1083
1084         /* Request added contacts */
1085         if (added->len > 0) {
1086                 empathy_tp_contact_factory_get_from_handles (priv->factory,
1087                         added->len, (TpHandle *) added->data,
1088                         tp_chat_got_added_contacts_cb, NULL, NULL,
1089                         G_OBJECT (chat));
1090         }
1091
1092         tp_chat_update_remote_contact (chat);
1093
1094         if (actor_contact != NULL) {
1095                 g_object_unref (actor_contact);
1096         }
1097 }
1098
1099 static void
1100 tp_chat_got_remote_contact_cb (EmpathyTpContactFactory *factory,
1101                                EmpathyContact          *contact,
1102                                const GError            *error,
1103                                gpointer                 user_data,
1104                                GObject                 *chat)
1105 {
1106         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1107
1108         if (error) {
1109                 DEBUG ("Error: %s", error->message);
1110                 empathy_tp_chat_close (EMPATHY_TP_CHAT (chat));
1111                 return;
1112         }
1113
1114         priv->remote_contact = g_object_ref (contact);
1115         g_object_notify (chat, "remote-contact");
1116
1117         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
1118 }
1119
1120 static void
1121 tp_chat_got_self_contact_cb (EmpathyTpContactFactory *factory,
1122                              EmpathyContact          *contact,
1123                              const GError            *error,
1124                              gpointer                 user_data,
1125                              GObject                 *chat)
1126 {
1127         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1128
1129         if (error) {
1130                 DEBUG ("Error: %s", error->message);
1131                 empathy_tp_chat_close (EMPATHY_TP_CHAT (chat));
1132                 return;
1133         }
1134
1135         priv->user = g_object_ref (contact);
1136         empathy_contact_set_is_user (priv->user, TRUE);
1137         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
1138 }
1139
1140 static void
1141 password_flags_changed_cb (TpChannel *channel,
1142     guint added,
1143     guint removed,
1144     gpointer user_data,
1145     GObject *weak_object)
1146 {
1147         EmpathyTpChat *self = EMPATHY_TP_CHAT (weak_object);
1148         EmpathyTpChatPriv *priv = GET_PRIV (self);
1149         gboolean was_needed, needed;
1150
1151         was_needed = empathy_tp_chat_password_needed (self);
1152
1153         priv->password_flags |= added;
1154         priv->password_flags ^= removed;
1155
1156         needed = empathy_tp_chat_password_needed (self);
1157
1158         if (was_needed != needed)
1159                 g_object_notify (G_OBJECT (self), "password-needed");
1160 }
1161
1162 static void
1163 got_password_flags_cb (TpChannel *proxy,
1164                              guint password_flags,
1165                              const GError *error,
1166                              gpointer user_data,
1167                              GObject *weak_object)
1168 {
1169         EmpathyTpChat *self = EMPATHY_TP_CHAT (weak_object);
1170         EmpathyTpChatPriv *priv = GET_PRIV (self);
1171
1172         priv->got_password_flags = TRUE;
1173         priv->password_flags = password_flags;
1174
1175         tp_chat_check_if_ready (EMPATHY_TP_CHAT (self));
1176 }
1177
1178 static GObject *
1179 tp_chat_constructor (GType                  type,
1180                      guint                  n_props,
1181                      GObjectConstructParam *props)
1182 {
1183         GObject           *chat;
1184         EmpathyTpChatPriv *priv;
1185         TpConnection      *connection;
1186         TpHandle           handle;
1187
1188         chat = G_OBJECT_CLASS (empathy_tp_chat_parent_class)->constructor (type, n_props, props);
1189
1190         priv = GET_PRIV (chat);
1191
1192         connection = tp_channel_borrow_connection (priv->channel);
1193         priv->factory = empathy_tp_contact_factory_dup_singleton (connection);
1194         g_signal_connect (priv->channel, "invalidated",
1195                           G_CALLBACK (tp_chat_invalidated_cb),
1196                           chat);
1197
1198         if (tp_proxy_has_interface_by_id (priv->channel,
1199                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
1200                 const TpIntSet *members;
1201                 GArray *handles;
1202
1203                 /* Get self contact from the group's self handle */
1204                 handle = tp_channel_group_get_self_handle (priv->channel);
1205                 empathy_tp_contact_factory_get_from_handle (priv->factory,
1206                         handle, tp_chat_got_self_contact_cb,
1207                         NULL, NULL, chat);
1208
1209                 /* Get initial member contacts */
1210                 members = tp_channel_group_get_members (priv->channel);
1211                 handles = tp_intset_to_array (members);
1212                 empathy_tp_contact_factory_get_from_handles (priv->factory,
1213                         handles->len, (TpHandle *) handles->data,
1214                         tp_chat_got_added_contacts_cb, NULL, NULL, chat);
1215
1216                 g_signal_connect (priv->channel, "group-members-changed",
1217                         G_CALLBACK (tp_chat_group_members_changed_cb), chat);
1218         } else {
1219                 /* Get the self contact from the connection's self handle */
1220                 handle = tp_connection_get_self_handle (connection);
1221                 empathy_tp_contact_factory_get_from_handle (priv->factory,
1222                         handle, tp_chat_got_self_contact_cb,
1223                         NULL, NULL, chat);
1224
1225                 /* Get the remote contact */
1226                 handle = tp_channel_get_handle (priv->channel, NULL);
1227                 empathy_tp_contact_factory_get_from_handle (priv->factory,
1228                         handle, tp_chat_got_remote_contact_cb,
1229                         NULL, NULL, chat);
1230         }
1231
1232         if (tp_proxy_has_interface_by_id (priv->channel,
1233                                           TP_IFACE_QUARK_PROPERTIES_INTERFACE)) {
1234                 tp_cli_properties_interface_call_list_properties (priv->channel, -1,
1235                                                                   tp_chat_list_properties_cb,
1236                                                                   NULL, NULL,
1237                                                                   G_OBJECT (chat));
1238                 tp_cli_properties_interface_connect_to_properties_changed (priv->channel,
1239                                                                            tp_chat_properties_changed_cb,
1240                                                                            NULL, NULL,
1241                                                                            G_OBJECT (chat), NULL);
1242                 tp_cli_properties_interface_connect_to_property_flags_changed (priv->channel,
1243                                                                                tp_chat_property_flags_changed_cb,
1244                                                                                NULL, NULL,
1245                                                                                G_OBJECT (chat), NULL);
1246         }
1247
1248         /* Check if the chat is password protected */
1249         if (tp_proxy_has_interface_by_id (priv->channel,
1250                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_PASSWORD)) {
1251                 priv->got_password_flags = FALSE;
1252
1253                 tp_cli_channel_interface_password_connect_to_password_flags_changed
1254                         (priv->channel, password_flags_changed_cb, chat, NULL,
1255                          G_OBJECT (chat), NULL);
1256
1257                 tp_cli_channel_interface_password_call_get_password_flags
1258                         (priv->channel, -1, got_password_flags_cb, chat, NULL, chat);
1259         } else {
1260                 /* No Password interface, so no need to fetch the password flags */
1261                 priv->got_password_flags = TRUE;
1262         }
1263
1264         return chat;
1265 }
1266
1267 static void
1268 tp_chat_get_property (GObject    *object,
1269                       guint       param_id,
1270                       GValue     *value,
1271                       GParamSpec *pspec)
1272 {
1273         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
1274         EmpathyTpChatPriv *priv = GET_PRIV (object);
1275
1276         switch (param_id) {
1277         case PROP_CHANNEL:
1278                 g_value_set_object (value, priv->channel);
1279                 break;
1280         case PROP_REMOTE_CONTACT:
1281                 g_value_set_object (value, priv->remote_contact);
1282                 break;
1283         case PROP_READY:
1284                 g_value_set_boolean (value, priv->ready);
1285                 break;
1286         case PROP_PASSWORD_NEEDED:
1287                 g_value_set_boolean (value, empathy_tp_chat_password_needed (self));
1288                 break;
1289         default:
1290                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1291                 break;
1292         };
1293 }
1294
1295 static void
1296 tp_chat_set_property (GObject      *object,
1297                       guint         param_id,
1298                       const GValue *value,
1299                       GParamSpec   *pspec)
1300 {
1301         EmpathyTpChatPriv *priv = GET_PRIV (object);
1302
1303         switch (param_id) {
1304         case PROP_CHANNEL:
1305                 priv->channel = g_value_dup_object (value);
1306                 break;
1307         default:
1308                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1309                 break;
1310         };
1311 }
1312
1313 static void
1314 empathy_tp_chat_class_init (EmpathyTpChatClass *klass)
1315 {
1316         GObjectClass *object_class = G_OBJECT_CLASS (klass);
1317
1318         object_class->dispose = tp_chat_dispose;
1319         object_class->finalize = tp_chat_finalize;
1320         object_class->constructor = tp_chat_constructor;
1321         object_class->get_property = tp_chat_get_property;
1322         object_class->set_property = tp_chat_set_property;
1323
1324         g_object_class_install_property (object_class,
1325                                          PROP_CHANNEL,
1326                                          g_param_spec_object ("channel",
1327                                                               "telepathy channel",
1328                                                               "The text channel for the chat",
1329                                                               TP_TYPE_CHANNEL,
1330                                                               G_PARAM_READWRITE |
1331                                                               G_PARAM_CONSTRUCT_ONLY));
1332
1333         g_object_class_install_property (object_class,
1334                                          PROP_REMOTE_CONTACT,
1335                                          g_param_spec_object ("remote-contact",
1336                                                               "The remote contact",
1337                                                               "The remote contact if there is no group iface on the channel",
1338                                                               EMPATHY_TYPE_CONTACT,
1339                                                               G_PARAM_READABLE));
1340
1341         g_object_class_install_property (object_class,
1342                                          PROP_READY,
1343                                          g_param_spec_boolean ("ready",
1344                                                                "Is the object ready",
1345                                                                "This object can't be used until this becomes true",
1346                                                                FALSE,
1347                                                                G_PARAM_READABLE));
1348
1349         g_object_class_install_property (object_class,
1350                                          PROP_PASSWORD_NEEDED,
1351                                          g_param_spec_boolean ("password-needed",
1352                                                                "password needed",
1353                                                                "TRUE if a password is needed to join the channel",
1354                                                                FALSE,
1355                                                                G_PARAM_READABLE));
1356
1357         /* Signals */
1358         signals[MESSAGE_RECEIVED] =
1359                 g_signal_new ("message-received",
1360                               G_TYPE_FROM_CLASS (klass),
1361                               G_SIGNAL_RUN_LAST,
1362                               0,
1363                               NULL, NULL,
1364                               g_cclosure_marshal_VOID__OBJECT,
1365                               G_TYPE_NONE,
1366                               1, EMPATHY_TYPE_MESSAGE);
1367
1368         signals[SEND_ERROR] =
1369                 g_signal_new ("send-error",
1370                               G_TYPE_FROM_CLASS (klass),
1371                               G_SIGNAL_RUN_LAST,
1372                               0,
1373                               NULL, NULL,
1374                               _empathy_marshal_VOID__STRING_UINT,
1375                               G_TYPE_NONE,
1376                               2, G_TYPE_STRING, G_TYPE_UINT);
1377
1378         signals[CHAT_STATE_CHANGED] =
1379                 g_signal_new ("chat-state-changed",
1380                               G_TYPE_FROM_CLASS (klass),
1381                               G_SIGNAL_RUN_LAST,
1382                               0,
1383                               NULL, NULL,
1384                               _empathy_marshal_VOID__OBJECT_UINT,
1385                               G_TYPE_NONE,
1386                               2, EMPATHY_TYPE_CONTACT, G_TYPE_UINT);
1387
1388         signals[PROPERTY_CHANGED] =
1389                 g_signal_new ("property-changed",
1390                               G_TYPE_FROM_CLASS (klass),
1391                               G_SIGNAL_RUN_LAST,
1392                               0,
1393                               NULL, NULL,
1394                               _empathy_marshal_VOID__STRING_BOXED,
1395                               G_TYPE_NONE,
1396                               2, G_TYPE_STRING, G_TYPE_VALUE);
1397
1398         signals[DESTROY] =
1399                 g_signal_new ("destroy",
1400                               G_TYPE_FROM_CLASS (klass),
1401                               G_SIGNAL_RUN_LAST,
1402                               0,
1403                               NULL, NULL,
1404                               g_cclosure_marshal_VOID__VOID,
1405                               G_TYPE_NONE,
1406                               0);
1407
1408         g_type_class_add_private (object_class, sizeof (EmpathyTpChatPriv));
1409 }
1410
1411 static void
1412 empathy_tp_chat_init (EmpathyTpChat *chat)
1413 {
1414         EmpathyTpChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
1415                 EMPATHY_TYPE_TP_CHAT, EmpathyTpChatPriv);
1416
1417         chat->priv = priv;
1418         priv->contact_monitor = NULL;
1419         priv->messages_queue = g_queue_new ();
1420         priv->pending_messages_queue = g_queue_new ();
1421 }
1422
1423 static void
1424 tp_chat_iface_init (EmpathyContactListIface *iface)
1425 {
1426         iface->add         = tp_chat_add;
1427         iface->remove      = tp_chat_remove;
1428         iface->get_members = tp_chat_get_members;
1429         iface->get_monitor = tp_chat_get_monitor;
1430 }
1431
1432 EmpathyTpChat *
1433 empathy_tp_chat_new (TpChannel *channel)
1434 {
1435         return g_object_new (EMPATHY_TYPE_TP_CHAT,
1436                              "channel", channel,
1437                              NULL);
1438 }
1439
1440 void
1441 empathy_tp_chat_close (EmpathyTpChat *chat) {
1442         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1443
1444         /* If there are still messages left, it'll come back..
1445          * We loose the ordering of sent messages though */
1446         tp_cli_channel_call_close (priv->channel, -1, tp_chat_async_cb,
1447                 "closing channel", NULL, NULL);
1448 }
1449
1450 const gchar *
1451 empathy_tp_chat_get_id (EmpathyTpChat *chat)
1452 {
1453         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1454         const gchar *id;
1455
1456
1457         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1458
1459         id = tp_channel_get_identifier (priv->channel);
1460         if (!EMP_STR_EMPTY (id))
1461                 return id;
1462         else if (priv->remote_contact)
1463                 return empathy_contact_get_id (priv->remote_contact);
1464         else
1465                 return NULL;
1466
1467 }
1468
1469 EmpathyContact *
1470 empathy_tp_chat_get_remote_contact (EmpathyTpChat *chat)
1471 {
1472         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1473
1474         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1475         g_return_val_if_fail (priv->ready, NULL);
1476
1477         return priv->remote_contact;
1478 }
1479
1480 TpChannel *
1481 empathy_tp_chat_get_channel (EmpathyTpChat *chat)
1482 {
1483         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1484
1485         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1486
1487         return priv->channel;
1488 }
1489
1490 TpConnection *
1491 empathy_tp_chat_get_connection (EmpathyTpChat *chat)
1492 {
1493         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1494
1495         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1496
1497         return tp_channel_borrow_connection (priv->channel);
1498 }
1499
1500 gboolean
1501 empathy_tp_chat_is_ready (EmpathyTpChat *chat)
1502 {
1503         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1504
1505         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), FALSE);
1506
1507         return priv->ready;
1508 }
1509
1510 void
1511 empathy_tp_chat_send (EmpathyTpChat *chat,
1512                       EmpathyMessage *message)
1513 {
1514         EmpathyTpChatPriv        *priv = GET_PRIV (chat);
1515         const gchar              *message_body;
1516         TpChannelTextMessageType  message_type;
1517
1518         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1519         g_return_if_fail (EMPATHY_IS_MESSAGE (message));
1520         g_return_if_fail (priv->ready);
1521
1522         message_body = empathy_message_get_body (message);
1523         message_type = empathy_message_get_tptype (message);
1524
1525         DEBUG ("Sending message: %s", message_body);
1526         tp_cli_channel_type_text_call_send (priv->channel, -1,
1527                                             message_type,
1528                                             message_body,
1529                                             tp_chat_send_cb,
1530                                             g_object_ref (message),
1531                                             (GDestroyNotify) g_object_unref,
1532                                             G_OBJECT (chat));
1533 }
1534
1535 void
1536 empathy_tp_chat_set_state (EmpathyTpChat      *chat,
1537                            TpChannelChatState  state)
1538 {
1539         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1540
1541         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1542         g_return_if_fail (priv->ready);
1543
1544         if (tp_proxy_has_interface_by_id (priv->channel,
1545                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_CHAT_STATE)) {
1546                 DEBUG ("Set state: %d", state);
1547                 tp_cli_channel_interface_chat_state_call_set_chat_state (priv->channel, -1,
1548                                                                          state,
1549                                                                          tp_chat_async_cb,
1550                                                                          "setting chat state",
1551                                                                          NULL,
1552                                                                          G_OBJECT (chat));
1553         }
1554 }
1555
1556
1557 const GList *
1558 empathy_tp_chat_get_pending_messages (EmpathyTpChat *chat)
1559 {
1560         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1561
1562         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1563         g_return_val_if_fail (priv->ready, NULL);
1564
1565         return priv->pending_messages_queue->head;
1566 }
1567
1568 static void
1569 acknowledge_messages (EmpathyTpChat *chat, GArray *ids) {
1570         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1571
1572         tp_cli_channel_type_text_call_acknowledge_pending_messages (
1573                 priv->channel, -1, ids, tp_chat_async_cb,
1574                 "acknowledging received message", NULL, G_OBJECT (chat));
1575 }
1576
1577 void
1578 empathy_tp_chat_acknowledge_message (EmpathyTpChat *chat,
1579                                      EmpathyMessage *message) {
1580         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1581         GArray *message_ids;
1582         GList *m;
1583         guint id;
1584
1585         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1586         g_return_if_fail (priv->ready);
1587
1588         if (!empathy_message_is_incoming (message))
1589                 goto out;
1590
1591         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
1592
1593         id = empathy_message_get_id (message);
1594         g_array_append_val (message_ids, id);
1595         acknowledge_messages (chat, message_ids);
1596         g_array_free (message_ids, TRUE);
1597
1598 out:
1599         m = g_queue_find (priv->pending_messages_queue, message);
1600         g_assert (m != NULL);
1601         g_queue_delete_link (priv->pending_messages_queue, m);
1602         g_object_unref (message);
1603 }
1604
1605 void
1606 empathy_tp_chat_acknowledge_messages (EmpathyTpChat *chat,
1607                                       const GList *messages) {
1608         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1609         /* Copy messages as the messges list (probably is) our own */
1610         GList *msgs = g_list_copy ((GList *) messages);
1611         GList *l;
1612         guint length;
1613         GArray *message_ids;
1614
1615         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1616         g_return_if_fail (priv->ready);
1617
1618         length = g_list_length ((GList *) messages);
1619
1620         if (length == 0)
1621                 return;
1622
1623         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), length);
1624
1625         for (l = msgs; l != NULL; l = g_list_next (l)) {
1626                 GList *m;
1627
1628                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1629
1630                 m = g_queue_find (priv->pending_messages_queue, message);
1631                 g_assert (m != NULL);
1632                 g_queue_delete_link (priv->pending_messages_queue, m);
1633
1634                 if (empathy_message_is_incoming (message)) {
1635                         guint id = empathy_message_get_id (message);
1636                         g_array_append_val (message_ids, id);
1637                 }
1638                 g_object_unref (message);
1639         }
1640
1641         if (message_ids->len > 0)
1642                 acknowledge_messages (chat, message_ids);
1643
1644         g_array_free (message_ids, TRUE);
1645         g_list_free (msgs);
1646 }
1647
1648 gboolean
1649 empathy_tp_chat_password_needed (EmpathyTpChat *self)
1650 {
1651         EmpathyTpChatPriv *priv = GET_PRIV (self);
1652
1653         return priv->password_flags & TP_CHANNEL_PASSWORD_FLAG_PROVIDE;
1654 }
1655
1656 static void
1657 provide_password_cb (TpChannel *channel,
1658                                       gboolean correct,
1659                                       const GError *error,
1660                                       gpointer user_data,
1661                                       GObject *weak_object)
1662 {
1663         GSimpleAsyncResult *result = user_data;
1664
1665         if (error != NULL) {
1666                 g_simple_async_result_set_from_error (result, error);
1667         }
1668         else if (!correct) {
1669                 /* The current D-Bus API is a bit weird so re-use the
1670                  * AuthenticationFailed error */
1671                 g_simple_async_result_set_error (result, TP_ERRORS,
1672                                                  TP_ERROR_AUTHENTICATION_FAILED, "Wrong password");
1673         }
1674
1675         g_simple_async_result_complete (result);
1676         g_object_unref (result);
1677 }
1678
1679 void
1680 empathy_tp_chat_provide_password_async (EmpathyTpChat *self,
1681                                                      const gchar *password,
1682                                                      GAsyncReadyCallback callback,
1683                                                      gpointer user_data)
1684 {
1685         EmpathyTpChatPriv *priv = GET_PRIV (self);
1686         GSimpleAsyncResult *result;
1687
1688         result = g_simple_async_result_new (G_OBJECT (self),
1689                                             callback, user_data,
1690                                             empathy_tp_chat_provide_password_finish);
1691
1692         tp_cli_channel_interface_password_call_provide_password
1693                 (priv->channel, -1, password, provide_password_cb, result,
1694                  NULL, G_OBJECT (self));
1695 }
1696
1697 gboolean
1698 empathy_tp_chat_provide_password_finish (EmpathyTpChat *self,
1699                                                       GAsyncResult *result,
1700                                                       GError **error)
1701 {
1702         if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result),
1703                 error))
1704                 return FALSE;
1705
1706         g_return_val_if_fail (g_simple_async_result_is_valid (result,
1707                                                               G_OBJECT (self), empathy_tp_chat_provide_password_finish), FALSE);
1708
1709         return TRUE;
1710 }