]> git.0d.be Git - empathy.git/blob - libempathy/empathy-tp-chat.c
8bb6567dc184b290acb9aad18bd53aa98cc530f9
[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
30 #include "empathy-tp-chat.h"
31 #include "empathy-tp-contact-factory.h"
32 #include "empathy-contact-monitor.h"
33 #include "empathy-contact-list.h"
34 #include "empathy-marshal.h"
35 #include "empathy-time.h"
36 #include "empathy-utils.h"
37
38 #define DEBUG_FLAG EMPATHY_DEBUG_TP | EMPATHY_DEBUG_CHAT
39 #include "empathy-debug.h"
40
41 #define GET_PRIV(obj) EMPATHY_GET_PRIV (obj, EmpathyTpChat)
42 typedef struct {
43         gboolean               dispose_has_run;
44         EmpathyTpContactFactory *factory;
45         EmpathyContactMonitor *contact_monitor;
46         EmpathyContact        *user;
47         EmpathyContact        *remote_contact;
48         GList                 *members;
49         TpChannel             *channel;
50         gboolean               listing_pending_messages;
51         /* Queue of messages not signalled yet */
52         GQueue                *messages_queue;
53         /* Queue of messages signalled but not acked yet */
54         GQueue                *pending_messages_queue;
55         gboolean               had_properties_list;
56         GPtrArray             *properties;
57         gboolean               ready;
58 } EmpathyTpChatPriv;
59
60 typedef struct {
61         gchar          *name;
62         guint           id;
63         TpPropertyFlags flags;
64         GValue         *value;
65 } TpChatProperty;
66
67 static void tp_chat_iface_init         (EmpathyContactListIface *iface);
68
69 enum {
70         PROP_0,
71         PROP_CHANNEL,
72         PROP_REMOTE_CONTACT,
73         PROP_READY,
74 };
75
76 enum {
77         MESSAGE_RECEIVED,
78         SEND_ERROR,
79         CHAT_STATE_CHANGED,
80         PROPERTY_CHANGED,
81         DESTROY,
82         LAST_SIGNAL
83 };
84
85 static guint signals[LAST_SIGNAL];
86
87 G_DEFINE_TYPE_WITH_CODE (EmpathyTpChat, empathy_tp_chat, G_TYPE_OBJECT,
88                          G_IMPLEMENT_INTERFACE (EMPATHY_TYPE_CONTACT_LIST,
89                                                 tp_chat_iface_init));
90
91 static void acknowledge_messages (EmpathyTpChat *chat, GArray *ids);
92
93 static void
94 tp_chat_invalidated_cb (TpProxy       *proxy,
95                         guint          domain,
96                         gint           code,
97                         gchar         *message,
98                         EmpathyTpChat *chat)
99 {
100         EmpathyTpChatPriv *priv = GET_PRIV (chat);
101
102         DEBUG ("Channel invalidated: %s", message);
103         g_signal_emit (chat, signals[DESTROY], 0);
104 }
105
106 static void
107 tp_chat_async_cb (TpChannel *proxy,
108                   const GError *error,
109                   gpointer user_data,
110                   GObject *weak_object)
111 {
112         if (error) {
113                 DEBUG ("Error %s: %s", (gchar*) user_data, error->message);
114         }
115 }
116
117 static void
118 tp_chat_add (EmpathyContactList *list,
119              EmpathyContact     *contact,
120              const gchar        *message)
121 {
122         EmpathyTpChatPriv *priv = GET_PRIV (list);
123         TpHandle           handle;
124         GArray             handles = {(gchar *) &handle, 1};
125
126         g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
127         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
128
129         handle = empathy_contact_get_handle (contact);
130         tp_cli_channel_interface_group_call_add_members (priv->channel, -1,
131                                                          &handles, NULL,
132                                                          NULL, NULL, NULL,
133                                                          NULL);
134 }
135
136 static void
137 tp_chat_remove (EmpathyContactList *list,
138                 EmpathyContact     *contact,
139                 const gchar        *message)
140 {
141         EmpathyTpChatPriv *priv = GET_PRIV (list);
142         TpHandle           handle;
143         GArray             handles = {(gchar *) &handle, 1};
144
145         g_return_if_fail (EMPATHY_IS_TP_CHAT (list));
146         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
147
148         handle = empathy_contact_get_handle (contact);
149         tp_cli_channel_interface_group_call_remove_members (priv->channel, -1,
150                                                             &handles, NULL,
151                                                             NULL, NULL, NULL,
152                                                             NULL);
153 }
154
155 static GList *
156 tp_chat_get_members (EmpathyContactList *list)
157 {
158         EmpathyTpChatPriv *priv = GET_PRIV (list);
159         GList             *members = NULL;
160
161         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (list), NULL);
162
163         if (priv->members) {
164                 members = g_list_copy (priv->members);
165                 g_list_foreach (members, (GFunc) g_object_ref, NULL);
166         } else {
167                 members = g_list_prepend (members, g_object_ref (priv->user));
168                 members = g_list_prepend (members, g_object_ref (priv->remote_contact));
169         }
170
171         return members;
172 }
173
174 static EmpathyContactMonitor *
175 tp_chat_get_monitor (EmpathyContactList *list)
176 {
177         EmpathyTpChatPriv *priv;
178
179         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (list), NULL);
180
181         priv = GET_PRIV (list);
182
183         if (priv->contact_monitor == NULL) {
184                 priv->contact_monitor = empathy_contact_monitor_new_for_iface (list);
185         }
186
187         return priv->contact_monitor;
188 }
189
190 static void
191 tp_chat_emit_queued_messages (EmpathyTpChat *chat)
192 {
193         EmpathyTpChatPriv *priv = GET_PRIV (chat);
194         EmpathyMessage    *message;
195
196         /* Check if we can now emit some queued messages */
197         while ((message = g_queue_peek_head (priv->messages_queue)) != NULL) {
198                 if (empathy_message_get_sender (message) == NULL) {
199                         break;
200                 }
201
202                 DEBUG ("Queued message ready");
203                 g_queue_pop_head (priv->messages_queue);
204                 g_queue_push_tail (priv->pending_messages_queue, message);
205                 g_signal_emit (chat, signals[MESSAGE_RECEIVED], 0, message);
206         }
207 }
208
209 static void
210 tp_chat_got_sender_cb (EmpathyTpContactFactory *factory,
211                        GList                   *contacts,
212                        gpointer                 message,
213                        GObject                 *chat)
214 {
215         empathy_message_set_sender (message, contacts->data);
216         tp_chat_emit_queued_messages (EMPATHY_TP_CHAT (chat));
217 }
218
219 static void
220 tp_chat_build_message (EmpathyTpChat *chat,
221                        guint          id,
222                        guint          type,
223                        guint          timestamp,
224                        guint          from_handle,
225                        const gchar   *message_body)
226 {
227         EmpathyTpChatPriv *priv;
228         EmpathyMessage    *message;
229
230         priv = GET_PRIV (chat);
231
232         message = empathy_message_new (message_body);
233         empathy_message_set_tptype (message, type);
234         empathy_message_set_receiver (message, priv->user);
235         empathy_message_set_timestamp (message, timestamp);
236         empathy_message_set_id (message, id);
237         g_queue_push_tail (priv->messages_queue, message);
238
239         if (from_handle == 0) {
240                 empathy_message_set_sender (message, priv->user);
241                 tp_chat_emit_queued_messages (chat);
242         } else {
243                 empathy_tp_contact_factory_get_from_handles (priv->factory,
244                         1, &from_handle,
245                         tp_chat_got_sender_cb,
246                         message, NULL, G_OBJECT (chat));
247         }
248 }
249
250 static void
251 tp_chat_received_cb (TpChannel   *channel,
252                      guint        message_id,
253                      guint        timestamp,
254                      guint        from_handle,
255                      guint        message_type,
256                      guint        message_flags,
257                      const gchar *message_body,
258                      gpointer     user_data,
259                      GObject     *chat_)
260 {
261         EmpathyTpChat *chat = EMPATHY_TP_CHAT (chat_);
262         EmpathyTpChatPriv *priv = GET_PRIV (chat);
263
264         if (priv->channel == NULL)
265                 return;
266
267         if (priv->listing_pending_messages) {
268                 return;
269         }
270  
271         DEBUG ("Message received: %s", message_body);
272
273         if (message_flags & TP_CHANNEL_TEXT_MESSAGE_FLAG_NON_TEXT_CONTENT &&
274             !tp_strdiff (message_body, "")) {
275                 GArray *ids;
276
277                 DEBUG ("Empty message with NonTextContent, ignoring and acking.");
278
279                 ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
280                 g_array_append_val (ids, message_id);
281                 acknowledge_messages (chat, ids);
282                 g_array_free (ids, TRUE);
283
284                 return;
285         }
286
287         tp_chat_build_message (chat,
288                                message_id,
289                                message_type,
290                                timestamp,
291                                from_handle,
292                                message_body);
293 }
294
295 static void
296 tp_chat_sent_cb (TpChannel   *channel,
297                  guint        timestamp,
298                  guint        message_type,
299                  const gchar *message_body,
300                  gpointer     user_data,
301                  GObject     *chat_)
302 {
303         EmpathyTpChat *chat = EMPATHY_TP_CHAT (chat_);
304         EmpathyTpChatPriv *priv = GET_PRIV (chat);
305
306         if (priv->channel == NULL)
307                 return;
308
309         DEBUG ("Message sent: %s", message_body);
310
311         tp_chat_build_message (chat,
312                                0,
313                                message_type,
314                                timestamp,
315                                0,
316                                message_body);
317 }
318
319 static void
320 tp_chat_send_error_cb (TpChannel   *channel,
321                        guint        error_code,
322                        guint        timestamp,
323                        guint        message_type,
324                        const gchar *message_body,
325                        gpointer     user_data,
326                        GObject     *chat)
327 {
328         EmpathyTpChatPriv *priv = GET_PRIV (chat);
329
330         if (priv->channel == NULL)
331                 return;
332
333         DEBUG ("Message sent error: %s (%d)", message_body, error_code);
334
335         tp_chat_build_message (EMPATHY_TP_CHAT (chat),
336                                0,
337                                message_type,
338                                timestamp,
339                                0,
340                                message_body);
341 }
342
343 static void
344 tp_chat_send_cb (TpChannel    *proxy,
345                  const GError *error,
346                  gpointer      user_data,
347                  GObject      *chat)
348 {
349         EmpathyMessage *message = EMPATHY_MESSAGE (user_data);
350
351         if (error) {
352                 DEBUG ("Error: %s", error->message);
353                 g_signal_emit (chat, signals[SEND_ERROR], 0, message,
354                                TP_CHANNEL_TEXT_SEND_ERROR_UNKNOWN);
355         }
356 }
357
358 typedef struct {
359         EmpathyTpChat *chat;
360         TpChannelChatState state;
361 } StateChangedData;
362
363 static void
364 tp_chat_state_changed_got_contact_cb (EmpathyTpContactFactory *factory,
365                                       GList                   *contacts,
366                                       gpointer                 user_data,
367                                       GObject                 *chat)
368 {
369         EmpathyContact *contact = contacts->data;
370         TpChannelChatState state;
371
372         state = GPOINTER_TO_UINT (user_data);
373         DEBUG ("Chat state changed for %s (%d): %d",
374                 empathy_contact_get_name (contact),
375                 empathy_contact_get_handle (contact), state);
376
377         g_signal_emit (chat, signals[CHAT_STATE_CHANGED], 0, contact, state);
378 }
379
380 static void
381 tp_chat_state_changed_cb (TpChannel *channel,
382                           TpHandle   handle,
383                           TpChannelChatState state,
384                           gpointer   user_data,
385                           GObject   *chat)
386 {
387         EmpathyTpChatPriv *priv = GET_PRIV (chat);
388
389         empathy_tp_contact_factory_get_from_handles (priv->factory, 1, &handle,
390                 tp_chat_state_changed_got_contact_cb, GUINT_TO_POINTER (state),
391                 NULL, chat);
392 }
393
394 static void
395 tp_chat_list_pending_messages_cb (TpChannel       *channel,
396                                   const GPtrArray *messages_list,
397                                   const GError    *error,
398                                   gpointer         user_data,
399                                   GObject         *chat_)
400 {
401         EmpathyTpChat     *chat = EMPATHY_TP_CHAT (chat_);
402         EmpathyTpChatPriv *priv = GET_PRIV (chat);
403         guint              i;
404         GArray            *empty_non_text_content_ids = NULL;
405
406         priv->listing_pending_messages = FALSE;
407
408         if (priv->channel == NULL)
409                 return;
410
411         if (error) {
412                 DEBUG ("Error listing pending messages: %s", error->message);
413                 return;
414         }
415
416         for (i = 0; i < messages_list->len; i++) {
417                 GValueArray    *message_struct;
418                 const gchar    *message_body;
419                 guint           message_id;
420                 guint           timestamp;
421                 guint           from_handle;
422                 guint           message_type;
423                 guint           message_flags;
424
425                 message_struct = g_ptr_array_index (messages_list, i);
426
427                 message_id = g_value_get_uint (g_value_array_get_nth (message_struct, 0));
428                 timestamp = g_value_get_uint (g_value_array_get_nth (message_struct, 1));
429                 from_handle = g_value_get_uint (g_value_array_get_nth (message_struct, 2));
430                 message_type = g_value_get_uint (g_value_array_get_nth (message_struct, 3));
431                 message_flags = g_value_get_uint (g_value_array_get_nth (message_struct, 4));
432                 message_body = g_value_get_string (g_value_array_get_nth (message_struct, 5));
433
434                 DEBUG ("Message pending: %s", message_body);
435
436                 if (message_flags & TP_CHANNEL_TEXT_MESSAGE_FLAG_NON_TEXT_CONTENT &&
437                     !tp_strdiff (message_body, "")) {
438                         DEBUG ("Empty message with NonTextContent, ignoring and acking.");
439
440                         if (empty_non_text_content_ids == NULL) {
441                                 empty_non_text_content_ids = g_array_new (FALSE, FALSE, sizeof (guint));
442                         }
443
444                         g_array_append_val (empty_non_text_content_ids, message_id);
445                         continue;
446                 }
447
448                 tp_chat_build_message (chat,
449                                        message_id,
450                                        message_type,
451                                        timestamp,
452                                        from_handle,
453                                        message_body);
454         }
455
456         if (empty_non_text_content_ids != NULL) {
457                 acknowledge_messages (chat, empty_non_text_content_ids);
458                 g_array_free (empty_non_text_content_ids, TRUE);
459         }
460 }
461
462 static void
463 tp_chat_property_flags_changed_cb (TpProxy         *proxy,
464                                    const GPtrArray *properties,
465                                    gpointer         user_data,
466                                    GObject         *chat)
467 {
468         EmpathyTpChatPriv *priv = GET_PRIV (chat);
469         guint              i, j;
470
471         if (priv->channel == NULL)
472                 return;
473
474         if (!priv->had_properties_list || !properties) {
475                 return;
476         }
477
478         for (i = 0; i < properties->len; i++) {
479                 GValueArray    *prop_struct;
480                 TpChatProperty *property;
481                 guint           id;
482                 guint           flags;
483
484                 prop_struct = g_ptr_array_index (properties, i);
485                 id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
486                 flags = g_value_get_uint (g_value_array_get_nth (prop_struct, 1));
487
488                 for (j = 0; j < priv->properties->len; j++) {
489                         property = g_ptr_array_index (priv->properties, j);
490                         if (property->id == id) {
491                                 property->flags = flags;
492                                 DEBUG ("property %s flags changed: %d",
493                                         property->name, property->flags);
494                                 break;
495                         }
496                 }
497         }
498 }
499
500 static void
501 tp_chat_properties_changed_cb (TpProxy         *proxy,
502                                const GPtrArray *properties,
503                                gpointer         user_data,
504                                GObject         *chat)
505 {
506         EmpathyTpChatPriv *priv = GET_PRIV (chat);
507         guint              i, j;
508
509         if (priv->channel == NULL)
510                 return;
511
512         if (!priv->had_properties_list || !properties) {
513                 return;
514         }
515
516         for (i = 0; i < properties->len; i++) {
517                 GValueArray    *prop_struct;
518                 TpChatProperty *property;
519                 guint           id;
520                 GValue         *src_value;
521
522                 prop_struct = g_ptr_array_index (properties, i);
523                 id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
524                 src_value = g_value_get_boxed (g_value_array_get_nth (prop_struct, 1));
525
526                 for (j = 0; j < priv->properties->len; j++) {
527                         property = g_ptr_array_index (priv->properties, j);
528                         if (property->id == id) {
529                                 if (property->value) {
530                                         g_value_copy (src_value, property->value);
531                                 } else {
532                                         property->value = tp_g_value_slice_dup (src_value);
533                                 }
534
535                                 DEBUG ("property %s changed", property->name);
536                                 g_signal_emit (chat, signals[PROPERTY_CHANGED], 0,
537                                                property->name, property->value);
538                                 break;
539                         }
540                 }
541         }
542 }
543
544 static void
545 tp_chat_get_properties_cb (TpProxy         *proxy,
546                            const GPtrArray *properties,
547                            const GError    *error,
548                            gpointer         user_data,
549                            GObject         *chat)
550 {
551         if (error) {
552                 DEBUG ("Error getting properties: %s", error->message);
553                 return;
554         }
555
556         tp_chat_properties_changed_cb (proxy, properties, user_data, chat);
557 }
558
559 static void
560 tp_chat_list_properties_cb (TpProxy         *proxy,
561                             const GPtrArray *properties,
562                             const GError    *error,
563                             gpointer         user_data,
564                             GObject         *chat)
565 {
566         EmpathyTpChatPriv *priv = GET_PRIV (chat);
567         GArray            *ids;
568         guint              i;
569
570         if (priv->channel == NULL)
571                 return;
572
573         priv->had_properties_list = TRUE;
574
575         if (error) {
576                 DEBUG ("Error listing properties: %s", error->message);
577                 return;
578         }
579
580         ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), properties->len);
581         priv->properties = g_ptr_array_sized_new (properties->len);
582         for (i = 0; i < properties->len; i++) {
583                 GValueArray    *prop_struct;
584                 TpChatProperty *property;
585
586                 prop_struct = g_ptr_array_index (properties, i);
587                 property = g_slice_new0 (TpChatProperty);
588                 property->id = g_value_get_uint (g_value_array_get_nth (prop_struct, 0));
589                 property->name = g_value_dup_string (g_value_array_get_nth (prop_struct, 1));
590                 property->flags = g_value_get_uint (g_value_array_get_nth (prop_struct, 3));
591
592                 DEBUG ("Adding property name=%s id=%d flags=%d",
593                         property->name, property->id, property->flags);
594                 g_ptr_array_add (priv->properties, property);
595                 if (property->flags & TP_PROPERTY_FLAG_READ) {
596                         g_array_append_val (ids, property->id);
597                 }
598         }
599
600         tp_cli_properties_interface_call_get_properties (proxy, -1,
601                                                          ids,
602                                                          tp_chat_get_properties_cb,
603                                                          NULL, NULL,
604                                                          chat);
605
606         g_array_free (ids, TRUE);
607 }
608
609 void
610 empathy_tp_chat_set_property (EmpathyTpChat *chat,
611                               const gchar   *name,
612                               const GValue  *value)
613 {
614         EmpathyTpChatPriv *priv = GET_PRIV (chat);
615         TpChatProperty    *property;
616         guint              i;
617
618         for (i = 0; i < priv->properties->len; i++) {
619                 property = g_ptr_array_index (priv->properties, i);
620                 if (!tp_strdiff (property->name, name)) {
621                         GPtrArray   *properties;
622                         GValueArray *prop;
623                         GValue       id = {0, };
624                         GValue       dest_value = {0, };
625
626                         if (!(property->flags & TP_PROPERTY_FLAG_WRITE)) {
627                                 break;
628                         }
629
630                         g_value_init (&id, G_TYPE_UINT);
631                         g_value_init (&dest_value, G_TYPE_VALUE);
632                         g_value_set_uint (&id, property->id);
633                         g_value_set_boxed (&dest_value, value);
634
635                         prop = g_value_array_new (2);
636                         g_value_array_append (prop, &id);
637                         g_value_array_append (prop, &dest_value);
638
639                         properties = g_ptr_array_sized_new (1);
640                         g_ptr_array_add (properties, prop);
641
642                         DEBUG ("Set property %s", name);
643                         tp_cli_properties_interface_call_set_properties (priv->channel, -1,
644                                                                          properties,
645                                                                          (tp_cli_properties_interface_callback_for_set_properties)
646                                                                          tp_chat_async_cb,
647                                                                          "Seting property", NULL,
648                                                                          G_OBJECT (chat));
649
650                         g_ptr_array_free (properties, TRUE);
651                         g_value_array_free (prop);
652
653                         break;
654                 }
655         }
656 }
657
658 static void
659 tp_chat_dispose (GObject *object)
660 {
661         EmpathyTpChat *self = EMPATHY_TP_CHAT (object);
662         EmpathyTpChatPriv *priv = GET_PRIV (self);
663
664         if (priv->dispose_has_run)
665                 return;
666
667         priv->dispose_has_run = TRUE;
668
669         if (priv->channel != NULL) {
670                 g_signal_handlers_disconnect_by_func (priv->channel,
671                         tp_chat_invalidated_cb, self);
672                 g_object_unref (priv->channel);
673         }
674         priv->channel = NULL;
675
676         if (priv->remote_contact != NULL)
677                 g_object_unref (priv->remote_contact);
678         priv->remote_contact = NULL;
679
680         if (priv->factory != NULL)
681                 g_object_unref (priv->factory);
682         priv->factory = NULL;
683
684         if (priv->user != NULL);
685                 g_object_unref (priv->user);
686         priv->user = NULL;
687
688         if (priv->contact_monitor)
689                 g_object_unref (priv->contact_monitor);
690         priv->contact_monitor = NULL;
691
692         g_queue_foreach (priv->messages_queue, (GFunc) g_object_unref, NULL);
693         g_queue_clear (priv->messages_queue);
694
695         g_queue_foreach (priv->pending_messages_queue,
696                 (GFunc) g_object_unref, NULL);
697         g_queue_clear (priv->pending_messages_queue);
698
699         if (G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose)
700                 G_OBJECT_CLASS (empathy_tp_chat_parent_class)->dispose (object);
701 }
702
703 static void
704 tp_chat_finalize (GObject *object)
705 {
706         EmpathyTpChatPriv *priv = GET_PRIV (object);
707         guint              i;
708
709         DEBUG ("Finalize: %p", object);
710
711         if (priv->properties) {
712                 for (i = 0; i < priv->properties->len; i++) {
713                         TpChatProperty *property;
714
715                         property = g_ptr_array_index (priv->properties, i);
716                         g_free (property->name);
717                         if (property->value) {
718                                 tp_g_value_slice_free (property->value);
719                         }
720                         g_slice_free (TpChatProperty, property);
721                 }
722                 g_ptr_array_free (priv->properties, TRUE);
723         }
724
725         g_queue_free (priv->messages_queue);
726         g_queue_free (priv->pending_messages_queue);
727
728         G_OBJECT_CLASS (empathy_tp_chat_parent_class)->finalize (object);
729 }
730
731 static void
732 tp_chat_check_if_ready (EmpathyTpChat *chat)
733 {
734         EmpathyTpChatPriv *priv = GET_PRIV (chat);
735
736         if (priv->ready || priv->user == NULL ||
737             (priv->members == NULL && priv->remote_contact == NULL)) {
738                 return;
739         }
740
741         DEBUG ("Ready!");
742
743         priv->listing_pending_messages = TRUE;
744         tp_cli_channel_type_text_call_list_pending_messages (priv->channel, -1,
745                                                              FALSE,
746                                                              tp_chat_list_pending_messages_cb,
747                                                              NULL, NULL,
748                                                              G_OBJECT (chat));
749
750         tp_cli_channel_type_text_connect_to_received (priv->channel,
751                                                       tp_chat_received_cb,
752                                                       NULL, NULL,
753                                                       G_OBJECT (chat), NULL);
754         tp_cli_channel_type_text_connect_to_sent (priv->channel,
755                                                   tp_chat_sent_cb,
756                                                   NULL, NULL,
757                                                   G_OBJECT (chat), NULL);
758         tp_cli_channel_type_text_connect_to_send_error (priv->channel,
759                                                         tp_chat_send_error_cb,
760                                                         NULL, NULL,
761                                                         G_OBJECT (chat), NULL);
762         tp_cli_channel_interface_chat_state_connect_to_chat_state_changed (priv->channel,
763                                                                            tp_chat_state_changed_cb,
764                                                                            NULL, NULL,
765                                                                            G_OBJECT (chat), NULL);
766         tp_cli_channel_interface_chat_state_connect_to_chat_state_changed (priv->channel,
767                                                                            tp_chat_state_changed_cb,
768                                                                            NULL, NULL,
769                                                                            G_OBJECT (chat), NULL);
770         priv->ready = TRUE;
771         g_object_notify (G_OBJECT (chat), "ready");
772 }
773
774 static void
775 tp_chat_update_remote_contact (EmpathyTpChat *chat)
776 {
777         EmpathyTpChatPriv *priv = GET_PRIV (chat);
778         EmpathyContact *contact = NULL;
779         TpHandle self_handle;
780         TpHandleType handle_type;
781         GList *l;
782
783         /* If this is a named chatroom, never pretend it is a private chat */
784         tp_channel_get_handle (priv->channel, &handle_type);
785         if (handle_type == TP_HANDLE_TYPE_ROOM) {
786                 return;
787         }
788
789         /* This is an MSN-like chat where anyone can join the chat at anytime.
790          * If there is only one non-self contact member, we are in a private
791          * chat and we set the "remote-contact" property to that contact. If
792          * there are more, set the "remote-contact" property to NULL and the
793          * UI will display a contact list. */
794         self_handle = tp_channel_group_get_self_handle (priv->channel);
795         for (l = priv->members; l; l = l->next) {
796                 /* Skip self contact if member */
797                 if (empathy_contact_get_handle (l->data) == self_handle) {
798                         continue;
799                 }
800
801                 /* We have more than one remote contact, break */
802                 if (contact != NULL) {
803                         contact = NULL;
804                         break;
805                 }
806
807                 /* If we didn't find yet a remote contact, keep this one */
808                 contact = l->data;
809         }
810
811         if (priv->remote_contact == contact) {
812                 return;
813         }
814
815         DEBUG ("Changing remote contact from %p to %p",
816                 priv->remote_contact, contact);
817
818         if (priv->remote_contact) {
819                 g_object_unref (priv->remote_contact);
820         }
821
822         priv->remote_contact = contact ? g_object_ref (contact) : NULL;
823         g_object_notify (G_OBJECT (chat), "remote-contact");
824 }
825
826 static void
827 tp_chat_got_added_contacts_cb (EmpathyTpContactFactory *factory,
828                                GList                   *contacts,
829                                gpointer                 user_data,
830                                GObject                 *chat)
831 {
832         EmpathyTpChatPriv *priv = GET_PRIV (chat);
833         GList *l;
834         const TpIntSet *members;
835         TpHandle handle;
836         EmpathyContact *contact;
837
838         members = tp_channel_group_get_members (priv->channel);
839         for (l = contacts; l; l = l->next) {
840                 contact = l->data;
841                 handle = empathy_contact_get_handle (contact);
842
843                 /* Make sure the contact is still member */
844                 if (tp_intset_is_member (members, handle)) {
845                         priv->members = g_list_prepend (priv->members,
846                                 g_object_ref (contact));
847                         g_signal_emit_by_name (chat, "members-changed",
848                                                contact, NULL, 0, NULL, FALSE);
849                 }
850         }
851
852         tp_chat_update_remote_contact (EMPATHY_TP_CHAT (chat));
853         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
854 }
855
856 static void
857 tp_chat_group_members_changed_cb (TpChannel     *self,
858                                   gchar         *message,
859                                   GArray        *added,
860                                   GArray        *removed,
861                                   GArray        *local_pending,
862                                   GArray        *remote_pending,
863                                   guint          actor,
864                                   guint          reason,
865                                   EmpathyTpChat *chat)
866 {
867         EmpathyTpChatPriv *priv = GET_PRIV (chat);
868         EmpathyContact *contact;
869         TpHandle handle;
870         guint i;
871         GList *l;
872
873         /* Remove contacts that are not members anymore */
874         for (i = 0; i < removed->len; i++) {
875                 for (l = priv->members; l; l = l->next) {
876                         contact = l->data;
877                         handle = empathy_contact_get_handle (contact);
878                         if (handle == g_array_index (removed, TpHandle, i)) {
879                                 priv->members = g_list_delete_link (priv->members, l);
880                                 g_signal_emit_by_name (chat, "members-changed",
881                                                        contact, NULL, reason,
882                                                        message, FALSE);
883                                 g_object_unref (contact);
884                                 break;
885                         }
886                 }
887         }
888
889         /* Request added contacts */
890         if (added->len > 0) {
891                 empathy_tp_contact_factory_get_from_handles (priv->factory,
892                         added->len, (TpHandle*) added->data,
893                         tp_chat_got_added_contacts_cb, NULL, NULL,
894                         G_OBJECT (chat));
895         }
896
897         tp_chat_update_remote_contact (chat);
898 }
899
900 static void
901 tp_chat_got_remote_contact_cb (EmpathyTpContactFactory *factory,
902                                GList *contacts,
903                                gpointer user_data,
904                                GObject *chat)
905 {
906         EmpathyTpChatPriv *priv = GET_PRIV (chat);
907
908         priv->remote_contact = g_object_ref (contacts->data);
909         g_object_notify (chat, "remote-contact");
910
911         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
912 }
913
914 static void
915 tp_chat_got_self_contact_cb (EmpathyTpContactFactory *factory,
916                              GList                   *contacts,
917                              gpointer                 user_data,
918                              GObject                 *chat)
919 {
920         EmpathyTpChatPriv *priv = GET_PRIV (chat);
921
922         priv->user = g_object_ref (contacts->data);
923         empathy_contact_set_is_user (priv->user, TRUE);
924         tp_chat_check_if_ready (EMPATHY_TP_CHAT (chat));
925 }
926
927 static void
928 tp_chat_get_self_handle_cb (TpConnection *connection,
929                             TpHandle self_handle,
930                             const GError *error,
931                             gpointer user_data,
932                             GObject *chat)
933 {
934         EmpathyTpChatPriv *priv = GET_PRIV (chat);
935
936         if (error) {
937                 DEBUG ("Error: %s", error->message);
938                 tp_cli_channel_call_close (priv->channel, -1,
939                                            NULL, NULL, NULL, NULL);
940                 return;
941         }
942
943         empathy_tp_contact_factory_get_from_handles (priv->factory,
944                 1, &self_handle,
945                 tp_chat_got_self_contact_cb,
946                 NULL, NULL, chat);
947 }
948
949 static GObject *
950 tp_chat_constructor (GType                  type,
951                      guint                  n_props,
952                      GObjectConstructParam *props)
953 {
954         GObject           *chat;
955         EmpathyTpChatPriv *priv;
956         TpConnection      *connection;
957         TpHandle           handle;
958
959         chat = G_OBJECT_CLASS (empathy_tp_chat_parent_class)->constructor (type, n_props, props);
960
961         priv = GET_PRIV (chat);
962
963         connection = tp_channel_borrow_connection (priv->channel);
964         priv->factory = empathy_tp_contact_factory_dup_singleton (connection);
965         g_signal_connect (priv->channel, "invalidated",
966                           G_CALLBACK (tp_chat_invalidated_cb),
967                           chat);
968
969         if (tp_proxy_has_interface_by_id (priv->channel,
970                                           TP_IFACE_QUARK_CHANNEL_INTERFACE_GROUP)) {
971                 const TpIntSet *members;
972                 GArray *handles;
973
974                 /* Get self contact from the group's self handle */
975                 handle = tp_channel_group_get_self_handle (priv->channel);
976                 empathy_tp_contact_factory_get_from_handles (priv->factory,
977                         1, &handle,
978                         tp_chat_got_self_contact_cb,
979                         NULL, NULL, chat);
980
981                 /* Get initial member contacts */
982                 members = tp_channel_group_get_members (priv->channel);
983                 handles = tp_intset_to_array (members);         
984                 empathy_tp_contact_factory_get_from_handles (priv->factory,
985                         handles->len, (TpHandle*) handles->data,
986                         tp_chat_got_added_contacts_cb, NULL, NULL, chat);
987
988                 g_signal_connect (priv->channel, "group-members-changed",
989                         G_CALLBACK (tp_chat_group_members_changed_cb), chat);
990         } else {
991                 /* Get the self contact from the connection's self handle */
992                 tp_cli_connection_call_get_self_handle (connection, -1,
993                         tp_chat_get_self_handle_cb, NULL, NULL, chat);
994
995                 /* Get the remote contact */
996                 handle = tp_channel_get_handle (priv->channel, NULL);
997                 empathy_tp_contact_factory_get_from_handles (priv->factory,
998                         1, &handle, tp_chat_got_remote_contact_cb,
999                         NULL, NULL, chat);
1000         }
1001
1002         if (tp_proxy_has_interface_by_id (priv->channel,
1003                                           TP_IFACE_QUARK_PROPERTIES_INTERFACE)) {
1004                 tp_cli_properties_interface_call_list_properties (priv->channel, -1,
1005                                                                   tp_chat_list_properties_cb,
1006                                                                   NULL, NULL,
1007                                                                   G_OBJECT (chat));
1008                 tp_cli_properties_interface_connect_to_properties_changed (priv->channel,
1009                                                                            tp_chat_properties_changed_cb,
1010                                                                            NULL, NULL,
1011                                                                            G_OBJECT (chat), NULL);
1012                 tp_cli_properties_interface_connect_to_property_flags_changed (priv->channel,
1013                                                                                tp_chat_property_flags_changed_cb,
1014                                                                                NULL, NULL,
1015                                                                                G_OBJECT (chat), NULL);
1016         }
1017
1018         return chat;
1019 }
1020
1021 static void
1022 tp_chat_get_property (GObject    *object,
1023                       guint       param_id,
1024                       GValue     *value,
1025                       GParamSpec *pspec)
1026 {
1027         EmpathyTpChatPriv *priv = GET_PRIV (object);
1028
1029         switch (param_id) {
1030         case PROP_CHANNEL:
1031                 g_value_set_object (value, priv->channel);
1032                 break;
1033         case PROP_REMOTE_CONTACT:
1034                 g_value_set_object (value, priv->remote_contact);
1035                 break;
1036         case PROP_READY:
1037                 g_value_set_boolean (value, priv->ready);
1038                 break;
1039         default:
1040                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1041                 break;
1042         };
1043 }
1044
1045 static void
1046 tp_chat_set_property (GObject      *object,
1047                       guint         param_id,
1048                       const GValue *value,
1049                       GParamSpec   *pspec)
1050 {
1051         EmpathyTpChatPriv *priv = GET_PRIV (object);
1052
1053         switch (param_id) {
1054         case PROP_CHANNEL:
1055                 priv->channel = g_value_dup_object (value);
1056                 break;
1057         default:
1058                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1059                 break;
1060         };
1061 }
1062
1063 static void
1064 empathy_tp_chat_class_init (EmpathyTpChatClass *klass)
1065 {
1066         GObjectClass *object_class = G_OBJECT_CLASS (klass);
1067
1068         object_class->dispose = tp_chat_dispose;
1069         object_class->finalize = tp_chat_finalize;
1070         object_class->constructor = tp_chat_constructor;
1071         object_class->get_property = tp_chat_get_property;
1072         object_class->set_property = tp_chat_set_property;
1073
1074         g_object_class_install_property (object_class,
1075                                          PROP_CHANNEL,
1076                                          g_param_spec_object ("channel",
1077                                                               "telepathy channel",
1078                                                               "The text channel for the chat",
1079                                                               TP_TYPE_CHANNEL,
1080                                                               G_PARAM_READWRITE |
1081                                                               G_PARAM_CONSTRUCT_ONLY));
1082
1083         g_object_class_install_property (object_class,
1084                                          PROP_REMOTE_CONTACT,
1085                                          g_param_spec_object ("remote-contact",
1086                                                               "The remote contact",
1087                                                               "The remote contact if there is no group iface on the channel",
1088                                                               EMPATHY_TYPE_CONTACT,
1089                                                               G_PARAM_READABLE));
1090
1091         g_object_class_install_property (object_class,
1092                                          PROP_READY,
1093                                          g_param_spec_boolean ("ready",
1094                                                                "Is the object ready",
1095                                                                "This object can't be used until this becomes true",
1096                                                                FALSE,
1097                                                                G_PARAM_READABLE));
1098
1099         /* Signals */
1100         signals[MESSAGE_RECEIVED] =
1101                 g_signal_new ("message-received",
1102                               G_TYPE_FROM_CLASS (klass),
1103                               G_SIGNAL_RUN_LAST,
1104                               0,
1105                               NULL, NULL,
1106                               g_cclosure_marshal_VOID__OBJECT,
1107                               G_TYPE_NONE,
1108                               1, EMPATHY_TYPE_MESSAGE);
1109
1110         signals[SEND_ERROR] =
1111                 g_signal_new ("send-error",
1112                               G_TYPE_FROM_CLASS (klass),
1113                               G_SIGNAL_RUN_LAST,
1114                               0,
1115                               NULL, NULL,
1116                               _empathy_marshal_VOID__OBJECT_UINT,
1117                               G_TYPE_NONE,
1118                               2, EMPATHY_TYPE_MESSAGE, G_TYPE_UINT);
1119
1120         signals[CHAT_STATE_CHANGED] =
1121                 g_signal_new ("chat-state-changed",
1122                               G_TYPE_FROM_CLASS (klass),
1123                               G_SIGNAL_RUN_LAST,
1124                               0,
1125                               NULL, NULL,
1126                               _empathy_marshal_VOID__OBJECT_UINT,
1127                               G_TYPE_NONE,
1128                               2, EMPATHY_TYPE_CONTACT, G_TYPE_UINT);
1129
1130         signals[PROPERTY_CHANGED] =
1131                 g_signal_new ("property-changed",
1132                               G_TYPE_FROM_CLASS (klass),
1133                               G_SIGNAL_RUN_LAST,
1134                               0,
1135                               NULL, NULL,
1136                               _empathy_marshal_VOID__STRING_BOXED,
1137                               G_TYPE_NONE,
1138                               2, G_TYPE_STRING, G_TYPE_VALUE);
1139
1140         signals[DESTROY] =
1141                 g_signal_new ("destroy",
1142                               G_TYPE_FROM_CLASS (klass),
1143                               G_SIGNAL_RUN_LAST,
1144                               0,
1145                               NULL, NULL,
1146                               g_cclosure_marshal_VOID__VOID,
1147                               G_TYPE_NONE,
1148                               0);
1149
1150         g_type_class_add_private (object_class, sizeof (EmpathyTpChatPriv));
1151 }
1152
1153 static void
1154 empathy_tp_chat_init (EmpathyTpChat *chat)
1155 {
1156         EmpathyTpChatPriv *priv = G_TYPE_INSTANCE_GET_PRIVATE (chat,
1157                 EMPATHY_TYPE_TP_CHAT, EmpathyTpChatPriv);
1158
1159         chat->priv = priv;
1160         priv->contact_monitor = NULL;
1161         priv->messages_queue = g_queue_new ();
1162         priv->pending_messages_queue = g_queue_new ();
1163 }
1164
1165 static void
1166 tp_chat_iface_init (EmpathyContactListIface *iface)
1167 {
1168         iface->add         = tp_chat_add;
1169         iface->remove      = tp_chat_remove;
1170         iface->get_members = tp_chat_get_members;
1171         iface->get_monitor = tp_chat_get_monitor;
1172 }
1173
1174 EmpathyTpChat *
1175 empathy_tp_chat_new (TpChannel *channel)
1176 {
1177         return g_object_new (EMPATHY_TYPE_TP_CHAT,
1178                              "channel", channel,
1179                              NULL);
1180 }
1181
1182 void
1183 empathy_tp_chat_close (EmpathyTpChat *chat) {
1184         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1185
1186         /* If there are still messages left, it'll come back..
1187          * We loose the ordering of sent messages though */
1188         tp_cli_channel_call_close (priv->channel, -1, tp_chat_async_cb,
1189                 "closing channel", NULL, NULL);
1190 }
1191
1192 const gchar *
1193 empathy_tp_chat_get_id (EmpathyTpChat *chat)
1194 {
1195         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1196
1197         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1198
1199         return tp_channel_get_identifier (priv->channel);
1200 }
1201
1202 EmpathyContact *
1203 empathy_tp_chat_get_remote_contact (EmpathyTpChat *chat)
1204 {
1205         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1206
1207         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1208         g_return_val_if_fail (priv->ready, NULL);
1209
1210         return priv->remote_contact;
1211 }
1212
1213 TpChannel *
1214 empathy_tp_chat_get_channel (EmpathyTpChat *chat)
1215 {
1216         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1217
1218         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1219
1220         return priv->channel;
1221 }
1222
1223 TpConnection *
1224 empathy_tp_chat_get_connection (EmpathyTpChat *chat)
1225 {
1226         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1227
1228         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1229
1230         return tp_channel_borrow_connection (priv->channel);
1231 }
1232
1233 gboolean
1234 empathy_tp_chat_is_ready (EmpathyTpChat *chat)
1235 {
1236         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1237
1238         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), FALSE);
1239
1240         return priv->ready;
1241 }
1242
1243 void
1244 empathy_tp_chat_send (EmpathyTpChat *chat,
1245                       EmpathyMessage *message)
1246 {
1247         EmpathyTpChatPriv        *priv = GET_PRIV (chat);
1248         const gchar              *message_body;
1249         TpChannelTextMessageType  message_type;
1250
1251         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1252         g_return_if_fail (EMPATHY_IS_MESSAGE (message));
1253         g_return_if_fail (priv->ready);
1254
1255         message_body = empathy_message_get_body (message);
1256         message_type = empathy_message_get_tptype (message);
1257
1258         DEBUG ("Sending message: %s", message_body);
1259         tp_cli_channel_type_text_call_send (priv->channel, -1,
1260                                             message_type,
1261                                             message_body,
1262                                             tp_chat_send_cb,
1263                                             g_object_ref (message),
1264                                             (GDestroyNotify) g_object_unref,
1265                                             G_OBJECT (chat));
1266 }
1267
1268 void
1269 empathy_tp_chat_set_state (EmpathyTpChat      *chat,
1270                            TpChannelChatState  state)
1271 {
1272         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1273
1274         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1275         g_return_if_fail (priv->ready);
1276
1277         DEBUG ("Set state: %d", state);
1278         tp_cli_channel_interface_chat_state_call_set_chat_state (priv->channel, -1,
1279                                                                  state,
1280                                                                  tp_chat_async_cb,
1281                                                                  "setting chat state",
1282                                                                  NULL,
1283                                                                  G_OBJECT (chat));
1284 }
1285
1286
1287 const GList *
1288 empathy_tp_chat_get_pending_messages (EmpathyTpChat *chat)
1289 {
1290         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1291
1292         g_return_val_if_fail (EMPATHY_IS_TP_CHAT (chat), NULL);
1293         g_return_val_if_fail (priv->ready, NULL);
1294
1295         return priv->pending_messages_queue->head;
1296 }
1297
1298 static void
1299 acknowledge_messages (EmpathyTpChat *chat, GArray *ids) {
1300         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1301
1302         tp_cli_channel_type_text_call_acknowledge_pending_messages (
1303                 priv->channel, -1, ids, tp_chat_async_cb,
1304                 "acknowledging received message", NULL, G_OBJECT (chat));
1305 }
1306
1307 void
1308 empathy_tp_chat_acknowledge_message (EmpathyTpChat *chat,
1309                                      EmpathyMessage *message) {
1310         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1311         GArray *message_ids;
1312         GList *m;
1313         guint id;
1314
1315         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1316         g_return_if_fail (priv->ready);
1317
1318         if (empathy_message_get_sender (message) == priv->user)
1319                 goto out;
1320
1321         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
1322
1323         id = empathy_message_get_id (message);
1324         g_array_append_val (message_ids, id);
1325         acknowledge_messages (chat, message_ids);
1326         g_array_free (message_ids, TRUE);
1327
1328 out:
1329         m = g_queue_find (priv->pending_messages_queue, message);
1330         g_assert (m != NULL);
1331         g_queue_delete_link (priv->pending_messages_queue, m);
1332         g_object_unref (message);
1333 }
1334
1335 void
1336 empathy_tp_chat_acknowledge_messages (EmpathyTpChat *chat,
1337                                       const GList *messages) {
1338         EmpathyTpChatPriv *priv = GET_PRIV (chat);
1339         /* Copy messages as the messges list (probably is) our own */
1340         GList *msgs = g_list_copy ((GList *) messages);
1341         GList *l;
1342         guint length;
1343         GArray *message_ids;
1344
1345         g_return_if_fail (EMPATHY_IS_TP_CHAT (chat));
1346         g_return_if_fail (priv->ready);
1347
1348         length = g_list_length ((GList *)messages);
1349
1350         if (length == 0)
1351                 return;
1352
1353         message_ids = g_array_sized_new (FALSE, FALSE, sizeof (guint), length);
1354
1355         for (l = msgs; l != NULL; l = g_list_next (l)) {
1356                 GList *m;
1357
1358                 EmpathyMessage *message = EMPATHY_MESSAGE (l->data);
1359
1360                 m = g_queue_find (priv->pending_messages_queue, message);
1361                 g_assert (m != NULL);
1362                 g_queue_delete_link (priv->pending_messages_queue, m);
1363
1364                 if (empathy_message_get_sender (message) != priv->user) {
1365                         guint id = empathy_message_get_id (message);
1366                         g_array_append_val (message_ids, id);
1367                 }
1368                 g_object_unref (message);
1369         }
1370
1371         if (message_ids->len > 0)
1372                 acknowledge_messages (chat, message_ids);
1373
1374         g_array_free (message_ids, TRUE);
1375         g_list_free (msgs);
1376 }
1377