64bec75ff052b1642488f6e719cf20cbd9040e97
[empathy.git] / libempathy / empathy-tp-contact-list.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2007 Xavier Claessens <xclaesse@gmail.com>
4  * Copyright (C) 2007 Collabora Ltd.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the
9  * License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  * 
21  * Authors: Xavier Claessens <xclaesse@gmail.com>
22  */
23
24 #include <config.h>
25
26 #include <string.h>
27
28 #include <libtelepathy/tp-helpers.h>
29 #include <libtelepathy/tp-conn.h>
30 #include <libtelepathy/tp-chan.h>
31 #include <libtelepathy/tp-chan-type-contact-list-gen.h>
32 #include <libtelepathy/tp-conn-iface-aliasing-gen.h>
33 #include <libtelepathy/tp-conn-iface-presence-gen.h>
34 #include <libtelepathy/tp-conn-iface-avatars-gen.h>
35
36 #include "empathy-tp-contact-list.h"
37 #include "empathy-contact-list.h"
38 #include "gossip-telepathy-group.h"
39 #include "gossip-debug.h"
40 #include "gossip-utils.h"
41
42 #define GET_PRIV(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), \
43                        EMPATHY_TYPE_TP_CONTACT_LIST, EmpathyTpContactListPriv))
44
45 #define DEBUG_DOMAIN "TpContactList"
46 #define MAX_AVATAR_REQUESTS 10
47
48 struct _EmpathyTpContactListPriv {
49         TpConn               *tp_conn;
50         McAccount            *account;
51         MissionControl       *mc;
52         GossipContact        *user_contact;
53         gboolean              setup;
54
55         GossipTelepathyGroup *known;
56         GossipTelepathyGroup *publish;
57         GossipTelepathyGroup *subscribe;
58
59         GHashTable           *groups;
60         GHashTable           *contacts;
61
62         DBusGProxy           *aliasing_iface;
63         DBusGProxy           *avatars_iface;
64         DBusGProxy           *presence_iface;
65
66         GList                *avatar_requests_queue;
67 };
68
69 typedef enum {
70         TP_CONTACT_LIST_TYPE_KNOWN,
71         TP_CONTACT_LIST_TYPE_PUBLISH,
72         TP_CONTACT_LIST_TYPE_SUBSCRIBE,
73         TP_CONTACT_LIST_TYPE_UNKNOWN,
74         TP_CONTACT_LIST_TYPE_COUNT
75 } TpContactListType;
76
77 typedef struct {
78         guint  handle;
79         GList *new_groups;
80 } TpContactListData;
81
82 typedef struct {
83         EmpathyTpContactList *list;
84         guint                 handle;
85 } TpContactListAvatarRequestData;
86
87 typedef struct {
88         EmpathyTpContactList *list;
89         guint                *handles;
90 } TpContactListAliasesRequestData;
91
92 static void                   empathy_tp_contact_list_class_init       (EmpathyTpContactListClass       *klass);
93 static void                   tp_contact_list_iface_init               (EmpathyContactListIface         *iface);
94 static void                   empathy_tp_contact_list_init             (EmpathyTpContactList            *list);
95 static void                   tp_contact_list_finalize                 (GObject                         *object);
96 static void                   tp_contact_list_finalize_proxies         (EmpathyTpContactList            *list);
97 static void                   tp_contact_list_setup                    (EmpathyContactList              *list);
98 static GossipContact *        tp_contact_list_find                     (EmpathyContactList              *list,
99                                                                         const gchar                     *id);
100 static void                   tp_contact_list_add                      (EmpathyContactList              *list,
101                                                                         GossipContact                   *contact,
102                                                                         const gchar                     *message);
103 static void                   tp_contact_list_remove                   (EmpathyContactList              *list,
104                                                                         GossipContact                   *contact,
105                                                                         const gchar                     *message);
106 static GList *                tp_contact_list_get_contacts             (EmpathyContactList              *list);
107 static void                   tp_contact_list_contact_removed_foreach  (guint                            handle,
108                                                                         GossipContact                   *contact,
109                                                                         EmpathyTpContactList            *list);
110 static void                   tp_contact_list_destroy_cb               (DBusGProxy                      *proxy,
111                                                                         EmpathyTpContactList            *list);
112 static gboolean               tp_contact_list_find_foreach             (guint                            handle,
113                                                                         GossipContact                   *contact,
114                                                                         gchar                           *id);
115 static void                   tp_contact_list_newchannel_cb            (DBusGProxy                      *proxy,
116                                                                         const gchar                     *object_path,
117                                                                         const gchar                     *channel_type,
118                                                                         TelepathyHandleType              handle_type,
119                                                                         guint                            channel_handle,
120                                                                         gboolean                         suppress_handle,
121                                                                         EmpathyTpContactList            *list);
122 static TpContactListType      tp_contact_list_get_type                 (EmpathyTpContactList            *list,
123                                                                         TpChan                          *list_chan);
124 static void                   tp_contact_list_contact_added_cb         (GossipTelepathyGroup            *group,
125                                                                         GArray                          *handles,
126                                                                         guint                            actor_handle,
127                                                                         guint                            reason,
128                                                                         const gchar                     *message,
129                                                                         EmpathyTpContactList            *list);
130 static void                   tp_contact_list_contact_removed_cb       (GossipTelepathyGroup            *group,
131                                                                         GArray                          *handles,
132                                                                         guint                            actor_handle,
133                                                                         guint                            reason,
134                                                                         const gchar                     *message,
135                                                                         EmpathyTpContactList            *list);
136 static void                   tp_contact_list_local_pending_cb         (GossipTelepathyGroup            *group,
137                                                                         GArray                          *handles,
138                                                                         guint                            actor_handle,
139                                                                         guint                            reason,
140                                                                         const gchar                     *message,
141                                                                         EmpathyTpContactList            *list);
142 static void                   tp_contact_list_groups_updated_cb        (GossipContact                   *contact,
143                                                                         GParamSpec                      *param,
144                                                                         EmpathyTpContactList            *list);
145 static void                   tp_contact_list_subscription_updated_cb  (GossipContact                   *contact,
146                                                                         GParamSpec                      *param,
147                                                                         EmpathyTpContactList            *list);
148 static void                   tp_contact_list_name_updated_cb          (GossipContact                   *contact,
149                                                                         GParamSpec                      *param,
150                                                                         EmpathyTpContactList            *list);
151 static void                   tp_contact_list_update_groups_foreach    (gchar                           *object_path,
152                                                                         GossipTelepathyGroup            *group,
153                                                                         TpContactListData               *data);
154 static GossipTelepathyGroup * tp_contact_list_get_group                (EmpathyTpContactList            *list,
155                                                                         const gchar                     *name);
156 static gboolean               tp_contact_list_find_group               (gchar                           *key,
157                                                                         GossipTelepathyGroup            *group,
158                                                                         gchar                           *group_name);
159 static void                   tp_contact_list_get_groups_foreach       (gchar                           *key,
160                                                                         GossipTelepathyGroup            *group,
161                                                                         GList                          **groups);
162 static void                   tp_contact_list_group_channel_closed_cb  (TpChan                          *channel,
163                                                                         EmpathyTpContactList            *list);
164 static void                   tp_contact_list_group_members_added_cb   (GossipTelepathyGroup            *group,
165                                                                         GArray                          *members,
166                                                                         guint                            actor_handle,
167                                                                         guint                            reason,
168                                                                         const gchar                     *message,
169                                                                         EmpathyTpContactList            *list);
170 static void                   tp_contact_list_group_members_removed_cb (GossipTelepathyGroup            *group,
171                                                                         GArray                          *members,
172                                                                         guint                            actor_handle,
173                                                                         guint                            reason,
174                                                                         const gchar                     *message,
175                                                                         EmpathyTpContactList            *list);
176 static void                   tp_contact_list_get_contacts_foreach     (guint                            handle,
177                                                                         GossipContact                   *contact,
178                                                                         GList                          **contacts);
179 static void                   tp_contact_list_get_info                 (EmpathyTpContactList            *list,
180                                                                         GArray                          *handles);
181 static void                   tp_contact_list_request_avatar           (EmpathyTpContactList            *list,
182                                                                         guint                            handle);
183 static void                   tp_contact_list_start_avatar_requests    (EmpathyTpContactList            *list);
184 static void                   tp_contact_list_avatar_update_cb         (DBusGProxy                      *proxy,
185                                                                         guint                            handle,
186                                                                         gchar                           *new_token,
187                                                                         EmpathyTpContactList            *list);
188 static void                   tp_contact_list_request_avatar_cb        (DBusGProxy                      *proxy,
189                                                                         GArray                          *avatar_data,
190                                                                         gchar                           *mime_type,
191                                                                         GError                          *error,
192                                                                         TpContactListAvatarRequestData  *data);
193 static void                   tp_contact_list_aliases_update_cb        (DBusGProxy                      *proxy,
194                                                                         GPtrArray                       *handlers,
195                                                                         EmpathyTpContactList            *list);
196 static void                   tp_contact_list_request_aliases_cb       (DBusGProxy                      *proxy,
197                                                                         gchar                          **contact_names,
198                                                                         GError                          *error,
199                                                                         TpContactListAliasesRequestData *data);
200 static void                   tp_contact_list_presence_update_cb       (DBusGProxy                      *proxy,
201                                                                         GHashTable                      *handle_table,
202                                                                         EmpathyTpContactList            *list);
203 static void                   tp_contact_list_parse_presence_foreach   (guint                            handle,
204                                                                         GValueArray                     *presence_struct,
205                                                                         EmpathyTpContactList            *list);
206 static void                   tp_contact_list_presences_table_foreach  (const gchar                     *state_str,
207                                                                         GHashTable                      *presences_table,
208                                                                         GossipPresence                 **presence);
209 static void                   tp_contact_list_status_changed_cb        (MissionControl                  *mc,
210                                                                         TelepathyConnectionStatus        status,
211                                                                         McPresence                       presence,
212                                                                         TelepathyConnectionStatusReason  reason,
213                                                                         const gchar                     *unique_name,
214                                                                         EmpathyTpContactList            *list);
215
216 enum {
217         DESTROY,
218         LAST_SIGNAL
219 };
220
221 static guint signals[LAST_SIGNAL];
222 static guint n_avatar_requests = 0;
223
224 G_DEFINE_TYPE_WITH_CODE (EmpathyTpContactList, empathy_tp_contact_list, G_TYPE_OBJECT,
225                          G_IMPLEMENT_INTERFACE (EMPATHY_TYPE_CONTACT_LIST,
226                                                 tp_contact_list_iface_init));
227
228 static void
229 empathy_tp_contact_list_class_init (EmpathyTpContactListClass *klass)
230 {
231         GObjectClass *object_class = G_OBJECT_CLASS (klass);
232
233         object_class->finalize = tp_contact_list_finalize;
234
235         signals[DESTROY] =
236                 g_signal_new ("destroy",
237                               G_TYPE_FROM_CLASS (klass),
238                               G_SIGNAL_RUN_LAST,
239                               0,
240                               NULL, NULL,
241                               g_cclosure_marshal_VOID__VOID,
242                               G_TYPE_NONE,
243                               0);
244
245         g_type_class_add_private (object_class, sizeof (EmpathyTpContactListPriv));
246 }
247
248 static void
249 tp_contact_list_iface_init (EmpathyContactListIface *iface)
250 {
251         iface->setup = tp_contact_list_setup;
252         iface->find = tp_contact_list_find;
253         iface->add = tp_contact_list_add;
254         iface->remove = tp_contact_list_remove;
255         iface->get_contacts = tp_contact_list_get_contacts;
256 }
257
258 static void
259 empathy_tp_contact_list_init (EmpathyTpContactList *list)
260 {
261         EmpathyTpContactListPriv *priv;
262
263         priv = GET_PRIV (list);
264
265         priv->groups = g_hash_table_new_full (g_str_hash,
266                                               g_str_equal,
267                                               (GDestroyNotify) g_free,
268                                               (GDestroyNotify) g_object_unref);
269         priv->contacts = g_hash_table_new_full (g_direct_hash,
270                                                 g_direct_equal,
271                                                 NULL,
272                                                 (GDestroyNotify) g_object_unref);
273 }
274
275 static void
276 tp_contact_list_finalize (GObject *object)
277 {
278         EmpathyTpContactListPriv *priv;
279         EmpathyTpContactList     *list;
280
281         list = EMPATHY_TP_CONTACT_LIST (object);
282         priv = GET_PRIV (list);
283
284         gossip_debug (DEBUG_DOMAIN, "finalize: %p", object);
285
286         dbus_g_proxy_disconnect_signal (DBUS_G_PROXY (priv->mc),
287                                         "AccountStatusChanged",
288                                         G_CALLBACK (tp_contact_list_status_changed_cb),
289                                         list);
290
291         tp_contact_list_finalize_proxies (list);
292
293         if (priv->tp_conn) {
294                 g_object_unref (priv->tp_conn);
295         }
296
297         if (priv->known) {
298                 g_object_unref (priv->known);
299         }
300
301         if (priv->subscribe) {
302                 g_object_unref (priv->subscribe);
303         }
304
305         if (priv->publish) {
306                 g_object_unref (priv->publish);
307         }
308
309         g_object_unref (priv->account);
310         g_object_unref (priv->user_contact);
311         g_object_unref (priv->mc);
312         g_hash_table_destroy (priv->groups);
313         g_hash_table_destroy (priv->contacts);
314
315         G_OBJECT_CLASS (empathy_tp_contact_list_parent_class)->finalize (object);
316 }
317
318 EmpathyTpContactList *
319 empathy_tp_contact_list_new (McAccount *account)
320 {
321         EmpathyTpContactListPriv *priv;
322         EmpathyTpContactList     *list;
323         MissionControl           *mc;
324         guint                     handle;
325         GError                   *error = NULL;
326
327         g_return_val_if_fail (MC_IS_ACCOUNT (account), NULL);
328
329         mc = gossip_mission_control_new ();
330
331         if (mission_control_get_connection_status (mc, account, NULL) != 0) {
332                 /* The account is not connected, nothing to do. */
333                 return NULL;
334         }
335
336         list = g_object_new (EMPATHY_TYPE_TP_CONTACT_LIST, NULL);
337         priv = GET_PRIV (list);
338
339         priv->tp_conn = mission_control_get_connection (mc, account, NULL);
340         priv->account = g_object_ref (account);
341         priv->mc = mc;
342
343         g_signal_connect (priv->tp_conn, "destroy",
344                           G_CALLBACK (tp_contact_list_destroy_cb),
345                           list);
346         dbus_g_proxy_connect_signal (DBUS_G_PROXY (priv->mc),
347                                      "AccountStatusChanged",
348                                      G_CALLBACK (tp_contact_list_status_changed_cb),
349                                      list, NULL);
350
351         priv->aliasing_iface = tp_conn_get_interface (priv->tp_conn,
352                                                       TELEPATHY_CONN_IFACE_ALIASING_QUARK);
353         priv->avatars_iface = tp_conn_get_interface (priv->tp_conn,
354                                                      TELEPATHY_CONN_IFACE_AVATARS_QUARK);
355         priv->presence_iface = tp_conn_get_interface (priv->tp_conn,
356                                                       TELEPATHY_CONN_IFACE_PRESENCE_QUARK);
357
358         if (priv->aliasing_iface) {
359                 dbus_g_proxy_connect_signal (priv->aliasing_iface,
360                                              "AliasesChanged",
361                                              G_CALLBACK (tp_contact_list_aliases_update_cb),
362                                              list, NULL);
363         }
364
365         if (priv->avatars_iface) {
366                 dbus_g_proxy_connect_signal (priv->avatars_iface,
367                                              "AvatarUpdated",
368                                              G_CALLBACK (tp_contact_list_avatar_update_cb),
369                                              list, NULL);
370         }
371
372         if (priv->presence_iface) {
373                 dbus_g_proxy_connect_signal (priv->presence_iface,
374                                              "PresenceUpdate",
375                                              G_CALLBACK (tp_contact_list_presence_update_cb),
376                                              list, NULL);
377         }
378
379         /* Get our own handle and contact */
380         if (!tp_conn_get_self_handle (DBUS_G_PROXY (priv->tp_conn),
381                                       &handle, &error)) {
382                 gossip_debug (DEBUG_DOMAIN, "GetSelfHandle Error: %s",
383                               error ? error->message : "No error given");
384                 g_clear_error (&error);
385         } else {
386                 priv->user_contact = empathy_tp_contact_list_get_from_handle (list, handle);
387         }
388
389         return list;
390 }
391
392 static void
393 tp_contact_list_setup (EmpathyContactList *list)
394 {
395         EmpathyTpContactListPriv *priv;
396         GPtrArray                *channels;
397         GError                   *error = NULL;
398         guint                     i;
399
400         g_return_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list));
401
402         priv = GET_PRIV (list);
403
404         gossip_debug (DEBUG_DOMAIN, "setup contact list: %p", list);
405
406         priv->setup = TRUE;
407         dbus_g_proxy_connect_signal (DBUS_G_PROXY (priv->tp_conn), "NewChannel",
408                                      G_CALLBACK (tp_contact_list_newchannel_cb),
409                                      list, NULL);
410
411         /* Get existing channels */
412         if (!tp_conn_list_channels (DBUS_G_PROXY (priv->tp_conn),
413                                     &channels,
414                                     &error)) {
415                 gossip_debug (DEBUG_DOMAIN,
416                               "Failed to get list of open channels: %s",
417                               error ? error->message : "No error given");
418                 g_clear_error (&error);
419                 return;
420         }
421
422         for (i = 0; channels->len > i; i++) {
423                 GValueArray         *chan_struct;
424                 const gchar         *object_path;
425                 const gchar         *chan_iface;
426                 TelepathyHandleType  handle_type;
427                 guint                handle;
428
429                 chan_struct = g_ptr_array_index (channels, i);
430                 object_path = g_value_get_boxed (g_value_array_get_nth (chan_struct, 0));
431                 chan_iface = g_value_get_string (g_value_array_get_nth (chan_struct, 1));
432                 handle_type = g_value_get_uint (g_value_array_get_nth (chan_struct, 2));
433                 handle = g_value_get_uint (g_value_array_get_nth (chan_struct, 3));
434
435                 tp_contact_list_newchannel_cb (DBUS_G_PROXY (priv->tp_conn),
436                                                object_path, chan_iface,
437                                                handle_type, handle,
438                                                FALSE,
439                                                EMPATHY_TP_CONTACT_LIST (list));
440
441                 g_value_array_free (chan_struct);
442         }
443
444         g_ptr_array_free (channels, TRUE);
445 }
446
447 static GossipContact *
448 tp_contact_list_find (EmpathyContactList *list,
449                       const gchar        *id)
450 {
451         EmpathyTpContactListPriv *priv;
452
453         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list), NULL);
454
455         priv = GET_PRIV (list);
456
457         return g_hash_table_find (priv->contacts,
458                                   (GHRFunc) tp_contact_list_find_foreach,
459                                   (gchar*) id);
460 }
461
462 static void
463 tp_contact_list_add (EmpathyContactList *list,
464                      GossipContact      *contact,
465                      const gchar        *message)
466 {
467         EmpathyTpContactListPriv *priv;
468         guint                     handle;
469
470         g_return_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list));
471
472         priv = GET_PRIV (list);
473
474         handle = gossip_contact_get_handle (contact);
475         gossip_telepathy_group_add_member (priv->subscribe, handle, message);
476 }
477
478 static void
479 tp_contact_list_remove (EmpathyContactList *list,
480                         GossipContact      *contact,
481                         const gchar        *message)
482 {
483         EmpathyTpContactListPriv *priv;
484         guint                     handle;
485
486         g_return_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list));
487
488         priv = GET_PRIV (list);
489
490         handle = gossip_contact_get_handle (contact);
491         gossip_telepathy_group_remove_member (priv->subscribe, handle, message);
492         gossip_telepathy_group_remove_member (priv->publish, handle, message);
493         gossip_telepathy_group_remove_member (priv->known, handle, message);
494 }
495
496 static GList *
497 tp_contact_list_get_contacts (EmpathyContactList *list)
498 {
499         EmpathyTpContactListPriv *priv;
500         GList                    *contacts = NULL;
501
502         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list), NULL);
503
504         priv = GET_PRIV (list);
505
506         /* FIXME: we should only return contacts that are in the contact list */
507         g_hash_table_foreach (priv->contacts,
508                               (GHFunc) tp_contact_list_get_contacts_foreach,
509                               &contacts);
510
511         return contacts;
512 }
513
514 McAccount *
515 empathy_tp_contact_list_get_account (EmpathyTpContactList *list)
516 {
517         EmpathyTpContactListPriv *priv;
518
519         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list), NULL);
520
521         priv = GET_PRIV (list);
522
523         return priv->account;
524 }
525
526 GossipContact *
527 empathy_tp_contact_list_get_user (EmpathyTpContactList *list)
528 {
529         EmpathyTpContactListPriv *priv;
530
531         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list), NULL);
532
533         priv = GET_PRIV (list);
534         
535         return priv->user_contact;
536 }
537
538 GossipContact *
539 empathy_tp_contact_list_get_from_id (EmpathyTpContactList *list,
540                                      const gchar          *id)
541 {
542         EmpathyTpContactListPriv *priv;
543         GossipContact            *contact;
544         const gchar              *contact_ids[] = {id, NULL};
545         GArray                   *handles;
546         guint                     handle;
547         GError                   *error = NULL;
548
549         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list), NULL);
550         g_return_val_if_fail (id != NULL, NULL);
551         
552         priv = GET_PRIV (list);
553
554         contact = tp_contact_list_find (EMPATHY_CONTACT_LIST (list), id);
555         if (contact) {
556                 return contact;
557         }
558
559         /* The id is unknown, requests a new handle */
560         if (!tp_conn_request_handles (DBUS_G_PROXY (priv->tp_conn),
561                                       TP_HANDLE_TYPE_CONTACT,
562                                       contact_ids,
563                                       &handles, &error)) {
564                 gossip_debug (DEBUG_DOMAIN, 
565                               "RequestHandle for %s failed: %s", id,
566                               error ? error->message : "No error given");
567                 g_clear_error (&error);
568                 return 0;
569         }
570
571         handle = g_array_index(handles, guint, 0);
572         g_array_free (handles, TRUE);
573
574         return empathy_tp_contact_list_get_from_handle (list, handle);
575 }
576
577 GossipContact *
578 empathy_tp_contact_list_get_from_handle (EmpathyTpContactList *list,
579                                          guint                 handle)
580 {
581         GossipContact *contact;
582         GArray        *handles;
583         GList         *contacts;
584
585         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list), NULL);
586
587         handles = g_array_new (FALSE, FALSE, sizeof (guint));
588         g_array_append_val (handles, handle);
589
590         contacts = empathy_tp_contact_list_get_from_handles (list, handles);
591         g_array_free (handles, TRUE);
592
593         if (!contacts) {
594                 return NULL;
595         }
596
597         contact = contacts->data;
598         g_list_free (contacts);
599
600         return contact;
601 }
602
603 GList *
604 empathy_tp_contact_list_get_from_handles (EmpathyTpContactList *list,
605                                           GArray               *handles)
606 {
607         EmpathyTpContactListPriv  *priv;
608         gchar                    **handles_names;
609         gchar                    **id;
610         GArray                    *new_handles;
611         GList                     *contacts = NULL;
612         guint                      i;
613         GError                    *error = NULL;
614
615         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list), NULL);
616         g_return_val_if_fail (handles != NULL, NULL);
617
618         priv = GET_PRIV (list);
619
620         /* Search all handles we already have */
621         new_handles = g_array_new (FALSE, FALSE, sizeof (guint));
622         for (i = 0; i < handles->len; i++) {
623                 GossipContact *contact;
624                 guint          handle;
625
626                 handle = g_array_index (handles, guint, i);
627
628                 if (handle == 0) {
629                         continue;
630                 }
631
632                 contact = g_hash_table_lookup (priv->contacts,
633                                                GUINT_TO_POINTER (handle));
634
635                 if (contact) {
636                         contacts = g_list_prepend (contacts,
637                                                    g_object_ref (contact));
638                 } else {
639                         g_array_append_val (new_handles, handle);
640                 }
641         }
642
643         if (new_handles->len == 0) {
644                 return contacts;
645         }
646
647         /* Holds all handles we don't have yet.
648          * FIXME: We should release them at some point. */
649         if (!tp_conn_hold_handles (DBUS_G_PROXY (priv->tp_conn),
650                                    TP_HANDLE_TYPE_CONTACT,
651                                    new_handles, &error)) {
652                 gossip_debug (DEBUG_DOMAIN, 
653                               "HoldHandles Error: %s",
654                               error ? error->message : "No error given");
655                 g_clear_error (&error);
656                 g_array_free (new_handles, TRUE);
657                 return contacts;
658         }
659
660         /* Get the IDs of all new handles */
661         if (!tp_conn_inspect_handles (DBUS_G_PROXY (priv->tp_conn),
662                                       TP_HANDLE_TYPE_CONTACT,
663                                       new_handles,
664                                       &handles_names,
665                                       &error)) {
666                 gossip_debug (DEBUG_DOMAIN, 
667                               "InspectHandle Error: %s",
668                               error ? error->message : "No error given");
669                 g_clear_error (&error);
670                 g_array_free (new_handles, TRUE);
671                 return contacts;
672         }
673
674         /* Create contact objects */
675         for (i = 0, id = handles_names; *id && i < new_handles->len; id++, i++) {
676                 GossipContact *contact;
677                 guint          handle;
678
679                 handle = g_array_index (new_handles, guint, i);
680                 contact = g_object_new (GOSSIP_TYPE_CONTACT,
681                                         "account", priv->account,
682                                         "id", *id,
683                                         "handle", handle,
684                                         NULL);
685
686                 g_signal_connect (contact, "notify::groups",
687                                   G_CALLBACK (tp_contact_list_groups_updated_cb),
688                                   list);
689                 g_signal_connect (contact, "notify::subscription",
690                                   G_CALLBACK (tp_contact_list_subscription_updated_cb),
691                                   list);
692                 g_signal_connect (contact, "notify::name",
693                                   G_CALLBACK (tp_contact_list_name_updated_cb),
694                                   list);
695
696                 gossip_debug (DEBUG_DOMAIN, "new contact created: %s (%d)",
697                               *id, handle);
698
699                 g_hash_table_insert (priv->contacts,
700                                      GUINT_TO_POINTER (handle),
701                                      contact);
702
703                 contacts = g_list_prepend (contacts, g_object_ref (contact));
704         }
705
706         tp_contact_list_get_info (list, new_handles);
707
708         g_array_free (new_handles, TRUE);
709         g_strfreev (handles_names);
710
711         return contacts;
712 }
713
714 void
715 empathy_tp_contact_list_rename_group (EmpathyTpContactList *list,
716                                       const gchar          *old_group,
717                                       const gchar          *new_group)
718 {
719         EmpathyTpContactListPriv *priv;
720         GossipTelepathyGroup     *group;
721         GArray                   *members;
722
723         g_return_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list));
724         g_return_if_fail (old_group != NULL);
725         g_return_if_fail (new_group != NULL);
726
727         priv = GET_PRIV (list);
728
729         group = g_hash_table_find (priv->groups,
730                                    (GHRFunc) tp_contact_list_find_group,
731                                    (gchar*) old_group);
732         if (!group) {
733                 /* The group doesn't exists on this account */
734                 return;
735         }
736
737         gossip_debug (DEBUG_DOMAIN, "rename group %s to %s", group, new_group);
738
739         /* Remove all members from the old group */
740         members = gossip_telepathy_group_get_members (group);
741         gossip_telepathy_group_remove_members (group, members, "");
742         tp_contact_list_group_members_removed_cb (group, members, 
743                                                0, 
744                                                TP_CHANNEL_GROUP_CHANGE_REASON_NONE, 
745                                                NULL, list);
746         g_hash_table_remove (priv->groups,
747                              gossip_telepathy_group_get_object_path (group));
748
749         /* Add all members to the new group */
750         group = tp_contact_list_get_group (list, new_group);
751         if (group) {
752                 gossip_telepathy_group_add_members (group, members, "");
753         }
754 }
755
756 GList *
757 empathy_tp_contact_list_get_groups (EmpathyTpContactList *list)
758 {
759         EmpathyTpContactListPriv *priv;
760         GList                    *groups = NULL;
761
762         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_LIST (list), NULL);
763
764         priv = GET_PRIV (list);
765
766         g_hash_table_foreach (priv->groups,
767                               (GHFunc) tp_contact_list_get_groups_foreach,
768                               &groups);
769
770         groups = g_list_sort (groups, (GCompareFunc) strcmp);
771
772         return groups;
773 }
774
775 static void
776 tp_contact_list_finalize_proxies (EmpathyTpContactList *list)
777 {
778         EmpathyTpContactListPriv *priv;
779
780         priv = GET_PRIV (list);
781
782         if (priv->tp_conn) {
783                 g_signal_handlers_disconnect_by_func (priv->tp_conn,
784                                                       tp_contact_list_destroy_cb,
785                                                       list);
786                 dbus_g_proxy_disconnect_signal (DBUS_G_PROXY (priv->tp_conn), "NewChannel",
787                                                 G_CALLBACK (tp_contact_list_newchannel_cb),
788                                                 list);
789         }
790
791         if (priv->aliasing_iface) {
792                 dbus_g_proxy_disconnect_signal (priv->aliasing_iface,
793                                                 "AliasesChanged",
794                                                 G_CALLBACK (tp_contact_list_aliases_update_cb),
795                                                 list);
796         }
797
798         if (priv->avatars_iface) {
799                 dbus_g_proxy_disconnect_signal (priv->avatars_iface,
800                                                 "AvatarUpdated",
801                                                 G_CALLBACK (tp_contact_list_avatar_update_cb),
802                                                 list);
803         }
804
805         if (priv->presence_iface) {
806                 dbus_g_proxy_disconnect_signal (priv->presence_iface,
807                                                 "PresenceUpdate",
808                                                 G_CALLBACK (tp_contact_list_presence_update_cb),
809                                                 list);
810         }
811 }
812
813 static void
814 tp_contact_list_destroy_cb (DBusGProxy           *proxy,
815                             EmpathyTpContactList *list)
816 {
817         EmpathyTpContactListPriv *priv;
818
819         priv = GET_PRIV (list);
820
821         gossip_debug (DEBUG_DOMAIN, "Connection destroyed... "
822                       "Account disconnected or CM crashed");
823
824         /* DBus proxies should NOT be used anymore */
825         g_object_unref (priv->tp_conn);
826         priv->tp_conn = NULL;
827         priv->aliasing_iface = NULL;
828         priv->avatars_iface = NULL;
829         priv->presence_iface = NULL;
830
831         /* Remove all contacts */
832         g_hash_table_foreach (priv->contacts,
833                               (GHFunc) tp_contact_list_contact_removed_foreach,
834                               list);
835         g_hash_table_remove_all (priv->contacts);
836
837         /* Tell the world to not use us anymore */
838         g_signal_emit (list, signals[DESTROY], 0);
839 }
840
841 static void
842 tp_contact_list_contact_removed_foreach (guint                 handle,
843                                          GossipContact        *contact,
844                                          EmpathyTpContactList *list)
845 {
846         g_signal_handlers_disconnect_by_func (contact,
847                                               tp_contact_list_groups_updated_cb,
848                                               list);
849         g_signal_handlers_disconnect_by_func (contact,
850                                               tp_contact_list_subscription_updated_cb,
851                                               list);
852         g_signal_handlers_disconnect_by_func (contact,
853                                               tp_contact_list_name_updated_cb,
854                                               list);
855
856         g_signal_emit_by_name (list, "contact-removed", contact);
857 }
858
859 static void
860 tp_contact_list_block_contact (EmpathyTpContactList *list,
861                                GossipContact        *contact)
862 {
863         g_signal_handlers_block_by_func (contact,
864                                          tp_contact_list_groups_updated_cb,
865                                          list);
866         g_signal_handlers_block_by_func (contact,
867                                          tp_contact_list_subscription_updated_cb,
868                                          list);
869         g_signal_handlers_block_by_func (contact,
870                                          tp_contact_list_name_updated_cb,
871                                          list);
872 }
873
874 static void
875 tp_contact_list_unblock_contact (EmpathyTpContactList *list,
876                                  GossipContact        *contact)
877 {
878         g_signal_handlers_unblock_by_func (contact,
879                                            tp_contact_list_groups_updated_cb,
880                                            list);
881         g_signal_handlers_unblock_by_func (contact,
882                                            tp_contact_list_subscription_updated_cb,
883                                            list);
884         g_signal_handlers_unblock_by_func (contact,
885                                            tp_contact_list_name_updated_cb,
886                                            list);
887 }
888
889 static gboolean
890 tp_contact_list_find_foreach (guint          handle,
891                               GossipContact *contact,
892                               gchar         *id)
893 {
894         if (strcmp (gossip_contact_get_id (contact), id) == 0) {
895                 return TRUE;
896         }
897
898         return FALSE;
899 }
900
901 static void
902 tp_contact_list_newchannel_cb (DBusGProxy           *proxy,
903                                const gchar          *object_path,
904                                const gchar          *channel_type,
905                                TelepathyHandleType   handle_type,
906                                guint                 channel_handle,
907                                gboolean              suppress_handle,
908                                EmpathyTpContactList *list)
909 {
910         EmpathyTpContactListPriv *priv;
911         GossipTelepathyGroup     *group;
912         TpChan                   *new_chan;
913         const gchar              *bus_name;
914         GArray                   *members;
915
916         priv = GET_PRIV (list);
917
918         if (strcmp (channel_type, TP_IFACE_CHANNEL_TYPE_CONTACT_LIST) != 0 ||
919             suppress_handle ||
920             !priv->setup) {
921                 return;
922         }
923
924         bus_name = dbus_g_proxy_get_bus_name (DBUS_G_PROXY (priv->tp_conn));
925         new_chan = tp_chan_new (tp_get_bus (),
926                                 bus_name,
927                                 object_path,
928                                 channel_type, handle_type, channel_handle);
929
930         if (handle_type == TP_HANDLE_TYPE_LIST) {
931                 TpContactListType list_type;
932
933                 list_type = tp_contact_list_get_type (list, new_chan);
934                 if (list_type == TP_CONTACT_LIST_TYPE_UNKNOWN) {
935                         gossip_debug (DEBUG_DOMAIN, "Unknown contact list channel");
936                         g_object_unref (new_chan);
937                         return;
938                 }
939
940                 gossip_debug (DEBUG_DOMAIN, "New contact list channel of type: %d",
941                               list_type);
942
943                 group = gossip_telepathy_group_new (new_chan, priv->tp_conn);
944
945                 switch (list_type) {
946                 case TP_CONTACT_LIST_TYPE_KNOWN:
947                         if (priv->known) {
948                                 g_object_unref (priv->known);
949                         }
950                         priv->known = group;
951                         break;
952                 case TP_CONTACT_LIST_TYPE_PUBLISH:
953                         if (priv->publish) {
954                                 g_object_unref (priv->publish);
955                         }
956                         priv->publish = group;
957                         break;
958                 case TP_CONTACT_LIST_TYPE_SUBSCRIBE:
959                         if (priv->subscribe) {
960                                 g_object_unref (priv->subscribe);
961                         }
962                         priv->subscribe = group;
963                         break;
964                 default:
965                         g_assert_not_reached ();
966                 }
967
968                 /* Connect and setup the new contact-list group */
969                 if (list_type == TP_CONTACT_LIST_TYPE_KNOWN ||
970                     list_type == TP_CONTACT_LIST_TYPE_SUBSCRIBE) {
971                         g_signal_connect (group, "members-added",
972                                           G_CALLBACK (tp_contact_list_contact_added_cb),
973                                           list);
974                         g_signal_connect (group, "members-removed",
975                                           G_CALLBACK (tp_contact_list_contact_removed_cb),
976                                           list);
977
978                         members = gossip_telepathy_group_get_members (group);
979                         tp_contact_list_contact_added_cb (group, members, 0,
980                                                        TP_CHANNEL_GROUP_CHANGE_REASON_NONE,
981                                                        NULL, list);
982                         g_array_free (members, TRUE);
983                 }
984                 if (list_type == TP_CONTACT_LIST_TYPE_PUBLISH) {
985                         GList  *members, *l;
986                         GArray *pending;
987
988                         g_signal_connect (group, "local-pending",
989                                           G_CALLBACK (tp_contact_list_local_pending_cb),
990                                           list);
991
992                         members = gossip_telepathy_group_get_local_pending_members_with_info (group);
993                         if (!members) {
994                                 g_object_unref (new_chan);
995                                 return;
996                         }
997
998                         pending = g_array_sized_new (FALSE, FALSE, sizeof (guint), 1);
999                         for (l = members; l; l = l->next) {
1000                                 GossipTpGroupInfo *info;
1001
1002                                 info = l->data;
1003
1004                                 g_array_insert_val (pending, 0, info->member);
1005                                 tp_contact_list_local_pending_cb (group, pending,
1006                                                                   info->actor,
1007                                                                   info->reason,
1008                                                                   info->message,
1009                                                                   list);
1010                         }
1011
1012                         gossip_telepathy_group_info_list_free (members);
1013                         g_array_free (pending, TRUE);
1014                 }
1015         }
1016         else if (handle_type == TP_HANDLE_TYPE_GROUP) {
1017                 const gchar *object_path;
1018
1019                 object_path = dbus_g_proxy_get_path (DBUS_G_PROXY (new_chan));
1020                 if (g_hash_table_lookup (priv->groups, object_path)) {
1021                         g_object_unref (new_chan);
1022                         return;
1023                 }
1024
1025                 group = gossip_telepathy_group_new (new_chan, priv->tp_conn);
1026
1027                 gossip_debug (DEBUG_DOMAIN, "New server-side group channel: %s",
1028                               gossip_telepathy_group_get_name (group));
1029
1030                 dbus_g_proxy_connect_signal (DBUS_G_PROXY (new_chan), "Closed",
1031                                              G_CALLBACK
1032                                              (tp_contact_list_group_channel_closed_cb),
1033                                              list, NULL);
1034
1035                 g_hash_table_insert (priv->groups, g_strdup (object_path), group);
1036                 g_signal_connect (group, "members-added",
1037                                   G_CALLBACK (tp_contact_list_group_members_added_cb),
1038                                   list);
1039                 g_signal_connect (group, "members-removed",
1040                                   G_CALLBACK (tp_contact_list_group_members_removed_cb),
1041                                   list);
1042
1043                 members = gossip_telepathy_group_get_members (group);
1044                 tp_contact_list_group_members_added_cb (group, members, 0,
1045                                                      TP_CHANNEL_GROUP_CHANGE_REASON_NONE,
1046                                                      NULL, list);
1047                 g_array_free (members, TRUE);
1048         }
1049
1050         g_object_unref (new_chan);
1051 }
1052
1053 static TpContactListType
1054 tp_contact_list_get_type (EmpathyTpContactList *list,
1055                           TpChan               *list_chan)
1056 {
1057         EmpathyTpContactListPriv  *priv;
1058         GArray                    *handles;
1059         gchar                    **handle_name;
1060         TpContactListType          list_type;
1061         GError                    *error = NULL;
1062
1063         priv = GET_PRIV (list);
1064
1065         handles = g_array_new (FALSE, FALSE, sizeof (guint));
1066         g_array_append_val (handles, list_chan->handle);
1067
1068         if (!tp_conn_inspect_handles (DBUS_G_PROXY (priv->tp_conn),
1069                                       TP_HANDLE_TYPE_LIST,
1070                                       handles,
1071                                       &handle_name,
1072                                       &error)) {
1073                 gossip_debug (DEBUG_DOMAIN, 
1074                               "InspectHandle Error: %s",
1075                               error ? error->message : "No error given");
1076                 g_clear_error (&error);
1077                 g_array_free (handles, TRUE);
1078                 return TP_CONTACT_LIST_TYPE_UNKNOWN;
1079         }
1080
1081         if (strcmp (*handle_name, "subscribe") == 0) {
1082                 list_type = TP_CONTACT_LIST_TYPE_SUBSCRIBE;
1083         } else if (strcmp (*handle_name, "publish") == 0) {
1084                 list_type = TP_CONTACT_LIST_TYPE_PUBLISH;
1085         } else if (strcmp (*handle_name, "known") == 0) {
1086                 list_type = TP_CONTACT_LIST_TYPE_KNOWN;
1087         } else {
1088                 list_type = TP_CONTACT_LIST_TYPE_UNKNOWN;
1089         }
1090
1091         g_strfreev (handle_name);
1092         g_array_free (handles, TRUE);
1093
1094         return list_type;
1095 }
1096
1097 static void
1098 tp_contact_list_contact_added_cb (GossipTelepathyGroup *group,
1099                                   GArray               *handles,
1100                                   guint                 actor_handle,
1101                                   guint                 reason,
1102                                   const gchar          *message,
1103                                   EmpathyTpContactList *list)
1104 {
1105         EmpathyTpContactListPriv *priv;
1106         GList                    *added_list, *l;
1107
1108         priv = GET_PRIV (list);
1109
1110         added_list = empathy_tp_contact_list_get_from_handles (list, handles);
1111
1112         for (l = added_list; l; l = l->next) {
1113                 GossipContact *contact;
1114
1115                 contact = GOSSIP_CONTACT (l->data);
1116                 tp_contact_list_block_contact (list, contact);
1117                 gossip_contact_set_subscription (contact, GOSSIP_SUBSCRIPTION_BOTH);
1118                 tp_contact_list_unblock_contact (list, contact);
1119
1120                 g_signal_emit_by_name (list, "contact-added", contact);
1121
1122                 g_object_unref (contact);
1123         }
1124
1125         g_list_free (added_list);
1126 }
1127
1128 static void
1129 tp_contact_list_contact_removed_cb (GossipTelepathyGroup *group,
1130                                     GArray               *handles,
1131                                     guint                 actor_handle,
1132                                     guint                 reason,
1133                                     const gchar          *message,
1134                                     EmpathyTpContactList *list)
1135 {
1136         EmpathyTpContactListPriv *priv;
1137         GList                    *removed_list, *l;
1138
1139         priv = GET_PRIV (list);
1140
1141         removed_list = empathy_tp_contact_list_get_from_handles (list, handles);
1142
1143         for (l = removed_list; l; l = l->next) {
1144                 GossipContact *contact;
1145                 guint          handle;
1146
1147                 contact = GOSSIP_CONTACT (l->data);
1148
1149                 handle = gossip_contact_get_handle (contact);
1150                 g_hash_table_remove (priv->contacts, GUINT_TO_POINTER (handle));
1151
1152                 g_signal_emit_by_name (list, "contact-removed", contact);
1153
1154                 g_object_unref (contact);
1155         }
1156
1157         g_list_free (removed_list);
1158 }
1159
1160 static void
1161 tp_contact_list_local_pending_cb (GossipTelepathyGroup *group,
1162                                   GArray               *handles,
1163                                   guint                 actor_handle,
1164                                   guint                 reason,
1165                                   const gchar          *message,
1166                                   EmpathyTpContactList *list)
1167 {
1168         EmpathyTpContactListPriv *priv;
1169         GList                    *pending_list, *l;
1170
1171         priv = GET_PRIV (list);
1172
1173         pending_list = empathy_tp_contact_list_get_from_handles (list, handles);
1174
1175         for (l = pending_list; l; l = l->next) {
1176                 GossipContact *contact;
1177
1178                 contact = GOSSIP_CONTACT (l->data);
1179
1180                 /* FIXME: Is that the correct way ? */
1181                 tp_contact_list_block_contact (list, contact);
1182                 gossip_contact_set_subscription (contact, GOSSIP_SUBSCRIPTION_FROM);
1183                 tp_contact_list_unblock_contact (list, contact);
1184                 g_signal_emit_by_name (list, "contact-added", contact);
1185
1186                 g_object_unref (contact);
1187         }
1188
1189         g_list_free (pending_list);
1190 }
1191
1192 static void
1193 tp_contact_list_groups_updated_cb (GossipContact        *contact,
1194                                    GParamSpec           *param,
1195                                    EmpathyTpContactList *list)
1196 {
1197         EmpathyTpContactListPriv *priv;
1198         TpContactListData         data;
1199         GList                    *groups, *l;
1200
1201         priv = GET_PRIV (list);
1202
1203         /* Make sure all groups are created */
1204         groups = gossip_contact_get_groups (contact);
1205         for (l = groups; l; l = l->next) {
1206                 tp_contact_list_get_group (list, l->data);
1207         }
1208
1209         data.handle = gossip_contact_get_handle (contact);
1210         data.new_groups = groups;
1211
1212         g_hash_table_foreach (priv->groups,
1213                               (GHFunc) tp_contact_list_update_groups_foreach,
1214                               &data);
1215 }
1216
1217 static void
1218 tp_contact_list_subscription_updated_cb (GossipContact        *contact,
1219                                          GParamSpec           *param,
1220                                          EmpathyTpContactList *list)
1221 {
1222         EmpathyTpContactListPriv *priv;
1223         GossipSubscription        subscription;
1224         guint                     handle;
1225
1226         priv = GET_PRIV (list);
1227
1228         subscription = gossip_contact_get_subscription (contact);
1229         handle = gossip_contact_get_handle (contact);
1230
1231         /* FIXME: what to do here, I'm a bit lost... */
1232         if (subscription) {
1233                 gossip_telepathy_group_add_member (priv->publish, handle, "");
1234         } else {
1235                 gossip_telepathy_group_remove_member (priv->publish, handle, "");
1236         }
1237 }
1238
1239 static void
1240 tp_contact_list_name_updated_cb (GossipContact        *contact,
1241                                  GParamSpec           *param,
1242                                  EmpathyTpContactList *list)
1243 {
1244         EmpathyTpContactListPriv *priv;
1245         GHashTable               *new_alias;
1246         const gchar              *new_name;
1247         guint                     handle;
1248         GError                   *error = NULL;
1249
1250         priv = GET_PRIV (list);
1251         
1252         handle = gossip_contact_get_handle (contact);
1253         new_name = gossip_contact_get_name (contact);
1254
1255         gossip_debug (DEBUG_DOMAIN, "renaming handle %d to %s",
1256                       handle, new_name);
1257
1258         new_alias = g_hash_table_new_full (g_direct_hash,
1259                                            g_direct_equal,
1260                                            NULL,
1261                                            g_free);
1262
1263         g_hash_table_insert (new_alias,
1264                              GUINT_TO_POINTER (handle),
1265                              g_strdup (new_name));
1266
1267         if (!tp_conn_iface_aliasing_set_aliases (priv->aliasing_iface,
1268                                                  new_alias,
1269                                                  &error)) {
1270                 gossip_debug (DEBUG_DOMAIN, 
1271                               "Couldn't rename contact: %s",
1272                               error ? error->message : "No error given");
1273                 g_clear_error (&error);
1274         }
1275
1276         g_hash_table_destroy (new_alias);
1277 }
1278
1279 static void
1280 tp_contact_list_update_groups_foreach (gchar                *object_path,
1281                                        GossipTelepathyGroup *group,
1282                                        TpContactListData    *data)
1283 {
1284         gboolean     is_member;
1285         gboolean     found = FALSE;
1286         const gchar *group_name;
1287         GList       *l;
1288
1289         is_member = gossip_telepathy_group_is_member (group, data->handle);
1290         group_name = gossip_telepathy_group_get_name (group);
1291
1292         for (l = data->new_groups; l; l = l->next) {
1293                 if (strcmp (group_name, l->data) == 0) {
1294                         found = TRUE;
1295                         break;
1296                 }
1297         }
1298
1299         if (is_member && !found) {
1300                 /* We are no longer member of this group */
1301                 gossip_debug (DEBUG_DOMAIN, "Contact %d removed from group '%s'",
1302                               data->handle, group_name);
1303                 gossip_telepathy_group_remove_member (group, data->handle, "");
1304         }
1305
1306         if (!is_member && found) {
1307                 /* We are now member of this group */
1308                 gossip_debug (DEBUG_DOMAIN, "Contact %d added to group '%s'",
1309                               data->handle, group_name);
1310                 gossip_telepathy_group_add_member (group, data->handle, "");
1311         }
1312 }
1313
1314 static GossipTelepathyGroup *
1315 tp_contact_list_get_group (EmpathyTpContactList *list,
1316                            const gchar          *name)
1317 {
1318         EmpathyTpContactListPriv *priv;
1319         GossipTelepathyGroup     *group;
1320         TpChan                   *group_channel;
1321         GArray                   *handles;
1322         guint                     group_handle;
1323         char                     *group_object_path;
1324         const char               *names[2] = {name, NULL};
1325         GError                   *error = NULL;
1326
1327         priv = GET_PRIV (list);
1328
1329         group = g_hash_table_find (priv->groups,
1330                                    (GHRFunc) tp_contact_list_find_group,
1331                                    (gchar*) name);
1332         if (group) {
1333                 return group;
1334         }
1335
1336         gossip_debug (DEBUG_DOMAIN, "creating new group: %s", name);
1337
1338         if (!tp_conn_request_handles (DBUS_G_PROXY (priv->tp_conn),
1339                                       TP_HANDLE_TYPE_GROUP,
1340                                       names,
1341                                       &handles,
1342                                       &error)) {
1343                 gossip_debug (DEBUG_DOMAIN,
1344                               "Couldn't request the creation of a new handle for group: %s",
1345                               error ? error->message : "No error given");
1346                 g_clear_error (&error);
1347                 return NULL;
1348         }
1349         group_handle = g_array_index (handles, guint, 0);
1350         g_array_free (handles, TRUE);
1351
1352         if (!tp_conn_request_channel (DBUS_G_PROXY (priv->tp_conn),
1353                                       TP_IFACE_CHANNEL_TYPE_CONTACT_LIST,
1354                                       TP_HANDLE_TYPE_GROUP,
1355                                       group_handle,
1356                                       FALSE,
1357                                       &group_object_path,
1358                                       &error)) {
1359                 gossip_debug (DEBUG_DOMAIN,
1360                               "Couldn't request the creation of a new group channel: %s",
1361                               error ? error->message : "No error given");
1362                 g_clear_error (&error);
1363                 return NULL;
1364         }
1365
1366         group_channel = tp_chan_new (tp_get_bus (),
1367                                      dbus_g_proxy_get_bus_name (DBUS_G_PROXY (priv->tp_conn)),
1368                                      group_object_path,
1369                                      TP_IFACE_CHANNEL_TYPE_CONTACT_LIST,
1370                                      TP_HANDLE_TYPE_GROUP,
1371                                      group_handle);
1372
1373         dbus_g_proxy_connect_signal (DBUS_G_PROXY (group_channel),
1374                                      "Closed",
1375                                      G_CALLBACK
1376                                      (tp_contact_list_group_channel_closed_cb),
1377                                      list,
1378                                      NULL);
1379
1380         group = gossip_telepathy_group_new (group_channel, priv->tp_conn);
1381         g_hash_table_insert (priv->groups, group_object_path, group);
1382         g_signal_connect (group, "members-added",
1383                           G_CALLBACK (tp_contact_list_group_members_added_cb),
1384                           list);
1385         g_signal_connect (group, "members-removed",
1386                           G_CALLBACK (tp_contact_list_group_members_removed_cb),
1387                           list);
1388
1389         return group;
1390 }
1391
1392 static gboolean
1393 tp_contact_list_find_group (gchar                 *key,
1394                             GossipTelepathyGroup  *group,
1395                             gchar                 *group_name)
1396 {
1397         if (strcmp (group_name, gossip_telepathy_group_get_name (group)) == 0) {
1398                 return TRUE;
1399         }
1400
1401         return FALSE;
1402 }
1403
1404 static void
1405 tp_contact_list_get_groups_foreach (gchar                 *key,
1406                                     GossipTelepathyGroup  *group,
1407                                     GList                **groups)
1408 {
1409         const gchar *name;
1410
1411         name = gossip_telepathy_group_get_name (group);
1412         *groups = g_list_append (*groups, g_strdup (name));
1413 }
1414
1415 static void
1416 tp_contact_list_group_channel_closed_cb (TpChan             *channel,
1417                                          EmpathyTpContactList *list)
1418 {
1419         EmpathyTpContactListPriv *priv;
1420
1421         priv = GET_PRIV (list);
1422
1423         g_hash_table_remove (priv->groups,
1424                              dbus_g_proxy_get_path (DBUS_G_PROXY (channel)));
1425 }
1426
1427 static void
1428 tp_contact_list_group_members_added_cb (GossipTelepathyGroup *group,
1429                                         GArray               *members,
1430                                         guint                 actor_handle,
1431                                         guint                 reason,
1432                                         const gchar          *message,
1433                                         EmpathyTpContactList *list)
1434 {
1435         EmpathyTpContactListPriv *priv;
1436         GList                    *added_list, *l;
1437         const gchar              *group_name;
1438
1439         priv = GET_PRIV (list);
1440
1441         group_name = gossip_telepathy_group_get_name (group);
1442         added_list = empathy_tp_contact_list_get_from_handles (list, members);
1443
1444         for (l = added_list; l; l = l->next) {
1445                 GossipContact *contact;
1446                 GList         *contact_groups;
1447
1448                 contact = GOSSIP_CONTACT (l->data);
1449                 contact_groups = gossip_contact_get_groups (contact);
1450
1451                 if (!g_list_find_custom (contact_groups,
1452                                          group_name,
1453                                          (GCompareFunc) strcmp)) {
1454                         gossip_debug (DEBUG_DOMAIN, "Contact %s added to group '%s'",
1455                                       gossip_contact_get_name (contact),
1456                                       group_name);
1457                         contact_groups = g_list_append (contact_groups,
1458                                                         g_strdup (group_name));
1459                         tp_contact_list_block_contact (list, contact);
1460                         gossip_contact_set_groups (contact, contact_groups);
1461                         tp_contact_list_unblock_contact (list, contact);
1462                 }
1463
1464                 g_object_unref (contact);
1465         }
1466
1467         g_list_free (added_list);
1468 }
1469
1470 static void
1471 tp_contact_list_group_members_removed_cb (GossipTelepathyGroup *group,
1472                                           GArray               *members,
1473                                           guint                 actor_handle,
1474                                           guint                 reason,
1475                                           const gchar          *message,
1476                                           EmpathyTpContactList *list)
1477 {
1478         EmpathyTpContactListPriv *priv;
1479         GList                    *removed_list, *l;
1480         const gchar              *group_name;
1481
1482         priv = GET_PRIV (list);
1483
1484         group_name = gossip_telepathy_group_get_name (group);
1485         removed_list = empathy_tp_contact_list_get_from_handles (list, members);
1486
1487         for (l = removed_list; l; l = l->next) {
1488                 GossipContact *contact;
1489                 GList         *contact_groups;
1490                 GList         *to_remove;
1491
1492                 /* FIXME: Does it leak ? */
1493                 contact = GOSSIP_CONTACT (l->data);
1494                 contact_groups = gossip_contact_get_groups (contact);
1495                 contact_groups = g_list_copy (contact_groups);
1496
1497                 to_remove = g_list_find_custom (contact_groups,
1498                                                 group_name,
1499                                                 (GCompareFunc) strcmp);
1500                 if (to_remove) {
1501                         gossip_debug (DEBUG_DOMAIN, "Contact %d removed from group '%s'",
1502                                       gossip_contact_get_handle (contact),
1503                                       group_name);
1504                         contact_groups = g_list_remove_link (contact_groups,
1505                                                              to_remove);
1506                         tp_contact_list_block_contact (list, contact);
1507                         gossip_contact_set_groups (contact, contact_groups);
1508                         tp_contact_list_unblock_contact (list, contact);
1509                 }
1510
1511                 g_list_free (contact_groups);
1512
1513                 g_object_unref (contact);
1514         }
1515
1516         g_list_free (removed_list);
1517 }
1518
1519 static void
1520 tp_contact_list_get_contacts_foreach (guint           handle,
1521                                       GossipContact  *contact,
1522                                       GList         **contacts)
1523 {
1524         *contacts = g_list_append (*contacts, g_object_ref (contact));
1525 }
1526
1527 static void
1528 tp_contact_list_get_info (EmpathyTpContactList *list,
1529                           GArray               *handles)
1530 {
1531         EmpathyTpContactListPriv *priv;
1532         GError                   *error = NULL;
1533
1534         priv = GET_PRIV (list);
1535
1536         if (priv->presence_iface) {
1537                 /* FIXME: We should use GetPresence instead */
1538                 if (!tp_conn_iface_presence_request_presence (priv->presence_iface,
1539                                                               handles, &error)) {
1540                         gossip_debug (DEBUG_DOMAIN, 
1541                                       "Could not request presences: %s",
1542                                       error ? error->message : "No error given");
1543                         g_clear_error (&error);
1544                 }
1545         }
1546
1547         if (priv->aliasing_iface) {
1548                 TpContactListAliasesRequestData *data;
1549
1550                 data = g_slice_new (TpContactListAliasesRequestData);
1551                 data->list = list;
1552                 data->handles = g_memdup (handles->data, handles->len * sizeof (guint));
1553
1554                 tp_conn_iface_aliasing_request_aliases_async (priv->aliasing_iface,
1555                                                               handles,
1556                                                               (tp_conn_iface_aliasing_request_aliases_reply)
1557                                                               tp_contact_list_request_aliases_cb,
1558                                                               data);
1559         }
1560
1561         if (priv->avatars_iface) {
1562                 guint i;
1563
1564                 for (i = 0; i < handles->len; i++) {
1565                         guint handle;
1566
1567                         handle = g_array_index (handles, gint, i);
1568                         tp_contact_list_request_avatar (list, handle);
1569                 }
1570         }
1571 }
1572
1573 static void
1574 tp_contact_list_request_avatar (EmpathyTpContactList *list,
1575                                 guint                 handle)
1576 {
1577         EmpathyTpContactListPriv *priv;
1578
1579         priv = GET_PRIV (list);
1580         
1581         /* We queue avatar requests to not send too many dbus async
1582          * calls at once. If we don't we reach the dbus's limit of
1583          * pending calls */
1584         priv->avatar_requests_queue = g_list_append (priv->avatar_requests_queue,
1585                                                      GUINT_TO_POINTER (handle));
1586         tp_contact_list_start_avatar_requests (list);
1587 }
1588
1589 static void
1590 tp_contact_list_start_avatar_requests (EmpathyTpContactList *list)
1591 {
1592         EmpathyTpContactListPriv       *priv;
1593         TpContactListAvatarRequestData *data;
1594
1595         priv = GET_PRIV (list);
1596
1597         while (n_avatar_requests <  MAX_AVATAR_REQUESTS &&
1598                priv->avatar_requests_queue) {
1599                 data = g_slice_new (TpContactListAvatarRequestData);
1600                 data->list = list;
1601                 data->handle = GPOINTER_TO_UINT (priv->avatar_requests_queue->data);
1602
1603                 n_avatar_requests++;
1604                 priv->avatar_requests_queue = g_list_remove (priv->avatar_requests_queue,
1605                                                              priv->avatar_requests_queue->data);
1606
1607                 tp_conn_iface_avatars_request_avatar_async (priv->avatars_iface,
1608                                                             data->handle,
1609                                                             (tp_conn_iface_avatars_request_avatar_reply)
1610                                                             tp_contact_list_request_avatar_cb,
1611                                                             data);
1612         }
1613 }
1614
1615 static void
1616 tp_contact_list_avatar_update_cb (DBusGProxy           *proxy,
1617                                   guint                 handle,
1618                                   gchar                *new_token,
1619                                   EmpathyTpContactList *list)
1620 {
1621         EmpathyTpContactListPriv *priv;
1622
1623         priv = GET_PRIV (list);
1624
1625         if (!g_hash_table_lookup (priv->contacts, GUINT_TO_POINTER (handle))) {
1626                 /* We don't know this contact, skip */
1627                 return;
1628         }
1629
1630         gossip_debug (DEBUG_DOMAIN, "Changing avatar for %d to %s",
1631                       handle, new_token);
1632
1633         tp_contact_list_request_avatar (list, handle);
1634 }
1635
1636 static void
1637 tp_contact_list_request_avatar_cb (DBusGProxy                     *proxy,
1638                                    GArray                         *avatar_data,
1639                                    gchar                          *mime_type,
1640                                    GError                         *error,
1641                                    TpContactListAvatarRequestData *data)
1642 {
1643         GossipContact *contact;
1644
1645         contact = empathy_tp_contact_list_get_from_handle (data->list, data->handle);
1646
1647         if (error) {
1648                 gossip_debug (DEBUG_DOMAIN, "Error requesting avatar for %s: %s",
1649                               gossip_contact_get_name (contact),
1650                               error ? error->message : "No error given");
1651         } else {
1652                 GossipAvatar *avatar;
1653
1654                 avatar = gossip_avatar_new (avatar_data->data,
1655                                             avatar_data->len,
1656                                             mime_type);
1657                 tp_contact_list_block_contact (data->list, contact);
1658                 gossip_contact_set_avatar (contact, avatar);
1659                 tp_contact_list_unblock_contact (data->list, contact);
1660                 gossip_avatar_unref (avatar);
1661         }
1662
1663         n_avatar_requests--;
1664         tp_contact_list_start_avatar_requests (data->list);
1665
1666         g_slice_free (TpContactListAvatarRequestData, data);
1667 }
1668
1669 static void
1670 tp_contact_list_aliases_update_cb (DBusGProxy           *proxy,
1671                                    GPtrArray            *renamed_handlers,
1672                                    EmpathyTpContactList *list)
1673 {
1674         EmpathyTpContactListPriv *priv;
1675         guint                     i;
1676
1677         priv = GET_PRIV (list);
1678
1679         for (i = 0; renamed_handlers->len > i; i++) {
1680                 guint          handle;
1681                 const gchar   *alias;
1682                 GValueArray   *renamed_struct;
1683                 GossipContact *contact;
1684
1685                 renamed_struct = g_ptr_array_index (renamed_handlers, i);
1686                 handle = g_value_get_uint(g_value_array_get_nth (renamed_struct, 0));
1687                 alias = g_value_get_string(g_value_array_get_nth (renamed_struct, 1));
1688
1689                 if (!g_hash_table_lookup (priv->contacts, GUINT_TO_POINTER (handle))) {
1690                         /* We don't know this contact, skip */
1691                         continue;
1692                 }
1693
1694                 if (G_STR_EMPTY (alias)) {
1695                         alias = NULL;
1696                 }
1697
1698                 contact = empathy_tp_contact_list_get_from_handle (list, handle);
1699                 tp_contact_list_block_contact (list, contact);
1700                 gossip_contact_set_name (contact, alias);
1701                 tp_contact_list_unblock_contact (list, contact);
1702
1703                 gossip_debug (DEBUG_DOMAIN, "contact %d renamed to %s (update cb)",
1704                               handle, alias);
1705         }
1706 }
1707
1708 static void
1709 tp_contact_list_request_aliases_cb (DBusGProxy                       *proxy,
1710                                     gchar                           **contact_names,
1711                                     GError                           *error,
1712                                     TpContactListAliasesRequestData  *data)
1713 {
1714         guint   i = 0;
1715         gchar **name;
1716
1717         if (error) {
1718                 gossip_debug (DEBUG_DOMAIN, "Error requesting aliases: %s",
1719                               error->message);
1720         }
1721
1722         for (name = contact_names; *name && !error; name++) {
1723                 GossipContact *contact;
1724
1725                 contact = empathy_tp_contact_list_get_from_handle (data->list,
1726                                                                    data->handles[i]);
1727                 tp_contact_list_block_contact (data->list, contact);
1728                 gossip_contact_set_name (contact, *name);
1729                 tp_contact_list_unblock_contact (data->list, contact);
1730
1731                 gossip_debug (DEBUG_DOMAIN, "contact %d renamed to %s (request cb)",
1732                               data->handles[i], *name);
1733
1734                 i++;
1735         }
1736
1737         g_free (data->handles);
1738         g_slice_free (TpContactListAliasesRequestData, data);
1739 }
1740
1741 static void
1742 tp_contact_list_presence_update_cb (DBusGProxy           *proxy,
1743                                     GHashTable           *handle_table,
1744                                     EmpathyTpContactList *list)
1745 {
1746         g_hash_table_foreach (handle_table,
1747                               (GHFunc) tp_contact_list_parse_presence_foreach,
1748                               list);
1749 }
1750
1751 static void
1752 tp_contact_list_parse_presence_foreach (guint                 handle,
1753                                         GValueArray          *presence_struct,
1754                                         EmpathyTpContactList *list)
1755 {
1756         EmpathyTpContactListPriv *priv;
1757         GHashTable     *presences_table;
1758         GossipContact  *contact;
1759         GossipPresence *presence = NULL;
1760
1761         priv = GET_PRIV (list);
1762
1763         if (!g_hash_table_lookup (priv->contacts, GUINT_TO_POINTER (handle))) {
1764                 /* We don't know this contact, skip */
1765                 return;
1766         }
1767
1768         contact = empathy_tp_contact_list_get_from_handle (list, handle);
1769         presences_table = g_value_get_boxed (g_value_array_get_nth (presence_struct, 1));
1770
1771         g_hash_table_foreach (presences_table,
1772                               (GHFunc) tp_contact_list_presences_table_foreach,
1773                               &presence);
1774
1775         gossip_debug (DEBUG_DOMAIN, "Presence changed for %s (%d) to %s (%d)",
1776                       gossip_contact_get_name (contact),
1777                       handle,
1778                       presence ? gossip_presence_get_status (presence) : "unset",
1779                       presence ? gossip_presence_get_state (presence) : MC_PRESENCE_UNSET);
1780
1781         tp_contact_list_block_contact (list, contact);
1782         gossip_contact_set_presence (contact, presence);
1783         tp_contact_list_unblock_contact (list, contact);
1784 }
1785
1786 static void
1787 tp_contact_list_presences_table_foreach (const gchar     *state_str,
1788                                          GHashTable      *presences_table,
1789                                          GossipPresence **presence)
1790 {
1791         McPresence    state;
1792         const GValue *message;
1793
1794         state = gossip_presence_state_from_str (state_str);
1795         if ((state == MC_PRESENCE_UNSET) || (state == MC_PRESENCE_OFFLINE)) {
1796                 return;
1797         }
1798
1799         if (*presence) {
1800                 g_object_unref (*presence);
1801                 *presence = NULL;
1802         }
1803
1804         *presence = gossip_presence_new ();
1805         gossip_presence_set_state (*presence, state);
1806
1807         message = g_hash_table_lookup (presences_table, "message");
1808         if (message != NULL) {
1809                 gossip_presence_set_status (*presence,
1810                                             g_value_get_string (message));
1811         }
1812 }
1813
1814 static void
1815 tp_contact_list_status_changed_cb (MissionControl                  *mc,
1816                                    TelepathyConnectionStatus        status,
1817                                    McPresence                       presence,
1818                                    TelepathyConnectionStatusReason  reason,
1819                                    const gchar                     *unique_name,
1820                                    EmpathyTpContactList            *list)
1821 {
1822         EmpathyTpContactListPriv *priv;
1823         McAccount                *account;
1824
1825         priv = GET_PRIV (list);
1826
1827         account = mc_account_lookup (unique_name);
1828         if (status != TP_CONN_STATUS_DISCONNECTED ||
1829             !gossip_account_equal (account, priv->account)) {
1830                 g_object_unref (account);
1831                 return;
1832         }
1833
1834         /* We are disconnected, do just like if the connection was destroyed */
1835         g_signal_handlers_disconnect_by_func (priv->tp_conn,
1836                                               tp_contact_list_destroy_cb,
1837                                               list);
1838         tp_contact_list_destroy_cb (DBUS_G_PROXY (priv->tp_conn), list);
1839
1840         g_object_unref (account);
1841 }
1842