]> git.0d.be Git - empathy.git/blob - libempathy/empathy-tp-chat.c
Respect indentation style.
[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         tp_cli_channel_interface_chat_state_connect_to_chat_state_changed (priv->channel,
827                                                                            tp_chat_state_changed_cb,
828                                                                            NULL, NULL,
829                                                                            G_OBJECT (chat), NULL);
830         priv->ready = TRUE;
831         g_object_notify (G_OBJECT (chat), "ready");
832 }
833
834 static void
835 tp_chat_update_remote_contact (EmpathyTpChat *chat)
836 {
837         EmpathyTpChatPriv *priv = GET_PRIV (chat);
838         EmpathyContact *contact = NULL;
839         TpHandle self_handle;
840         TpHandleType handle_type;
841         GList *l;
842
843         /* If this is a named chatroom, never pretend it is a private chat */
844         tp_channel_get_handle (priv->channel, &handle_type);
845         if (handle_type == TP_HANDLE_TYPE_ROOM) {
846                 return;
847         }
848
849         /* This is an MSN-like chat where anyone can join the chat at anytime.
850          * If there is only one non-self contact member, we are in a private
851          * chat and we set the "remote-contact" property to that contact. If
852          * there are more, set the "remote-contact" property to NULL and the
853          * UI will display a contact list. */
854         self_handle = tp_channel_group_get_self_handle (priv->channel);
855         for (l = priv->members; l; l = l->next) {
856                 /* Skip self contact if member */
857                 if (empathy_contact_get_handle (l->data) == self_handle) {
858                         continue;
859                 }
860
861                 /* We have more than one remote contact, break */
862                 if (contact != NULL) {
863                         contact = NULL;
864                         break;
865                 }
866
867                 /* If we didn't find yet a remote contact, keep this one */
868                 contact = l->data;
869         }
870
871         if (priv->remote_contact == contact) {
872                 return;
873         }
874
875         DEBUG ("Changing remote contact from %p to %p",
876                 priv->remote_contact, contact);
877
878         if (priv->remote_contact) {
879                 g_object_unref (priv->remote_contact);
880         }
881
882         priv->remote_contact = contact ? g_object_ref (contact) : NULL;
883         g_object_notify (G_OBJECT (chat), "remote-contact");
884 }
885
886 static void
887 tp_chat_got_added_contacts_cb (EmpathyTpContactFactory *factory,
888                                guint                    n_contacts,
889                                EmpathyContact * const * contacts,
890                                guint                    n_failed,
891                                const TpHandle          *failed,
892                                const GError            *error,
893                                gpointer                 user_data,
894                                GObject                 *chat)
895 {
896         EmpathyTpChatPriv *priv = GET_PRIV (chat);
897         guint i;
898         const TpIntSet *members;
899         TpHandle handle;
900         EmpathyContact *contact;
901
902         if (error) {
903                 DEBUG ("Error: %s", error->message);
904                 return;
905         }
906
907         members = tp_channel_group_get_members (priv->channel);
908         for (i = 0; i < n_contacts; i++) {
909                 contact = contacts[i];
910                 handle = empathy_contact_get_handle (contact);
911
912                 /* Make sure the contact is still member */
913                 if (tp_intset_is_member (members, handle)) {
914                         priv->members = g_list_prepend (priv->members,
915                                 g_object_ref (contact));
916                         g_signal_emit_by_name (chat, "members-changed",
917                                                contact, NULL, 0, NULL, TRUE);
918                 }
919         }
920
921         tp_chat_update_remote_contact (EMPATHY_TP_CHAT (chat));
922         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
923 }
924
925 static EmpathyContact *
926 chat_lookup_contact (EmpathyTpChat *chat,
927                      TpHandle       handle,
928                      gboolean       remove_)
929 {
930         EmpathyTpChatPriv *priv = GET_PRIV (chat);
931         GList *l;
932
933         for (l = priv->members; l; l = l->next) {
934                 EmpathyContact *c = l->data;
935
936                 if (empathy_contact_get_handle (c) != handle) {
937                         continue;
938                 }
939
940                 if (remove_) {
941                         /* Caller takes the reference. */
942                         priv->members = g_list_delete_link (priv->members, l);
943                 } else {
944                         g_object_ref (c);
945                 }
946
947                 return c;
948         }
949
950         return NULL;
951 }
952
953 static void
954 tp_chat_group_members_changed_cb (TpChannel     *self,
955                                   gchar         *message,
956                                   GArray        *added,
957                                   GArray        *removed,
958                                   GArray        *local_pending,
959                                   GArray        *remote_pending,
960                                   guint          actor,
961                                   guint          reason,
962                                   EmpathyTpChat *chat)
963 {
964         EmpathyTpChatPriv *priv = GET_PRIV (chat);
965         EmpathyContact *contact;
966         EmpathyContact *actor_contact = NULL;
967         guint i;
968
969         if (actor != 0) {
970                 actor_contact = chat_lookup_contact (chat, actor, FALSE);
971                 if (actor_contact == NULL) {
972                         /* FIXME: handle this a tad more gracefully: perhaps
973                          * the actor was a server op. We could use the
974                          * contact-ids detail of MembersChangedDetailed.
975                          */
976                         DEBUG ("actor %u not a channel member", actor);
977                 }
978         }
979
980         /* Remove contacts that are not members anymore */
981         for (i = 0; i < removed->len; i++) {
982                 contact = chat_lookup_contact (chat,
983                         g_array_index (removed, TpHandle, i), TRUE);
984
985                 if (contact != NULL) {
986                         g_signal_emit_by_name (chat, "members-changed", contact,
987                                                actor_contact, reason, message,
988                                                FALSE);
989                         g_object_unref (contact);
990                 }
991         }
992
993         /* Request added contacts */
994         if (added->len > 0) {
995                 empathy_tp_contact_factory_get_from_handles (priv->factory,
996                         added->len, (TpHandle *) added->data,
997                         tp_chat_got_added_contacts_cb, NULL, NULL,
998                         G_OBJECT (chat));
999         }
1000
1001         tp_chat_update_remote_contact (chat);
1002
1003         if (actor_contact != NULL) {
1004                 g_object_unref (actor_contact);
1005         }
1006 }
1007
1008 static void
1009 tp_chat_got_remote_contact_cb (EmpathyTpContactFactory *factory,
1010                                EmpathyContact          *contact,
1011                                const GError            *error,
1012                                gpointer                 user_data,
1013                                GObject                 *chat)
1014 {
1015         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1016
1017         if (error) {
1018                 DEBUG ("Error: %s", error->message);
1019                 empathy_tp_chat_close (EMPATHY_TP_CHAT (chat));
1020                 return;
1021         }
1022
1023         priv->remote_contact = g_object_ref (contact);
1024         g_object_notify (chat, "remote-contact");
1025
1026         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
1027 }
1028
1029 static void
1030 tp_chat_got_self_contact_cb (EmpathyTpContactFactory *factory,
1031                              EmpathyContact          *contact,
1032                              const GError            *error,
1033                              gpointer                 user_data,
1034                              GObject                 *chat)
1035 {
1036         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1037
1038         if (error) {
1039                 DEBUG ("Error: %s", error->message);
1040                 empathy_tp_chat_close (EMPATHY_TP_CHAT (chat));
1041                 return;
1042         }
1043
1044         priv->user = g_object_ref (contact);
1045         empathy_contact_set_is_user (priv->user, TRUE);
1046         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
1047 }
1048
1049 static void
1050 password_flags_changed_cb (TpChannel *channel,
1051     guint added,
1052     guint removed,
1053     gpointer user_data,
1054     GObject *weak_object)
1055 {
1056         EmpathyTpChat *self = EMPATHY_TP_CHAT (weak_object);
1057         EmpathyTpChatPriv *priv = GET_PRIV (self);
1058         gboolean was_needed, needed;
1059
1060         was_needed = empathy_tp_chat_password_needed (self);
1061
1062         priv->password_flags |= added;
1063         priv->password_flags ^= removed;
1064
1065         needed = empathy_tp_chat_password_needed (self);
1066
1067         if (was_needed != needed)
1068                 g_object_notify (G_OBJECT (self), "password-needed");
1069 }
1070
1071 static void
1072 got_password_flags_cb (TpChannel *proxy,
1073                              guint password_flags,
1074                              const GError *error,
1075                              gpointer user_data,
1076                              GObject *weak_object)
1077 {
1078         EmpathyTpChat *self = EMPATHY_TP_CHAT (weak_object);
1079         EmpathyTpChatPriv *priv = GET_PRIV (self);
1080
1081         priv->got_password_flags = TRUE;
1082         priv->password_flags = password_flags;
1083
1084         tp_chat_check_if_ready (EMPATHY_TP_CHAT (self));
1085 }
1086
1087 static GObject *
1088 tp_chat_constructor (GType                  type,
1089                      guint                  n_props,
1090                      GObjectConstructParam *props)
1091 {
1092         GObject           *chat;
1093         EmpathyTpChatPriv *priv;
1094         TpConnection      *connection;
1095         TpHandle           handle;
1096
1097         chat = G_OBJECT_CLASS (empathy_tp_chat_parent_class)->constructor (type, n_props, props);
1098
1099         priv = GET_PRIV (chat);
1100
1101         connection = tp_channel_borrow_connection (priv->channel);
1102         priv->factory = empathy_tp_contact_factory_dup_singleton (connection);
1103         g_signal_connect (priv->channel, "invalidated",
1104                           G_CALLBACK (tp_chat_invalidated_cb),
1105                           chat);
1106
1107         if (tp_proxy_has_interface_by_id (priv->channel,
1108                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
1109                 const TpIntSet *members;
1110                 GArray *handles;
1111
1112                 /* Get self contact from the group's self handle */
1113                 handle = tp_channel_group_get_self_handle (priv->channel);
1114                 empathy_tp_contact_factory_get_from_handle (priv->factory,
1115                         handle, tp_chat_got_self_contact_cb,
1116                         NULL, NULL, chat);
1117
1118                 /* Get initial member contacts */
1119                 members = tp_channel_group_get_members (priv->channel);
1120                 handles = tp_intset_to_array (members);
1121                 empathy_tp_contact_factory_get_from_handles (priv->factory,
1122                         handles->len, (TpHandle *) handles->data,
1123                         tp_chat_got_added_contacts_cb, NULL, NULL, chat);
1124
1125                 g_signal_connect (priv->channel, "group-members-changed",
1126                         G_CALLBACK (tp_chat_group_members_changed_cb), chat);
1127         } else {
1128                 /* Get the self contact from the connection's self handle */
1129                 handle = tp_connection_get_self_handle (connection);
1130                 empathy_tp_contact_factory_get_from_handle (priv->factory,
1131                         handle, tp_chat_got_self_contact_cb,
1132                         NULL, NULL, chat);
1133
1134                 /* Get the remote contact */
1135                 handle = tp_channel_get_handle (priv->channel, NULL);
1136                 empathy_tp_contact_factory_get_from_handle (priv->factory,
1137                         handle, tp_chat_got_remote_contact_cb,
1138                         NULL, NULL, chat);
1139         }
1140
1141         if (tp_proxy_has_interface_by_id (priv->channel,
1142                                           TP_IFACE_QUARK_PROPERTIES_INTERFACE)) {
1143                 tp_cli_properties_interface_call_list_properties (priv->channel, -1,
1144                                                                   tp_chat_list_properties_cb,
1145                                                                   NULL, NULL,
1146                                                                   G_OBJECT (chat));
1147                 tp_cli_properties_interface_connect_to_properties_changed (priv->channel,
1148                                                                            tp_chat_properties_changed_cb,
1149                                                                            NULL, NULL,
1150                                                                            G_OBJECT (chat), NULL);
1151                 tp_cli_properties_interface_connect_to_property_flags_changed (priv->channel,
1152                                                                                tp_chat_property_flags_changed_cb,
1153                                                                                NULL, NULL,
1154                                                                                G_OBJECT (chat), NULL);
1155         }
1156
1157         /* Check if the chat is password protected */
1158         if (tp_proxy_has_interface_by_id (priv->channel,
1159                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_PASSWORD)) {
1160                 priv->got_password_flags = FALSE;
1161
1162                 tp_cli_channel_interface_password_connect_to_password_flags_changed
1163                         (priv->channel, password_flags_changed_cb, chat, NULL,
1164                          G_OBJECT (chat), NULL);
1165
1166                 tp_cli_channel_interface_password_call_get_password_flags
1167                         (priv->channel, -1, got_password_flags_cb, chat, NULL, chat);
1168         } else {
1169                 /* No Password interface, so no need to fetch the password flags */
1170                 priv->got_password_flags = TRUE;
1171         }
1172
1173         return chat;
1174 }
1175
1176 static void
1177 tp_chat_get_property (GObject    *object,
1178                       guint       param_id,
1179                       GValue     *value,
1180                       GParamSpec *pspec)
1181 {
1182         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
1183         EmpathyTpChatPriv *priv = GET_PRIV (object);
1184
1185         switch (param_id) {
1186         case PROP_CHANNEL:
1187                 g_value_set_object (value, priv->channel);
1188                 break;
1189         case PROP_REMOTE_CONTACT:
1190                 g_value_set_object (value, priv->remote_contact);
1191                 break;
1192         case PROP_READY:
1193                 g_value_set_boolean (value, priv->ready);
1194                 break;
1195         case PROP_PASSWORD_NEEDED:
1196                 g_value_set_boolean (value, empathy_tp_chat_password_needed (self));
1197                 break;
1198         default:
1199                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1200                 break;
1201         };
1202 }
1203
1204 static void
1205 tp_chat_set_property (GObject      *object,
1206                       guint         param_id,
1207                       const GValue *value,
1208                       GParamSpec   *pspec)
1209 {
1210         EmpathyTpChatPriv *priv = GET_PRIV (object);
1211
1212         switch (param_id) {
1213         case PROP_CHANNEL:
1214                 priv->channel = g_value_dup_object (value);
1215                 break;
1216         default:
1217                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1218                 break;
1219         };
1220 }
1221
1222 static void
1223 empathy_tp_chat_class_init (EmpathyTpChatClass *klass)
1224 {
1225         GObjectClass *object_class = G_OBJECT_CLASS (klass);
1226
1227         object_class->dispose = tp_chat_dispose;
1228         object_class->finalize = tp_chat_finalize;
1229         object_class->constructor = tp_chat_constructor;
1230         object_class->get_property = tp_chat_get_property;
1231         object_class->set_property = tp_chat_set_property;
1232
1233         g_object_class_install_property (object_class,
1234                                          PROP_CHANNEL,
1235                                          g_param_spec_object ("channel",
1236                                                               "telepathy channel",
1237                                                               "The text channel for the chat",
1238                                                               TP_TYPE_CHANNEL,
1239                                                               G_PARAM_READWRITE |
1240                                                               G_PARAM_CONSTRUCT_ONLY));
1241
1242         g_object_class_install_property (object_class,
1243                                          PROP_REMOTE_CONTACT,
1244                                          g_param_spec_object ("remote-contact",
1245                                                               "The remote contact",
1246                                                               "The remote contact if there is no group iface on the channel",
1247                                                               EMPATHY_TYPE_CONTACT,
1248                                                               G_PARAM_READABLE));
1249
1250         g_object_class_install_property (object_class,
1251                                          PROP_READY,
1252                                          g_param_spec_boolean ("ready",
1253                                                                "Is the object ready",
1254                                                                "This object can't be used until this becomes true",
1255                                                                FALSE,
1256                                                                G_PARAM_READABLE));
1257
1258         g_object_class_install_property (object_class,
1259                                          PROP_PASSWORD_NEEDED,
1260                                          g_param_spec_boolean ("password-needed",
1261                                                                "password needed",
1262                                                                "TRUE if a password is needed to join the channel",
1263                                                                FALSE,
1264                                                                G_PARAM_READABLE));
1265
1266         /* Signals */
1267         signals[MESSAGE_RECEIVED] =
1268                 g_signal_new ("message-received",
1269                               G_TYPE_FROM_CLASS (klass),
1270                               G_SIGNAL_RUN_LAST,
1271                               0,
1272                               NULL, NULL,
1273                               g_cclosure_marshal_VOID__OBJECT,
1274                               G_TYPE_NONE,
1275                               1, EMPATHY_TYPE_MESSAGE);
1276
1277         signals[SEND_ERROR] =
1278                 g_signal_new ("send-error",
1279                               G_TYPE_FROM_CLASS (klass),
1280                               G_SIGNAL_RUN_LAST,
1281                               0,
1282                               NULL, NULL,
1283                               _empathy_marshal_VOID__STRING_UINT,
1284                               G_TYPE_NONE,
1285                               2, G_TYPE_STRING, G_TYPE_UINT);
1286
1287         signals[CHAT_STATE_CHANGED] =
1288                 g_signal_new ("chat-state-changed",
1289                               G_TYPE_FROM_CLASS (klass),
1290                               G_SIGNAL_RUN_LAST,
1291                               0,
1292                               NULL, NULL,
1293                               _empathy_marshal_VOID__OBJECT_UINT,
1294                               G_TYPE_NONE,
1295                               2, EMPATHY_TYPE_CONTACT, G_TYPE_UINT);
1296
1297         signals[PROPERTY_CHANGED] =
1298                 g_signal_new ("property-changed",
1299                               G_TYPE_FROM_CLASS (klass),
1300                               G_SIGNAL_RUN_LAST,
1301                               0,
1302                               NULL, NULL,
1303                               _empathy_marshal_VOID__STRING_BOXED,
1304                               G_TYPE_NONE,
1305                               2, G_TYPE_STRING, G_TYPE_VALUE);
1306
1307         signals[DESTROY] =
1308                 g_signal_new ("destroy",
1309                               G_TYPE_FROM_CLASS (klass),
1310                               G_SIGNAL_RUN_LAST,
1311                               0,
1312                               NULL, NULL,
1313                               g_cclosure_marshal_VOID__VOID,
1314                               G_TYPE_NONE,
1315                               0);
1316
1317         g_type_class_add_private (object_class, sizeof (EmpathyTpChatPriv));
1318 }
1319
1320 static void
1321 empathy_tp_chat_init (EmpathyTpChat *chat)
1322 {
1323         EmpathyTpChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
1324                 EMPATHY_TYPE_TP_CHAT, EmpathyTpChatPriv);
1325
1326         chat->priv = priv;
1327         priv->contact_monitor = NULL;
1328         priv->messages_queue = g_queue_new ();
1329         priv->pending_messages_queue = g_queue_new ();
1330 }
1331
1332 static void
1333 tp_chat_iface_init (EmpathyContactListIface *iface)
1334 {
1335         iface->add         = tp_chat_add;
1336         iface->remove      = tp_chat_remove;
1337         iface->get_members = tp_chat_get_members;
1338         iface->get_monitor = tp_chat_get_monitor;
1339 }
1340
1341 EmpathyTpChat *
1342 empathy_tp_chat_new (TpChannel *channel)
1343 {
1344         return g_object_new (EMPATHY_TYPE_TP_CHAT,
1345                              "channel", channel,
1346                              NULL);
1347 }
1348
1349 void
1350 empathy_tp_chat_close (EmpathyTpChat *chat) {
1351         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1352
1353         /* If there are still messages left, it'll come back..
1354          * We loose the ordering of sent messages though */
1355         tp_cli_channel_call_close (priv->channel, -1, tp_chat_async_cb,
1356                 "closing channel", NULL, NULL);
1357 }
1358
1359 const gchar *
1360 empathy_tp_chat_get_id (EmpathyTpChat *chat)
1361 {
1362         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1363         const gchar *id;
1364
1365
1366         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1367
1368         id = tp_channel_get_identifier (priv->channel);
1369         if (!EMP_STR_EMPTY (id))
1370                 return id;
1371         else if (priv->remote_contact)
1372                 return empathy_contact_get_id (priv->remote_contact);
1373         else
1374                 return NULL;
1375
1376 }
1377
1378 EmpathyContact *
1379 empathy_tp_chat_get_remote_contact (EmpathyTpChat *chat)
1380 {
1381         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1382
1383         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1384         g_return_val_if_fail (priv->ready, NULL);
1385
1386         return priv->remote_contact;
1387 }
1388
1389 TpChannel *
1390 empathy_tp_chat_get_channel (EmpathyTpChat *chat)
1391 {
1392         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1393
1394         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1395
1396         return priv->channel;
1397 }
1398
1399 TpConnection *
1400 empathy_tp_chat_get_connection (EmpathyTpChat *chat)
1401 {
1402         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1403
1404         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1405
1406         return tp_channel_borrow_connection (priv->channel);
1407 }
1408
1409 gboolean
1410 empathy_tp_chat_is_ready (EmpathyTpChat *chat)
1411 {
1412         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1413
1414         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), FALSE);
1415
1416         return priv->ready;
1417 }
1418
1419 void
1420 empathy_tp_chat_send (EmpathyTpChat *chat,
1421                       EmpathyMessage *message)
1422 {
1423         EmpathyTpChatPriv        *priv = GET_PRIV (chat);
1424         const gchar              *message_body;
1425         TpChannelTextMessageType  message_type;
1426
1427         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1428         g_return_if_fail (EMPATHY_IS_MESSAGE (message));
1429         g_return_if_fail (priv->ready);
1430
1431         message_body = empathy_message_get_body (message);
1432         message_type = empathy_message_get_tptype (message);
1433
1434         DEBUG ("Sending message: %s", message_body);
1435         tp_cli_channel_type_text_call_send (priv->channel, -1,
1436                                             message_type,
1437                                             message_body,
1438                                             tp_chat_send_cb,
1439                                             g_object_ref (message),
1440                                             (GDestroyNotify) g_object_unref,
1441                                             G_OBJECT (chat));
1442 }
1443
1444 void
1445 empathy_tp_chat_set_state (EmpathyTpChat      *chat,
1446                            TpChannelChatState  state)
1447 {
1448         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1449
1450         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1451         g_return_if_fail (priv->ready);
1452
1453         if (tp_proxy_has_interface_by_id (priv->channel,
1454                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_CHAT_STATE)) {
1455                 DEBUG ("Set state: %d", state);
1456                 tp_cli_channel_interface_chat_state_call_set_chat_state (priv->channel, -1,
1457                                                                          state,
1458                                                                          tp_chat_async_cb,
1459                                                                          "setting chat state",
1460                                                                          NULL,
1461                                                                          G_OBJECT (chat));
1462         }
1463 }
1464
1465
1466 const GList *
1467 empathy_tp_chat_get_pending_messages (EmpathyTpChat *chat)
1468 {
1469         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1470
1471         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1472         g_return_val_if_fail (priv->ready, NULL);
1473
1474         return priv->pending_messages_queue->head;
1475 }
1476
1477 static void
1478 acknowledge_messages (EmpathyTpChat *chat, GArray *ids) {
1479         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1480
1481         tp_cli_channel_type_text_call_acknowledge_pending_messages (
1482                 priv->channel, -1, ids, tp_chat_async_cb,
1483                 "acknowledging received message", NULL, G_OBJECT (chat));
1484 }
1485
1486 void
1487 empathy_tp_chat_acknowledge_message (EmpathyTpChat *chat,
1488                                      EmpathyMessage *message) {
1489         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1490         GArray *message_ids;
1491         GList *m;
1492         guint id;
1493
1494         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1495         g_return_if_fail (priv->ready);
1496
1497         if (!empathy_message_is_incoming (message))
1498                 goto out;
1499
1500         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
1501
1502         id = empathy_message_get_id (message);
1503         g_array_append_val (message_ids, id);
1504         acknowledge_messages (chat, message_ids);
1505         g_array_free (message_ids, TRUE);
1506
1507 out:
1508         m = g_queue_find (priv->pending_messages_queue, message);
1509         g_assert (m != NULL);
1510         g_queue_delete_link (priv->pending_messages_queue, m);
1511         g_object_unref (message);
1512 }
1513
1514 void
1515 empathy_tp_chat_acknowledge_messages (EmpathyTpChat *chat,
1516                                       const GList *messages) {
1517         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1518         /* Copy messages as the messges list (probably is) our own */
1519         GList *msgs = g_list_copy ((GList *) messages);
1520         GList *l;
1521         guint length;
1522         GArray *message_ids;
1523
1524         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1525         g_return_if_fail (priv->ready);
1526
1527         length = g_list_length ((GList *) messages);
1528
1529         if (length == 0)
1530                 return;
1531
1532         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), length);
1533
1534         for (l = msgs; l != NULL; l = g_list_next (l)) {
1535                 GList *m;
1536
1537                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1538
1539                 m = g_queue_find (priv->pending_messages_queue, message);
1540                 g_assert (m != NULL);
1541                 g_queue_delete_link (priv->pending_messages_queue, m);
1542
1543                 if (empathy_message_is_incoming (message)) {
1544                         guint id = empathy_message_get_id (message);
1545                         g_array_append_val (message_ids, id);
1546                 }
1547                 g_object_unref (message);
1548         }
1549
1550         if (message_ids->len > 0)
1551                 acknowledge_messages (chat, message_ids);
1552
1553         g_array_free (message_ids, TRUE);
1554         g_list_free (msgs);
1555 }
1556
1557 gboolean
1558 empathy_tp_chat_password_needed (EmpathyTpChat *self)
1559 {
1560         EmpathyTpChatPriv *priv = GET_PRIV (self);
1561
1562         return priv->password_flags & TP_CHANNEL_PASSWORD_FLAG_PROVIDE;
1563 }
1564
1565 static void
1566 provide_password_cb (TpChannel *channel,
1567                                       gboolean correct,
1568                                       const GError *error,
1569                                       gpointer user_data,
1570                                       GObject *weak_object)
1571 {
1572         GSimpleAsyncResult *result = user_data;
1573
1574         if (error != NULL) {
1575                 g_simple_async_result_set_from_error (result, error);
1576         }
1577         else if (!correct) {
1578                 /* The current D-Bus API is a bit weird so re-use the
1579                  * AuthenticationFailed error */
1580                 g_simple_async_result_set_error (result, TP_ERRORS,
1581                                                  TP_ERROR_AUTHENTICATION_FAILED, "Wrong password");
1582         }
1583
1584         g_simple_async_result_complete (result);
1585         g_object_unref (result);
1586 }
1587
1588 void
1589 empathy_tp_chat_provide_password_async (EmpathyTpChat *self,
1590                                                      const gchar *password,
1591                                                      GAsyncReadyCallback callback,
1592                                                      gpointer user_data)
1593 {
1594         EmpathyTpChatPriv *priv = GET_PRIV (self);
1595         GSimpleAsyncResult *result;
1596
1597         result = g_simple_async_result_new (G_OBJECT (self),
1598                                             callback, user_data,
1599                                             empathy_tp_chat_provide_password_finish);
1600
1601         tp_cli_channel_interface_password_call_provide_password
1602                 (priv->channel, -1, password, provide_password_cb, result,
1603                  NULL, G_OBJECT (self));
1604 }
1605
1606 gboolean
1607 empathy_tp_chat_provide_password_finish (EmpathyTpChat *self,
1608                                                       GAsyncResult *result,
1609                                                       GError **error)
1610 {
1611         if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result),
1612                 error))
1613                 return FALSE;
1614
1615         g_return_val_if_fail (g_simple_async_result_is_valid (result,
1616                                                               G_OBJECT (self), empathy_tp_chat_provide_password_finish), FALSE);
1617
1618         return TRUE;
1619 }