]> git.0d.be Git - empathy.git/blob - libempathy/empathy-tp-contact-factory.c
EmpathyTpContactFactory: If the presence dict doesn't contain a presence-message...
[empathy.git] / libempathy / empathy-tp-contact-factory.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2007 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/util.h>
27 #include <libtelepathy/tp-conn.h>
28 #include <libtelepathy/tp-conn-iface-aliasing-gen.h>
29 #include <libtelepathy/tp-conn-iface-presence-gen.h>
30 #include <libtelepathy/tp-conn-iface-avatars-gen.h>
31 #include <libtelepathy/tp-conn-iface-capabilities-gen.h>
32 #include <libmissioncontrol/mission-control.h>
33
34 #include "empathy-tp-contact-factory.h"
35 #include "empathy-utils.h"
36 #include "empathy-debug.h"
37
38 #define GET_PRIV(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), \
39                        EMPATHY_TYPE_TP_CONTACT_FACTORY, EmpathyTpContactFactoryPriv))
40
41 #define DEBUG_DOMAIN "TpContactFactory"
42
43 struct _EmpathyTpContactFactoryPriv {
44         MissionControl *mc;
45         McAccount      *account;
46
47         TpConn         *tp_conn;
48         DBusGProxy     *aliasing_iface;
49         DBusGProxy     *avatars_iface;
50         DBusGProxy     *presence_iface;
51         DBusGProxy     *capabilities_iface;
52
53         GList          *contacts;
54         guint           self_handle;
55 };
56
57 static void empathy_tp_contact_factory_class_init (EmpathyTpContactFactoryClass *klass);
58 static void empathy_tp_contact_factory_init       (EmpathyTpContactFactory      *factory);
59
60 G_DEFINE_TYPE (EmpathyTpContactFactory, empathy_tp_contact_factory, G_TYPE_OBJECT);
61
62 enum {
63         PROP_0,
64         PROP_ACCOUNT,
65 };
66
67 static EmpathyContact *
68 tp_contact_factory_find_by_handle (EmpathyTpContactFactory *tp_factory,
69                                    guint                    handle)
70 {
71         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
72         GList                       *l;
73
74         for (l = priv->contacts; l; l = l->next) {
75                 if (empathy_contact_get_handle (l->data) == handle) {
76                         return l->data;
77                 }
78         }
79
80         return NULL;
81 }
82
83 static EmpathyContact *
84 tp_contact_factory_find_by_id (EmpathyTpContactFactory *tp_factory,
85                                const gchar             *id)
86 {
87         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
88         GList                       *l;
89
90         for (l = priv->contacts; l; l = l->next) {
91                 if (!tp_strdiff (empathy_contact_get_id (l->data), id)) {
92                         return l->data;
93                 }
94         }
95
96         return NULL;
97 }
98
99 static void
100 tp_contact_factory_weak_notify (gpointer data,
101                                 GObject *where_the_object_was)
102 {
103         EmpathyTpContactFactoryPriv *priv = GET_PRIV (data);
104
105         empathy_debug (DEBUG_DOMAIN, "Remove finalized contact %p",
106                        where_the_object_was);
107
108         priv->contacts = g_list_remove (priv->contacts, where_the_object_was);
109 }
110
111 static void
112 tp_contact_factory_presences_table_foreach (const gchar    *state_str,
113                                             GHashTable     *presences_table,
114                                             EmpathyContact *contact)
115 {
116         const GValue *message;
117
118         empathy_contact_set_presence (contact,
119                                       empathy_presence_from_str (state_str));
120         
121         message = g_hash_table_lookup (presences_table, "message");
122         if (message != NULL) {
123                 empathy_contact_set_presence_message (contact,
124                                                       g_value_get_string (message));
125         } else {
126                 empathy_contact_set_presence_message (contact, NULL);
127         }
128 }
129
130 static void
131 tp_contact_factory_parse_presence_foreach (guint                    handle,
132                                            GValueArray             *presence_struct,
133                                            EmpathyTpContactFactory *tp_factory)
134 {
135         GHashTable      *presences_table;
136         EmpathyContact  *contact;
137
138         contact = tp_contact_factory_find_by_handle (tp_factory, handle);
139         if (!contact) {
140                 return;
141         }
142
143         presences_table = g_value_get_boxed (g_value_array_get_nth (presence_struct, 1));
144
145         g_hash_table_foreach (presences_table,
146                               (GHFunc) tp_contact_factory_presences_table_foreach,
147                               contact);
148
149         empathy_debug (DEBUG_DOMAIN, "Changing presence for contact %s (%d) to %s (%d)",
150                       empathy_contact_get_id (contact),
151                       handle,
152                       empathy_contact_get_presence_message (contact),
153                       empathy_contact_get_presence (contact));
154 }
155
156 static void
157 tp_contact_factory_get_presence_cb (DBusGProxy *proxy,
158                                     GHashTable *handle_table,
159                                     GError     *error,
160                                     gpointer    user_data)
161 {
162         EmpathyTpContactFactory *tp_factory = user_data;
163
164         if (error) {
165                 empathy_debug (DEBUG_DOMAIN, "Error getting presence: %s",
166                               error->message);
167                 goto OUT;
168         }
169
170         g_hash_table_foreach (handle_table,
171                               (GHFunc) tp_contact_factory_parse_presence_foreach,
172                               tp_factory);
173
174         g_hash_table_destroy (handle_table);
175 OUT:
176         g_object_unref (tp_factory);
177 }
178
179 static void
180 tp_contact_factory_presence_update_cb (DBusGProxy              *proxy,
181                                        GHashTable              *handle_table,
182                                        EmpathyTpContactFactory *tp_factory)
183 {
184         g_hash_table_foreach (handle_table,
185                               (GHFunc) tp_contact_factory_parse_presence_foreach,
186                               tp_factory);
187 }
188
189 static void
190 tp_contact_factory_set_aliases_cb (DBusGProxy *proxy,
191                                    GError     *error,
192                                    gpointer    user_data)
193 {
194         EmpathyTpContactFactory *tp_factory = user_data;
195
196         if (error) {
197                 empathy_debug (DEBUG_DOMAIN, "Error setting alias: %s",
198                                error->message);
199         }
200
201         g_object_unref (tp_factory);
202 }
203
204 typedef struct {
205         EmpathyTpContactFactory *tp_factory;
206         guint                   *handles;
207 } RequestAliasesData;
208
209 static void
210 tp_contact_factory_request_aliases_cb (DBusGProxy  *proxy,
211                                        gchar      **contact_names,
212                                        GError      *error,
213                                        gpointer     user_data)
214 {
215         RequestAliasesData  *data = user_data;
216         guint                i = 0;
217         gchar              **name;
218
219         if (error) {
220                 empathy_debug (DEBUG_DOMAIN, "Error requesting aliases: %s",
221                               error->message);
222                 goto OUT;
223         }
224
225         for (name = contact_names; *name; name++) {
226                 EmpathyContact *contact;
227
228                 contact = tp_contact_factory_find_by_handle (data->tp_factory,
229                                                              data->handles[i]);
230                 if (!contact) {
231                         continue;
232                 }
233
234                 empathy_debug (DEBUG_DOMAIN, "Renaming contact %s (%d) to %s (request cb)",
235                                empathy_contact_get_id (contact),
236                                data->handles[i], *name);
237
238                 empathy_contact_set_name (contact, *name);
239
240                 i++;
241         }
242
243         g_strfreev (contact_names);
244 OUT:
245         g_object_unref (data->tp_factory);
246         g_free (data->handles);
247         g_slice_free (RequestAliasesData, data);
248 }
249
250 static void
251 tp_contact_factory_aliases_changed_cb (DBusGProxy *proxy,
252                                        GPtrArray  *renamed_handlers,
253                                        gpointer    user_data)
254 {
255         EmpathyTpContactFactory *tp_factory = user_data;
256         guint                    i;
257
258         for (i = 0; renamed_handlers->len > i; i++) {
259                 guint           handle;
260                 const gchar    *alias;
261                 GValueArray    *renamed_struct;
262                 EmpathyContact *contact;
263
264                 renamed_struct = g_ptr_array_index (renamed_handlers, i);
265                 handle = g_value_get_uint(g_value_array_get_nth (renamed_struct, 0));
266                 alias = g_value_get_string(g_value_array_get_nth (renamed_struct, 1));
267                 contact = tp_contact_factory_find_by_handle (tp_factory, handle);
268
269                 if (!contact) {
270                         /* We don't know this contact, skip */
271                         continue;
272                 }
273
274                 if (G_STR_EMPTY (alias)) {
275                         alias = NULL;
276                 }
277
278                 empathy_debug (DEBUG_DOMAIN, "Renaming contact %s (%d) to %s (changed cb)",
279                                empathy_contact_get_id (contact),
280                                handle, alias);
281
282                 empathy_contact_set_name (contact, alias);
283         }
284 }
285
286 static void
287 tp_contact_factory_set_avatar_cb (DBusGProxy *proxy,
288                                   gchar      *token,
289                                   GError     *error,
290                                   gpointer    user_data)
291 {
292         EmpathyTpContactFactory *tp_factory = user_data;
293
294         if (error) {
295                 empathy_debug (DEBUG_DOMAIN, "Error setting avatar: %s",
296                                error->message);
297         }
298
299         g_object_unref (tp_factory);
300         g_free (token);
301 }
302
303 static void
304 tp_contact_factory_clear_avatar_cb (DBusGProxy *proxy,
305                                     GError     *error,
306                                     gpointer    user_data)
307 {
308         EmpathyTpContactFactory *tp_factory = user_data;
309
310         if (error) {
311                 empathy_debug (DEBUG_DOMAIN, "Error clearing avatar: %s",
312                                error->message);
313         }
314
315         g_object_unref (tp_factory);
316 }
317
318 static void
319 tp_contact_factory_avatar_retrieved_cb (DBusGProxy *proxy,
320                                         guint       handle,
321                                         gchar      *token,
322                                         GArray     *avatar_data,
323                                         gchar      *mime_type,
324                                         gpointer    user_data)
325 {
326         EmpathyTpContactFactory *tp_factory = user_data;
327         EmpathyContact          *contact;
328         EmpathyAvatar           *avatar;
329
330         contact = tp_contact_factory_find_by_handle (tp_factory, handle);
331         if (!contact) {
332                 return;
333         }
334
335         empathy_debug (DEBUG_DOMAIN, "Avatar retrieved for contact %s (%d)",
336                        empathy_contact_get_id (contact),
337                        handle);
338
339         avatar = empathy_avatar_new (avatar_data->data,
340                                      avatar_data->len,
341                                      mime_type,
342                                      token);
343
344         empathy_contact_set_avatar (contact, avatar);
345         empathy_avatar_unref (avatar);
346 }
347
348 static void
349 tp_contact_factory_request_avatars_cb (DBusGProxy *proxy,
350                                        GError     *error,
351                                        gpointer    user_data)
352 {
353         EmpathyTpContactFactory *tp_factory = user_data;
354
355         if (error) {
356                 empathy_debug (DEBUG_DOMAIN, "Error requesting avatars: %s",
357                                error->message);
358         }
359
360         g_object_unref (tp_factory);
361 }
362
363 static gboolean
364 tp_contact_factory_avatar_maybe_update (EmpathyTpContactFactory *tp_factory,
365                                         guint                    handle,
366                                         const gchar             *token)
367 {
368         EmpathyContact *contact;
369         EmpathyAvatar  *avatar;
370
371         contact = tp_contact_factory_find_by_handle (tp_factory, handle);
372         if (!contact) {
373                 return TRUE;
374         }
375
376         /* Check if we have an avatar */
377         if (G_STR_EMPTY (token)) {
378                 empathy_contact_set_avatar (contact, NULL);
379                 return TRUE;
380         }
381
382         /* Check if the avatar changed */
383         avatar = empathy_contact_get_avatar (contact);
384         if (avatar && !tp_strdiff (avatar->token, token)) {
385                 return TRUE;
386         }
387
388         /* The avatar changed, search the new one in the cache */
389         avatar = empathy_avatar_new_from_cache (token);
390         if (avatar) {
391                 /* Got from cache, use it */
392                 empathy_contact_set_avatar (contact, avatar);
393                 empathy_avatar_unref (avatar);
394                 return TRUE;
395         }
396
397         /* Avatar is not up-to-date, we have to request it. */
398         return FALSE;
399 }
400
401 typedef struct {
402         EmpathyTpContactFactory *tp_factory;
403         GArray                  *handles;
404 } TokensData;
405
406 static void
407 tp_contact_factory_avatar_tokens_foreach (gpointer key,
408                                           gpointer value,
409                                           gpointer user_data)
410 {
411         TokensData  *data = user_data;
412         const gchar *token = value;
413         guint        handle = GPOINTER_TO_UINT (key);
414
415         if (!tp_contact_factory_avatar_maybe_update (data->tp_factory,
416                                                      handle, token)) {
417                 g_array_append_val (data->handles, handle);
418         }
419 }
420
421 static void
422 tp_contact_factory_get_known_avatar_tokens_cb (DBusGProxy *proxy,
423                                                GHashTable *tokens,
424                                                GError     *error,
425                                                gpointer    user_data)
426 {
427         EmpathyTpContactFactory     *tp_factory = user_data;
428         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
429         TokensData                   data;
430
431         if (error) {
432                 empathy_debug (DEBUG_DOMAIN,
433                                "Error getting known avatars tokens: %s",
434                                error->message);
435                 goto OUT;
436         }
437
438         data.tp_factory = tp_factory;
439         data.handles = g_array_new (FALSE, FALSE, sizeof (guint));
440         g_hash_table_foreach (tokens,
441                               tp_contact_factory_avatar_tokens_foreach,
442                               &data);
443
444         empathy_debug (DEBUG_DOMAIN, "Got %d tokens, need to request %d avatars",
445                        g_hash_table_size (tokens),
446                        data.handles->len);
447
448         /* Request needed avatars */
449         if (data.handles->len > 0) {
450                 tp_conn_iface_avatars_request_avatars_async (priv->avatars_iface,
451                                                              data.handles,
452                                                              tp_contact_factory_request_avatars_cb,
453                                                              g_object_ref (tp_factory));
454         }
455
456         g_hash_table_destroy (tokens);
457         g_array_free (data.handles, TRUE);
458 OUT:
459         g_object_unref (tp_factory);
460 }
461
462 static void
463 tp_contact_factory_avatar_updated_cb (DBusGProxy *proxy,
464                                       guint       handle,
465                                       gchar      *new_token,
466                                       gpointer    user_data)
467 {
468         EmpathyTpContactFactory     *tp_factory = user_data;
469         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
470         GArray                      *handles;
471
472         if (tp_contact_factory_avatar_maybe_update (tp_factory, handle, new_token)) {
473                 /* Avatar was cached, nothing to do */
474                 return;
475         }
476
477         empathy_debug (DEBUG_DOMAIN, "Need to request avatar for token %s",
478                        new_token);
479
480         handles = g_array_new (FALSE, FALSE, sizeof (guint));
481         g_array_append_val (handles, handle);
482
483         tp_conn_iface_avatars_request_avatars_async (priv->avatars_iface,
484                                                      handles,
485                                                      tp_contact_factory_request_avatars_cb,
486                                                      g_object_ref (tp_factory));
487         g_array_free (handles, TRUE);
488 }
489
490 static void
491 tp_contact_factory_update_capabilities (EmpathyTpContactFactory *tp_factory,
492                                         guint                    handle,
493                                         const gchar             *channel_type,
494                                         guint                    generic,
495                                         guint                    specific)
496 {
497         EmpathyContact      *contact;
498         EmpathyCapabilities  capabilities;
499
500         contact = tp_contact_factory_find_by_handle (tp_factory, handle);
501         if (!contact) {
502                 return;
503         }
504
505         capabilities = empathy_contact_get_capabilities (contact);
506
507         if (strcmp (channel_type, TP_IFACE_CHANNEL_TYPE_STREAMED_MEDIA) == 0) {
508                 capabilities &= ~EMPATHY_CAPABILITIES_AUDIO;
509                 capabilities &= ~EMPATHY_CAPABILITIES_VIDEO;
510                 if (specific & TP_CHANNEL_MEDIA_CAPABILITY_AUDIO) {
511                         capabilities |= EMPATHY_CAPABILITIES_AUDIO;
512                 }
513                 if (specific & TP_CHANNEL_MEDIA_CAPABILITY_VIDEO) {
514                         capabilities |= EMPATHY_CAPABILITIES_VIDEO;
515                 }
516         }
517
518         empathy_debug (DEBUG_DOMAIN, "Changing capabilities for contact %s (%d) to %d",
519                        empathy_contact_get_id (contact),
520                        empathy_contact_get_handle (contact),
521                        capabilities);
522
523         empathy_contact_set_capabilities (contact, capabilities);
524 }
525
526 static void
527 tp_contact_factory_get_capabilities_cb (DBusGProxy *proxy,
528                                         GPtrArray  *capabilities,
529                                         GError     *error,
530                                         gpointer    user_data)
531 {
532         EmpathyTpContactFactory *tp_factory = user_data;
533         guint                    i;
534
535         if (error) {
536                 empathy_debug (DEBUG_DOMAIN, "Error getting capabilities: %s",
537                                error->message);
538                 goto OUT;
539         }
540
541         for (i = 0; i < capabilities->len; i++) {
542                 GValueArray *values;
543                 guint        handle;
544                 const gchar *channel_type;
545                 guint        generic;
546                 guint        specific;
547
548                 values = g_ptr_array_index (capabilities, i);
549                 handle = g_value_get_uint (g_value_array_get_nth (values, 0));
550                 channel_type = g_value_get_string (g_value_array_get_nth (values, 1));
551                 generic = g_value_get_uint (g_value_array_get_nth (values, 2));
552                 specific = g_value_get_uint (g_value_array_get_nth (values, 3));
553
554                 tp_contact_factory_update_capabilities (tp_factory,
555                                                         handle,
556                                                         channel_type,
557                                                         generic,
558                                                         specific);
559
560                 g_value_array_free (values);
561         }
562
563         g_ptr_array_free (capabilities, TRUE);
564 OUT:
565         g_object_unref (tp_factory);
566 }
567
568 static void
569 tp_contact_factory_capabilities_changed_cb (DBusGProxy *proxy,
570                                             GPtrArray  *capabilities,
571                                             gpointer    user_data)
572 {
573         EmpathyTpContactFactory *tp_factory = user_data;
574         guint                    i;
575
576         for (i = 0; i < capabilities->len; i++) {
577                 GValueArray *values;
578                 guint        handle;
579                 const gchar *channel_type;
580                 guint        generic;
581                 guint        specific;
582
583                 values = g_ptr_array_index (capabilities, i);
584                 handle = g_value_get_uint (g_value_array_get_nth (values, 0));
585                 channel_type = g_value_get_string (g_value_array_get_nth (values, 1));
586                 generic = g_value_get_uint (g_value_array_get_nth (values, 3));
587                 specific = g_value_get_uint (g_value_array_get_nth (values, 5));
588
589                 tp_contact_factory_update_capabilities (tp_factory,
590                                                         handle,
591                                                         channel_type,
592                                                         generic,
593                                                         specific);
594         }
595 }
596
597 static void
598 tp_contact_factory_request_everything (EmpathyTpContactFactory *tp_factory,
599                                        GArray                  *handles)
600 {
601         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
602
603         if (priv->presence_iface) {
604                 tp_conn_iface_presence_get_presence_async (priv->presence_iface,
605                                                            handles,
606                                                            tp_contact_factory_get_presence_cb,
607                                                            g_object_ref (tp_factory));
608         }
609
610         if (priv->aliasing_iface) {
611                 RequestAliasesData *data;
612
613                 data = g_slice_new (RequestAliasesData);
614                 data->tp_factory = g_object_ref (tp_factory);
615                 data->handles = g_memdup (handles->data, handles->len * sizeof (guint));
616
617                 tp_conn_iface_aliasing_request_aliases_async (priv->aliasing_iface,
618                                                               handles,
619                                                               tp_contact_factory_request_aliases_cb,
620                                                               data);
621         }
622
623         if (priv->avatars_iface) {
624                 tp_conn_iface_avatars_get_known_avatar_tokens_async (priv->avatars_iface,
625                                                                      handles,
626                                                                      tp_contact_factory_get_known_avatar_tokens_cb,
627                                                                      g_object_ref (tp_factory));
628         }
629
630         if (priv->capabilities_iface) {
631                 tp_conn_iface_capabilities_get_capabilities_async (priv->capabilities_iface,
632                                                                    handles,
633                                                                    tp_contact_factory_get_capabilities_cb,
634                                                                    g_object_ref (tp_factory));
635         }
636 }
637
638 typedef struct {
639         EmpathyTpContactFactory *tp_factory;
640         GList                   *contacts;
641 } RequestHandlesData;
642
643 static void
644 tp_contact_factory_request_handles_cb (DBusGProxy *proxy,
645                                        GArray     *handles,
646                                        GError     *error,
647                                        gpointer    user_data)
648 {
649         RequestHandlesData          *data = user_data;
650         EmpathyTpContactFactory     *tp_factory = data->tp_factory;
651         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
652         GList                       *l;
653         guint                        i = 0;
654
655         if (error) {
656                 empathy_debug (DEBUG_DOMAIN, "Failed to request handles: %s",
657                                error->message);
658                 goto OUT;
659         }
660
661         for (l = data->contacts; l; l = l->next) {
662                 guint handle;
663
664                 handle = g_array_index (handles, guint, i);
665                 empathy_contact_set_handle (l->data, handle);
666                 if (handle == priv->self_handle) {
667                         empathy_contact_set_is_user (l->data, TRUE);
668                 }
669
670                 i++;
671         }
672
673         tp_contact_factory_request_everything (tp_factory, handles);
674         g_array_free (handles, TRUE);
675
676 OUT:
677         g_list_foreach (data->contacts, (GFunc) g_object_unref, NULL);
678         g_list_free (data->contacts);
679         g_object_unref (tp_factory);
680         g_slice_free (RequestHandlesData, data);
681 }
682
683 static void
684 tp_contact_factory_disconnect_contact_foreach (gpointer data,
685                                                gpointer user_data)
686 {
687         EmpathyContact *contact = data;
688         
689         empathy_contact_set_presence (contact, MC_PRESENCE_UNSET);
690         empathy_contact_set_handle (contact, 0);
691 }
692
693 static void
694 tp_contact_factory_destroy_cb (TpConn                  *tp_conn,
695                                EmpathyTpContactFactory *tp_factory)
696 {
697         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
698
699         empathy_debug (DEBUG_DOMAIN, "Account disconnected or CM crashed");
700
701         g_object_unref (priv->tp_conn);
702         priv->tp_conn = NULL;
703         priv->aliasing_iface = NULL;
704         priv->avatars_iface = NULL;
705         priv->presence_iface = NULL;
706         priv->capabilities_iface = NULL;
707
708         g_list_foreach (priv->contacts,
709                         tp_contact_factory_disconnect_contact_foreach,
710                         tp_factory);
711 }
712
713 static void
714 tp_contact_factory_disconnect (EmpathyTpContactFactory *tp_factory)
715 {
716         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
717
718         if (priv->aliasing_iface) {
719                 dbus_g_proxy_disconnect_signal (priv->aliasing_iface,
720                                                 "AliasesChanged",
721                                                 G_CALLBACK (tp_contact_factory_aliases_changed_cb),
722                                                 tp_factory);
723         }
724         if (priv->avatars_iface) {
725                 dbus_g_proxy_disconnect_signal (priv->avatars_iface,
726                                                 "AvatarUpdated",
727                                                 G_CALLBACK (tp_contact_factory_avatar_updated_cb),
728                                                 tp_factory);
729                 dbus_g_proxy_disconnect_signal (priv->avatars_iface,
730                                                 "AvatarRetrieved",
731                                                 G_CALLBACK (tp_contact_factory_avatar_retrieved_cb),
732                                                 tp_factory);
733         }
734         if (priv->presence_iface) {
735                 dbus_g_proxy_disconnect_signal (priv->presence_iface,
736                                                 "PresenceUpdate",
737                                                 G_CALLBACK (tp_contact_factory_presence_update_cb),
738                                                 tp_factory);
739         }
740         if (priv->capabilities_iface) {
741                 dbus_g_proxy_disconnect_signal (priv->capabilities_iface,
742                                                 "CapabilitiesChanged",
743                                                 G_CALLBACK (tp_contact_factory_capabilities_changed_cb),
744                                                 tp_factory);
745         }
746         if (priv->tp_conn) {
747                 g_signal_handlers_disconnect_by_func (priv->tp_conn,
748                                                       tp_contact_factory_destroy_cb,
749                                                       tp_factory);
750         }
751 }
752
753 static void
754 tp_contact_factory_update (EmpathyTpContactFactory *tp_factory)
755 {
756         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
757         TpConn                      *tp_conn = NULL;
758         RequestHandlesData          *data;
759         const gchar                **contact_ids;
760         guint                        i;
761         GList                       *l;
762         GError                      *error = NULL;
763
764         if (priv->account) {
765                 guint status;
766
767                 /* status == 0 means the status is CONNECTED */
768                 status = mission_control_get_connection_status (priv->mc,
769                                                                 priv->account,
770                                                                 NULL);
771                 if (status == 0) {
772                         tp_conn = mission_control_get_connection (priv->mc,
773                                                                   priv->account,
774                                                                   NULL);
775                 }
776         }
777
778         if (!tp_conn) {
779                 /* We are not connected anymore, remove the old connection */
780                 tp_contact_factory_disconnect (tp_factory);
781                 if (priv->tp_conn) {
782                         tp_contact_factory_destroy_cb (priv->tp_conn, tp_factory);
783                 }
784                 return;
785         }
786         else if (priv->tp_conn) {
787                 /* We were connected and we still are connected, nothing
788                  * changed so nothing to do. */
789                 g_object_unref (tp_conn);
790                 return;
791         }
792
793         /* We got a new connection */
794         priv->tp_conn = tp_conn;
795         priv->aliasing_iface = tp_conn_get_interface (priv->tp_conn,
796                                                       TP_IFACE_QUARK_CONNECTION_INTERFACE_ALIASING);
797         priv->avatars_iface = tp_conn_get_interface (priv->tp_conn,
798                                                      TP_IFACE_QUARK_CONNECTION_INTERFACE_AVATARS);
799         priv->presence_iface = tp_conn_get_interface (priv->tp_conn,
800                                                       TP_IFACE_QUARK_CONNECTION_INTERFACE_PRESENCE);
801         priv->capabilities_iface = tp_conn_get_interface (priv->tp_conn,
802                                                           TP_IFACE_QUARK_CONNECTION_INTERFACE_CAPABILITIES);
803
804         /* Connect signals */
805         if (priv->aliasing_iface) {
806                 dbus_g_proxy_connect_signal (priv->aliasing_iface,
807                                              "AliasesChanged",
808                                              G_CALLBACK (tp_contact_factory_aliases_changed_cb),
809                                              tp_factory, NULL);
810         }
811         if (priv->avatars_iface) {
812                 dbus_g_proxy_connect_signal (priv->avatars_iface,
813                                              "AvatarUpdated",
814                                              G_CALLBACK (tp_contact_factory_avatar_updated_cb),
815                                              tp_factory, NULL);
816                 dbus_g_proxy_connect_signal (priv->avatars_iface,
817                                              "AvatarRetrieved",
818                                              G_CALLBACK (tp_contact_factory_avatar_retrieved_cb),
819                                              tp_factory, NULL);
820         }
821         if (priv->presence_iface) {
822                 dbus_g_proxy_connect_signal (priv->presence_iface,
823                                              "PresenceUpdate",
824                                              G_CALLBACK (tp_contact_factory_presence_update_cb),
825                                              tp_factory, NULL);
826         }
827         if (priv->capabilities_iface) {
828                 dbus_g_proxy_connect_signal (priv->capabilities_iface,
829                                              "CapabilitiesChanged",
830                                              G_CALLBACK (tp_contact_factory_capabilities_changed_cb),
831                                              tp_factory, NULL);
832         }
833         g_signal_connect (priv->tp_conn, "destroy",
834                           G_CALLBACK (tp_contact_factory_destroy_cb),
835                           tp_factory);
836
837         /* Get our own handle */
838         if (!tp_conn_get_self_handle (DBUS_G_PROXY (priv->tp_conn),
839                                       &priv->self_handle,
840                                       &error)) {
841                 empathy_debug (DEBUG_DOMAIN, "GetSelfHandle Error: %s",
842                               error ? error->message : "No error given");
843                 g_clear_error (&error);
844         }
845
846         /* Request new handles for all contacts */
847         if (priv->contacts) {
848                 data = g_slice_new (RequestHandlesData);
849                 data->tp_factory = g_object_ref (tp_factory);
850                 data->contacts = g_list_copy (priv->contacts);
851                 g_list_foreach (data->contacts, (GFunc) g_object_ref, NULL);
852
853                 i = g_list_length (data->contacts);
854                 contact_ids = g_new0 (const gchar*, i + 1);
855                 i = 0;
856                 for (l = data->contacts; l; l = l->next) {
857                         contact_ids[i] = empathy_contact_get_id (l->data);
858                         i++;
859                 }
860
861                 tp_conn_request_handles_async (DBUS_G_PROXY (priv->tp_conn),
862                                                TP_HANDLE_TYPE_CONTACT,
863                                                contact_ids,
864                                                tp_contact_factory_request_handles_cb,
865                                                data);
866                 g_free (contact_ids);
867         }
868 }
869
870 static void
871 tp_contact_factory_status_changed_cb (MissionControl           *mc,
872                                       TpConnectionStatus        status,
873                                       McPresence                presence,
874                                       TpConnectionStatusReason  reason,
875                                       const gchar              *unique_name,
876                                       EmpathyTpContactFactory  *tp_factory)
877 {
878         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
879         McAccount                   *account;
880
881         account = mc_account_lookup (unique_name);
882         if (account && empathy_account_equal (account, priv->account)) {
883                 tp_contact_factory_update (tp_factory);
884         }
885         g_object_unref (account);
886 }
887
888 static void
889 tp_contact_factory_add_contact (EmpathyTpContactFactory *tp_factory,
890                                 EmpathyContact          *contact)
891 {
892         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
893
894         g_object_weak_ref (G_OBJECT (contact),
895                            tp_contact_factory_weak_notify,
896                            tp_factory);
897         priv->contacts = g_list_prepend (priv->contacts, contact);
898
899         if (!priv->presence_iface) {
900                 /* We have no presence iface, set default presence
901                  * to available */
902                 empathy_contact_set_presence (contact, MC_PRESENCE_AVAILABLE);
903         }
904
905         empathy_debug (DEBUG_DOMAIN, "Contact added: %s (%d)",
906                        empathy_contact_get_id (contact),
907                        empathy_contact_get_handle (contact));
908 }
909
910 static void
911 tp_contact_factory_hold_handles_cb (DBusGProxy *proxy,
912                                     GError     *error,
913                                     gpointer    userdata)
914 {
915         if (error) {
916                 empathy_debug (DEBUG_DOMAIN, "Failed to hold handles: %s",
917                                error->message);
918         }
919 }
920
921 EmpathyContact *
922 empathy_tp_contact_factory_get_user (EmpathyTpContactFactory *tp_factory)
923 {
924         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
925
926         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_FACTORY (tp_factory), NULL);
927
928         return empathy_tp_contact_factory_get_from_handle (tp_factory,
929                                                            priv->self_handle);
930 }
931
932 EmpathyContact *
933 empathy_tp_contact_factory_get_from_id (EmpathyTpContactFactory *tp_factory,
934                                         const gchar             *id)
935 {
936         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
937         EmpathyContact              *contact;
938
939         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_FACTORY (tp_factory), NULL);
940         g_return_val_if_fail (id != NULL, NULL);
941
942         /* Check if the contact already exists */
943         contact = tp_contact_factory_find_by_id (tp_factory, id);
944         if (contact) {
945                 return g_object_ref (contact);
946         }
947
948         /* Create new contact */
949         contact = g_object_new (EMPATHY_TYPE_CONTACT,
950                                 "account", priv->account,
951                                 "id", id,
952                                 NULL);
953         tp_contact_factory_add_contact (tp_factory, contact);
954
955         /* If the account is connected, request contact's handle */
956         if (priv->tp_conn) {
957                 RequestHandlesData *data;
958                 const gchar        *contact_ids[] = {id, NULL};
959                 
960                 data = g_slice_new (RequestHandlesData);
961                 data->tp_factory = g_object_ref (tp_factory);
962                 data->contacts = g_list_prepend (NULL, g_object_ref (contact));
963                 tp_conn_request_handles_async (DBUS_G_PROXY (priv->tp_conn),
964                                                TP_HANDLE_TYPE_CONTACT,
965                                                contact_ids,
966                                                tp_contact_factory_request_handles_cb,
967                                                data);
968         }
969
970         return contact;
971 }
972
973 EmpathyContact *
974 empathy_tp_contact_factory_get_from_handle (EmpathyTpContactFactory *tp_factory,
975                                             guint                    handle)
976 {
977         EmpathyContact *contact;
978         GArray         *handles;
979         GList          *contacts;
980
981         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_FACTORY (tp_factory), NULL);
982
983         handles = g_array_new (FALSE, FALSE, sizeof (guint));
984         g_array_append_val (handles, handle);
985
986         contacts = empathy_tp_contact_factory_get_from_handles (tp_factory, handles);
987         g_array_free (handles, TRUE);
988
989         contact = contacts ? contacts->data : NULL;
990         g_list_free (contacts);
991
992         return contact;
993 }
994
995 GList *
996 empathy_tp_contact_factory_get_from_handles (EmpathyTpContactFactory *tp_factory,
997                                              GArray                  *handles)
998 {
999         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
1000         GList                       *contacts = NULL;
1001         GArray                      *new_handles;
1002         gchar                      **handles_names;
1003         guint                        i;
1004         GError                      *error = NULL;
1005
1006         g_return_val_if_fail (EMPATHY_IS_TP_CONTACT_FACTORY (tp_factory), NULL);
1007         g_return_val_if_fail (handles != NULL, NULL);
1008
1009         /* Search all contacts we already have */
1010         new_handles = g_array_new (FALSE, FALSE, sizeof (guint));
1011         for (i = 0; i < handles->len; i++) {
1012                 EmpathyContact *contact;
1013                 guint           handle;
1014
1015                 handle = g_array_index (handles, guint, i);
1016                 if (handle == 0) {
1017                         continue;
1018                 }
1019
1020                 contact = tp_contact_factory_find_by_handle (tp_factory, handle);
1021                 if (contact) {
1022                         contacts = g_list_prepend (contacts, g_object_ref (contact));
1023                 } else {
1024                         g_array_append_val (new_handles, handle);
1025                 }
1026         }
1027
1028         if (new_handles->len == 0) {
1029                 g_array_free (new_handles, TRUE);
1030                 return contacts;
1031         }
1032
1033         /* Get the IDs of all new handles */
1034         if (!tp_conn_inspect_handles (DBUS_G_PROXY (priv->tp_conn),
1035                                       TP_HANDLE_TYPE_CONTACT,
1036                                       new_handles,
1037                                       &handles_names,
1038                                       &error)) {
1039                 empathy_debug (DEBUG_DOMAIN, 
1040                               "Couldn't inspect contact: %s",
1041                               error ? error->message : "No error given");
1042                 g_clear_error (&error);
1043                 g_array_free (new_handles, TRUE);
1044                 return contacts;
1045         }
1046
1047         /* Create new contacts */
1048         for (i = 0; i < new_handles->len; i++) {
1049                 EmpathyContact *contact;
1050                 gchar          *id;
1051                 guint           handle;
1052                 gboolean        is_user;
1053
1054                 id = handles_names[i];
1055                 handle = g_array_index (new_handles, guint, i);
1056
1057                 is_user = (handle == priv->self_handle);
1058                 contact = g_object_new (EMPATHY_TYPE_CONTACT,
1059                                         "account", priv->account,
1060                                         "handle", handle,
1061                                         "id", id,
1062                                         "is-user", is_user,
1063                                         NULL);
1064                 tp_contact_factory_add_contact (tp_factory, contact);
1065                 contacts = g_list_prepend (contacts, contact);
1066                 g_free (id);
1067         }
1068         g_free (handles_names);
1069
1070         /* Hold all new handles. */
1071         tp_conn_hold_handles_async (DBUS_G_PROXY (priv->tp_conn),
1072                                     TP_HANDLE_TYPE_CONTACT,
1073                                     new_handles,
1074                                     tp_contact_factory_hold_handles_cb,
1075                                     NULL);
1076
1077         tp_contact_factory_request_everything (tp_factory, new_handles);
1078
1079         g_array_free (new_handles, TRUE);
1080
1081         return contacts;
1082 }
1083
1084 void
1085 empathy_tp_contact_factory_set_alias (EmpathyTpContactFactory *tp_factory,
1086                                       EmpathyContact          *contact,
1087                                       const gchar             *alias)
1088 {
1089         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
1090         GHashTable                  *new_alias;
1091         guint                        handle;
1092
1093         g_return_if_fail (EMPATHY_IS_TP_CONTACT_FACTORY (tp_factory));
1094         g_return_if_fail (EMPATHY_IS_CONTACT (contact));
1095         g_return_if_fail (empathy_account_equal (empathy_contact_get_account (contact),
1096                                                  priv->account));
1097
1098         if (!priv->aliasing_iface) {
1099                 return;
1100         }
1101
1102         handle = empathy_contact_get_handle (contact);
1103
1104         empathy_debug (DEBUG_DOMAIN, "Setting alias for contact %s (%d) to %s",
1105                        empathy_contact_get_id (contact),
1106                        handle, alias);
1107
1108         new_alias = g_hash_table_new_full (g_direct_hash,
1109                                            g_direct_equal,
1110                                            NULL,
1111                                            g_free);
1112
1113         g_hash_table_insert (new_alias,
1114                              GUINT_TO_POINTER (handle),
1115                              g_strdup (alias));
1116
1117         tp_conn_iface_aliasing_set_aliases_async (priv->aliasing_iface,
1118                                                   new_alias,
1119                                                   tp_contact_factory_set_aliases_cb,
1120                                                   g_object_ref (tp_factory));
1121
1122         g_hash_table_destroy (new_alias);
1123 }
1124
1125 void
1126 empathy_tp_contact_factory_set_avatar (EmpathyTpContactFactory *tp_factory,
1127                                        const gchar             *data,
1128                                        gsize                    size,
1129                                        const gchar             *mime_type)
1130 {
1131         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
1132
1133         g_return_if_fail (EMPATHY_IS_TP_CONTACT_FACTORY (tp_factory));
1134
1135         if (!priv->avatars_iface) {
1136                 return;
1137         }
1138
1139         if (data && size > 0 && size < G_MAXUINT) {
1140                 GArray avatar;
1141
1142                 avatar.data = (gchar*) data;
1143                 avatar.len = size;
1144
1145                 empathy_debug (DEBUG_DOMAIN, "Setting avatar on account %s",
1146                                mc_account_get_unique_name (priv->account));
1147
1148                 tp_conn_iface_avatars_set_avatar_async (priv->avatars_iface,
1149                                                         &avatar,
1150                                                         mime_type,
1151                                                         tp_contact_factory_set_avatar_cb,
1152                                                         g_object_ref (tp_factory));
1153         } else {
1154                 empathy_debug (DEBUG_DOMAIN, "Clearing avatar on account %s",
1155                                mc_account_get_unique_name (priv->account));
1156                 tp_conn_iface_avatars_clear_avatar_async (priv->avatars_iface,
1157                                                           tp_contact_factory_clear_avatar_cb,
1158                                                           g_object_ref (tp_factory));
1159         }
1160 }
1161
1162 static void
1163 tp_contact_factory_get_property (GObject    *object,
1164                                  guint       param_id,
1165                                  GValue     *value,
1166                                  GParamSpec *pspec)
1167 {
1168         EmpathyTpContactFactoryPriv *priv = GET_PRIV (object);
1169
1170         switch (param_id) {
1171         case PROP_ACCOUNT:
1172                 g_value_set_object (value, priv->account);
1173                 break;
1174         default:
1175                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1176                 break;
1177         };
1178 }
1179
1180 static void
1181 tp_contact_factory_set_property (GObject      *object,
1182                                  guint         param_id,
1183                                  const GValue *value,
1184                                  GParamSpec   *pspec)
1185 {
1186         EmpathyTpContactFactoryPriv *priv = GET_PRIV (object);
1187
1188         switch (param_id) {
1189         case PROP_ACCOUNT:
1190                 priv->account = g_object_ref (g_value_get_object (value));
1191                 break;
1192         default:
1193                 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
1194                 break;
1195         };
1196 }
1197
1198 static void
1199 tp_contact_factory_finalize (GObject *object)
1200 {
1201         EmpathyTpContactFactoryPriv *priv = GET_PRIV (object);
1202         GList                       *l;
1203
1204         empathy_debug (DEBUG_DOMAIN, "Finalized: %p (%s)",
1205                        object,
1206                        mc_account_get_normalized_name (priv->account));
1207
1208         tp_contact_factory_disconnect (EMPATHY_TP_CONTACT_FACTORY (object));
1209         dbus_g_proxy_disconnect_signal (DBUS_G_PROXY (priv->mc),
1210                                         "AccountStatusChanged",
1211                                         G_CALLBACK (tp_contact_factory_status_changed_cb),
1212                                         object);
1213
1214         for (l = priv->contacts; l; l = l->next) {
1215                 g_object_weak_unref (G_OBJECT (l->data),
1216                                      tp_contact_factory_weak_notify,
1217                                      object);
1218         }
1219
1220         g_list_free (priv->contacts);
1221         g_object_unref (priv->mc);
1222         g_object_unref (priv->account);
1223
1224         if (priv->tp_conn) {
1225                 g_object_unref (priv->tp_conn);
1226         }
1227
1228         G_OBJECT_CLASS (empathy_tp_contact_factory_parent_class)->finalize (object);
1229 }
1230
1231 static GObject *
1232 tp_contact_factory_constructor (GType                  type,
1233                                 guint                  n_props,
1234                                 GObjectConstructParam *props)
1235 {
1236         GObject *tp_factory;
1237
1238         tp_factory = G_OBJECT_CLASS (empathy_tp_contact_factory_parent_class)->constructor (type, n_props, props);
1239
1240         tp_contact_factory_update (EMPATHY_TP_CONTACT_FACTORY (tp_factory));
1241
1242         return tp_factory;
1243 }
1244
1245
1246 static void
1247 empathy_tp_contact_factory_class_init (EmpathyTpContactFactoryClass *klass)
1248 {
1249         GObjectClass *object_class = G_OBJECT_CLASS (klass);
1250
1251         object_class->finalize = tp_contact_factory_finalize;
1252         object_class->constructor = tp_contact_factory_constructor;
1253         object_class->get_property = tp_contact_factory_get_property;
1254         object_class->set_property = tp_contact_factory_set_property;
1255
1256         /* Construct-only properties */
1257         g_object_class_install_property (object_class,
1258                                          PROP_ACCOUNT,
1259                                          g_param_spec_object ("account",
1260                                                               "Factory's Account",
1261                                                               "The account associated with the factory",
1262                                                               MC_TYPE_ACCOUNT,
1263                                                               G_PARAM_READWRITE |
1264                                                               G_PARAM_CONSTRUCT_ONLY));
1265
1266         g_type_class_add_private (object_class, sizeof (EmpathyTpContactFactoryPriv));
1267 }
1268
1269 static void
1270 empathy_tp_contact_factory_init (EmpathyTpContactFactory *tp_factory)
1271 {
1272         EmpathyTpContactFactoryPriv *priv = GET_PRIV (tp_factory);
1273
1274         priv->mc = empathy_mission_control_new ();
1275         dbus_g_proxy_connect_signal (DBUS_G_PROXY (priv->mc),
1276                                      "AccountStatusChanged",
1277                                      G_CALLBACK (tp_contact_factory_status_changed_cb),
1278                                      tp_factory, NULL);
1279 }
1280
1281 EmpathyTpContactFactory *
1282 empathy_tp_contact_factory_new (McAccount *account)
1283 {
1284         return g_object_new (EMPATHY_TYPE_TP_CONTACT_FACTORY,
1285                              "account", account,
1286                              NULL);
1287 }
1288