summaryrefslogtreecommitdiff
path: root/src/conn-aliasing.c
blob: 3f803f1515ebf121382178a580fe294fdfb85ab6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
/*
 * conn-aliasing.c - Gabble connection aliasing interface
 * Copyright (C) 2005-2010 Collabora Ltd.
 * Copyright (C) 2005-2010 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"
#include "conn-aliasing.h"

#include <wocky/wocky.h>

#include <telepathy-glib/telepathy-glib.h>
#include <telepathy-glib/telepathy-glib-dbus.h>

#define DEBUG_FLAG GABBLE_DEBUG_CONNECTION

#include "connection.h"
#include "debug.h"
#include "namespaces.h"
#include "presence-cache.h"
#include "request-pipeline.h"
#include "roster.h"
#include "util.h"
#include "vcard-manager.h"

static void gabble_conn_aliasing_pep_nick_reply_handler (
    GabbleConnection *conn, WockyStanza *msg, TpHandle handle);

static GabbleConnectionAliasSource _gabble_connection_get_cached_remote_alias (
    GabbleConnection *, TpHandle, gchar **);
static void maybe_request_vcard (GabbleConnection *self, TpHandle handle,
  GabbleConnectionAliasSource source);

typedef struct _AliasesRequest AliasesRequest;

struct _AliasesRequest
{
  GabbleConnection *conn;
  DBusGMethodInvocation *request_call;
  guint pending_vcard_requests;
  guint pending_pep_requests;
  GArray *contacts;
  GabbleVCardManagerRequest **vcard_requests;
  GabbleRequestPipelineItem **pep_requests;
  gchar **aliases;
};

typedef struct
{
  AliasesRequest *aliases_request;
  guint index;
} AliasRequest;

static AliasesRequest *
aliases_request_new (GabbleConnection *conn,
                     DBusGMethodInvocation *request_call,
                     const GArray *contacts)
{
  AliasesRequest *request;

  request = g_slice_new0 (AliasesRequest);
  request->conn = conn;
  request->request_call = request_call;
  request->contacts = g_array_new (FALSE, FALSE, sizeof (TpHandle));
  g_array_insert_vals (request->contacts, 0, contacts->data, contacts->len);
  request->vcard_requests =
    g_new0 (GabbleVCardManagerRequest *, contacts->len);
  request->pep_requests =
    g_new0 (GabbleRequestPipelineItem *, contacts->len);
  request->aliases = g_new0 (gchar *, contacts->len + 1);

  return request;
}


static void
aliases_request_free (AliasesRequest *request)
{
  guint i;

  for (i = 0; i < request->contacts->len; i++)
    {
      /* FIXME: what if vcard_manager is NULL? */
      if (request->vcard_requests[i] != NULL)
        gabble_vcard_manager_cancel_request (request->conn->vcard_manager,
            request->vcard_requests[i]);
    }

  g_array_unref (request->contacts);
  g_free (request->vcard_requests);
  g_free (request->pep_requests);
  g_strfreev (request->aliases);
  g_slice_free (AliasesRequest, request);
}


static gboolean
aliases_request_try_return (AliasesRequest *request)
{
  if (request->pending_vcard_requests == 0 &&
      request->pending_pep_requests == 0)
    {
      /* Cast to (const gchar **) necessary because no-one understands 'const'
       * in C.
       */
      tp_svc_connection_interface_aliasing1_return_from_request_aliases (
          request->request_call, (const gchar **)request->aliases);
      return TRUE;
    }

  return FALSE;
}


static void
aliases_request_vcard_cb (GabbleVCardManager *manager,
                          GabbleVCardManagerRequest *request,
                          TpHandle handle,
                          WockyNode *vcard,
                          GError *error,
                          gpointer user_data)
{
  AliasesRequest *aliases_request = (AliasesRequest *) user_data;
  GabbleConnectionAliasSource source;
  guint i;
  gboolean found = FALSE;
  gchar *alias = NULL;

  g_assert (aliases_request->pending_vcard_requests > 0);

  /* The index of the vCard request in the vCard request array is the
   * index of the contact/alias in their respective arrays. */

  for (i = 0; i < aliases_request->contacts->len; i++)
    if (aliases_request->vcard_requests[i] == request)
      {
        found = TRUE;
        break;
      }

  g_assert (found);
  source = _gabble_connection_get_cached_alias (aliases_request->conn,
      g_array_index (aliases_request->contacts, TpHandle, i), &alias);
  g_assert (source != GABBLE_CONNECTION_ALIAS_NONE);
  g_assert (NULL != alias);

  aliases_request->pending_vcard_requests--;
  aliases_request->vcard_requests[i] = NULL;
  aliases_request->aliases[i] = alias;

  if (aliases_request_try_return (aliases_request))
    aliases_request_free (aliases_request);
}


static void
_cache_negatively (GabbleConnection *self,
                   TpHandle handle)
{
  /* We don't actually need to distinguish between "uncached" and
   * "known to have no alias" because of how PEP works, so just
   * remove it from the cache. */
  g_hash_table_remove (self->pep_alias_cache, GUINT_TO_POINTER (handle));
}

/* Cache pep if successful */
static void
aliases_request_cache_pep (GabbleConnection *self,
                           WockyStanza *msg,
                           TpHandle handle,
                           GError *error)
{
  if (error != NULL)
    {
      DEBUG ("Error getting alias from PEP: %s", error->message);
      _cache_negatively (self, handle);
      return;
    }
  else if (wocky_stanza_extract_errors (msg, NULL, NULL, NULL, NULL))
    {
      STANZA_DEBUG (msg, "Error getting alias from PEP");
      _cache_negatively (self, handle);
    }
  else
    {
      /* Try to extract an alias, caching it if necessary. */
      gabble_conn_aliasing_pep_nick_reply_handler (self, msg, handle);
    }

}

static void
aliases_request_basic_pep_cb (GabbleConnection *self,
                              WockyStanza *msg,
                              gpointer user_data,
                              GError *error)
{
  TpBaseConnection *base = (TpBaseConnection *) self;
  GabbleConnectionAliasSource source = GABBLE_CONNECTION_ALIAS_NONE;
  TpHandle handle = GPOINTER_TO_UINT (user_data);

  aliases_request_cache_pep (self, msg, handle, error);

  source = _gabble_connection_get_cached_alias (self, handle, NULL);

  if (source < GABBLE_CONNECTION_ALIAS_FROM_VCARD &&
      tp_base_connection_get_status (base) == TP_CONNECTION_STATUS_CONNECTED &&
      !gabble_vcard_manager_has_cached_alias (self->vcard_manager, handle))
    {
      /* no alias in PEP, get the vcard */
      gabble_vcard_manager_request (self->vcard_manager, handle, 0,
        NULL, NULL, G_OBJECT (self));
    }
}

static void
aliases_request_pep_cb (GabbleConnection *self,
                        WockyStanza *msg,
                        gpointer user_data,
                        GError *error)
{
  TpBaseConnection *base = (TpBaseConnection *) self;
  AliasRequest *alias_request = (AliasRequest *) user_data;
  AliasesRequest *aliases_request = alias_request->aliases_request;
  guint index = alias_request->index;
  TpHandle handle = g_array_index (aliases_request->contacts, TpHandle, index);
  GabbleConnectionAliasSource source = GABBLE_CONNECTION_ALIAS_NONE;
  gchar *alias = NULL;

  aliases_request->pending_pep_requests--;
  aliases_request->pep_requests[index] = NULL;
  g_slice_free (AliasRequest, alias_request);

  aliases_request_cache_pep (self, msg, handle, error);

  source = _gabble_connection_get_cached_alias (aliases_request->conn,
      handle, &alias);
  g_assert (source != GABBLE_CONNECTION_ALIAS_NONE);
  g_assert (NULL != alias);
  DEBUG ("Got cached alias %s with priority %u", alias, source);

  if (source >= GABBLE_CONNECTION_ALIAS_FROM_VCARD ||
      (self->vcard_manager != NULL &&
       gabble_vcard_manager_has_cached_alias (self->vcard_manager, handle)))
    {
      aliases_request->aliases[index] = alias;
    }
  else if (tp_base_connection_get_status (base) !=
               TP_CONNECTION_STATUS_CONNECTED)
    {
      DEBUG ("no longer connected, not chaining up to vCard");
      g_free (alias);
    }
  else
    {
      /* not in PEP and we have no vCard - chain to looking up their vCard */
      GabbleVCardManagerRequest *vcard_request = gabble_vcard_manager_request
          (self->vcard_manager, handle, 0, aliases_request_vcard_cb,
           aliases_request, G_OBJECT (self));

      g_free (alias);
      aliases_request->vcard_requests[index] = vcard_request;
      aliases_request->pending_vcard_requests++;
    }

  if (aliases_request_try_return (aliases_request))
    aliases_request_free (aliases_request);
}

typedef struct {
  GabbleRequestPipelineCb callback;
  gpointer user_data;
  TpHandleRepoIface *contact_handles;
  TpHandle handle;
} pep_request_ctx;

static void
pep_request_cb (
    GabbleConnection *conn,
    WockyStanza *msg,
    gpointer user_data,
    GError *error)
{
  pep_request_ctx *ctx = user_data;

  ctx->callback (conn, msg, ctx->user_data, error);
  g_slice_free (pep_request_ctx, ctx);
}

/**
 * @self must have %TP_CONNECTION_STATUS_CONNECTED.
 */
static GabbleRequestPipelineItem *
gabble_do_pep_request (GabbleConnection *self,
                       TpHandle handle,
                       TpHandleRepoIface *contact_handles,
                       GabbleRequestPipelineCb callback,
                       gpointer user_data)
{
  TpBaseConnection *base = (TpBaseConnection *) self;
  const gchar *to;
  WockyStanza *msg;
  GabbleRequestPipelineItem *pep_request;
  pep_request_ctx *ctx;

  /* callers must check this... */
  g_assert (tp_base_connection_get_status (base) ==
      TP_CONNECTION_STATUS_CONNECTED);
  /* ... which implies this */
  g_assert (self->req_pipeline != NULL);

  ctx = g_slice_new0 (pep_request_ctx);
  ctx->callback = callback;
  ctx->user_data = user_data;
  ctx->contact_handles = contact_handles;
  ctx->handle = handle;

  to = tp_handle_inspect (contact_handles, handle);
  msg = wocky_stanza_build (WOCKY_STANZA_TYPE_IQ, WOCKY_STANZA_SUB_TYPE_GET,
      NULL, to,
      '(', "pubsub",
        ':', NS_PUBSUB,
        '(', "items",
          '@', "node", NS_NICK,
        ')',
      ')',
      NULL);
   pep_request = gabble_request_pipeline_enqueue (self->req_pipeline,
      msg, 0, pep_request_cb, ctx);
   g_object_unref (msg);

   return pep_request;
}

/**
 * gabble_connection_request_aliases
 *
 * Implements D-Bus method RequestAliases
 * on interface Connection.Interface.Aliasing
 *
 * @context: The D-Bus invocation context to use to return values
 *           or throw an error.
 */
static void
gabble_connection_request_aliases (TpSvcConnectionInterfaceAliasing1 *iface,
                                   const GArray *contacts,
                                   DBusGMethodInvocation *context)
{
  GabbleConnection *self = GABBLE_CONNECTION (iface);
  TpBaseConnection *base = (TpBaseConnection *) self;
  TpHandleRepoIface *contact_handles = tp_base_connection_get_handles (base,
      TP_ENTITY_TYPE_CONTACT);
  guint i;
  AliasesRequest *request;
  GError *error = NULL;

  g_assert (GABBLE_IS_CONNECTION (self));

  TP_BASE_CONNECTION_ERROR_IF_NOT_CONNECTED (base, context);

  if (!tp_handles_are_valid (contact_handles, contacts, FALSE, &error))
    {
      dbus_g_method_return_error (context, error);
      g_error_free (error);
      return;
    }

  request = aliases_request_new (self, context, contacts);

  for (i = 0; i < contacts->len; i++)
    {
      TpHandle handle = g_array_index (contacts, TpHandle, i);
      GabbleConnectionAliasSource source;
      GabbleVCardManagerRequest *vcard_request;
      gchar *alias;

      source = _gabble_connection_get_cached_alias (self, handle, &alias);
      g_assert (source != GABBLE_CONNECTION_ALIAS_NONE);
      g_assert (NULL != alias);

      if (source >= GABBLE_CONNECTION_ALIAS_FROM_VCARD ||
          gabble_vcard_manager_has_cached_alias (self->vcard_manager, handle))
        {
          /* Either the alias we got was from a vCard or better, or we already
           * tried getting an alias from a vcard and failed, so there's no
           * point trying again. */
          request->aliases[i] = alias;
        }
      else if (self->features & GABBLE_CONNECTION_FEATURES_PEP)
        {
           /* FIXME: we shouldn't have to do this, since we should get PEP
            * events when someone first sends us presence. However, the
            * current ejabberd PEP implementation doesn't seem to give
            * us notifications of the initial state. */
          AliasRequest *data = g_slice_new (AliasRequest);

          g_free (alias);

          data->aliases_request = request;
          data->index = i;

          request->pending_pep_requests++;
          request->pep_requests[i] = gabble_do_pep_request (self,
              handle, contact_handles, aliases_request_pep_cb, data);

        }
      else
        {
          DEBUG ("requesting vCard for alias of contact %s",
              tp_handle_inspect (contact_handles, handle));

          g_free (alias);
          vcard_request = gabble_vcard_manager_request (self->vcard_manager,
              handle, 0, aliases_request_vcard_cb, request, G_OBJECT (self));

          request->vcard_requests[i] = vcard_request;
          request->pending_vcard_requests++;
        }
    }

  if (aliases_request_try_return (request))
    aliases_request_free (request);
}

static void
nick_publish_msg_reply_cb (GabbleConnection *conn,
                           WockyStanza *sent_msg,
                           WockyStanza *reply_msg,
                           GObject *object,
                           gpointer user_data)
{
  GError *error = NULL;

  if (wocky_stanza_extract_errors (reply_msg, NULL, &error, NULL, NULL))
    {
      DEBUG ("can't publish nick using PEP: %s: %s",
          wocky_xmpp_stanza_error_to_string (error), error->message);

      g_clear_error (&error);
    }
}

static gboolean
set_one_alias (
    GabbleConnection *conn,
    TpHandle handle,
    gchar *alias,
    GError **error)
{
  TpBaseConnection *base = (TpBaseConnection *) conn;
  TpHandleRepoIface *contact_handles = tp_base_connection_get_handles (base,
      TP_ENTITY_TYPE_CONTACT);
  gboolean ret = TRUE;

  g_assert (tp_base_connection_get_status (base) ==
      TP_CONNECTION_STATUS_CONNECTED);

  if (tp_str_empty (alias))
    alias = NULL;

  if (!tp_handle_is_valid (contact_handles, handle, error))
    {
      ret = FALSE;
    }
  else if (tp_base_connection_get_self_handle (base) == handle)
    {
      /* only alter the roster if we're already there, e.g. because someone
       * added us with another client
       */
      if (gabble_roster_handle_has_entry (conn->roster, handle)
          && !gabble_roster_handle_set_name (conn->roster, handle,
                                             alias, error))
        {
          ret = FALSE;
        }
    }
  else
    {
      gchar *remote_alias = NULL;
      GabbleConnectionAliasSource source = GABBLE_CONNECTION_ALIAS_FROM_ROSTER;

      if (alias == NULL)
        {
          source = _gabble_connection_get_cached_remote_alias (conn, handle,
              &remote_alias);
          alias = remote_alias;
        }

      ret = gabble_roster_handle_set_name (conn->roster, handle, alias, error);
      g_free (remote_alias);

      /* If we don't have a cached remote alias for this contact, try to ask
       * for one. (Maybe we haven't seen a PEP update or fetched their vCard in
       * this session?)
       */
      maybe_request_vcard (conn, handle, source);
    }

  if (tp_base_connection_get_self_handle (base) == handle)
    {
      GabbleVCardManagerEditInfo *edit;
      GQueue edits = G_QUEUE_INIT;

      /* User has called SetAliases on themselves - patch their vCard.
       * FIXME: because SetAliases is currently synchronous, we ignore errors
       * here, and just let the request happen in the background.
       */

      if (conn->features & GABBLE_CONNECTION_FEATURES_PEP)
        {
          /* Publish nick using PEP */
          WockyStanza *msg;
          WockyNode *item;

          msg = wocky_pep_service_make_publish_stanza (conn->pep_nick, &item);
          /* Does the right thing if alias == NULL. */
          wocky_node_add_child_with_content_ns (item, "nick", alias, NS_NICK);

          _gabble_connection_send_with_reply (conn, msg,
              nick_publish_msg_reply_cb, NULL, NULL, NULL);

          g_object_unref (msg);
        }

      if (alias == NULL)
        /* Deliberately not doing the fall-back-to-FN-on-GTalk dance because
         * clearing your FN is more serious.
         */
        edit = gabble_vcard_manager_edit_info_new ("NICKNAME", NULL,
            GABBLE_VCARD_EDIT_DELETE, NULL);
      else
        edit = gabble_vcard_manager_edit_info_new (NULL, alias,
            GABBLE_VCARD_EDIT_SET_ALIAS, NULL);

      g_queue_push_head (&edits, edit);
      /* Yes, gabble_vcard_manager_edit steals the list you pass it. */
      gabble_vcard_manager_edit (conn->vcard_manager, 0, NULL,
          NULL, G_OBJECT (conn), edits.head);
    }

  return ret;
}

/**
 * gabble_connection_set_aliases
 *
 * Implements D-Bus method SetAliases
 * on interface Connection.Interface.Aliasing
 */
static void
gabble_connection_set_aliases (TpSvcConnectionInterfaceAliasing1 *iface,
                               GHashTable *aliases,
                               DBusGMethodInvocation *context)
{
  GabbleConnection *self = GABBLE_CONNECTION (iface);
  TpBaseConnection *base = (TpBaseConnection *) self;
  GHashTableIter iter;
  gpointer key, value;
  gboolean retval = TRUE;
  GError *first_error = NULL;

  g_assert (GABBLE_IS_CONNECTION (self));

  TP_BASE_CONNECTION_ERROR_IF_NOT_CONNECTED (base, context);

  g_hash_table_iter_init (&iter, aliases);
  while (g_hash_table_iter_next (&iter, &key, &value))
    {
      if (!set_one_alias (self, GPOINTER_TO_UINT (key), value,
            (first_error == NULL ? &first_error : NULL)))
        retval = FALSE;
    }

  if (retval)
    {
      tp_svc_connection_interface_aliasing1_return_from_set_aliases (
          context);
    }
  else
    {
      dbus_g_method_return_error (context, first_error);
      g_error_free (first_error);
    }
}

static gboolean
_grab_nickname (GabbleConnection *self,
                TpHandle handle,
                WockyNode *node)
{
  TpBaseConnection *base = (TpBaseConnection *) self;
  TpHandleRepoIface *contact_handles = tp_base_connection_get_handles (base,
      TP_ENTITY_TYPE_CONTACT);
  const gchar *old, *nickname;

  node = wocky_node_get_child_ns (node, "nick", NS_NICK);

  if (NULL == node)
    {
      DEBUG ("didn't get a nickname for %s", tp_handle_inspect
          (contact_handles, handle));
      _cache_negatively (self, handle);
      return FALSE;
    }

  nickname = node->content;

  old = g_hash_table_lookup (self->pep_alias_cache, GUINT_TO_POINTER (handle));

  if (tp_strdiff (old, nickname))
    {
      if (nickname == NULL)
        {
          DEBUG ("got empty <nick/> node, caching negatively");
          _cache_negatively (self, handle);
        }
      else
        {
          DEBUG ("caching positively");
          g_hash_table_insert (self->pep_alias_cache, GUINT_TO_POINTER (handle),
              g_strdup (nickname));
        }

      gabble_conn_aliasing_nickname_updated ((GObject *) self, handle, self);
    }

  return TRUE;
}


static void
pep_nick_node_changed (WockyPepService *pep,
    WockyBareContact *contact,
    WockyStanza *stanza,
    WockyNode *item,
    GabbleConnection *conn)
{
  TpHandleRepoIface *contact_repo = tp_base_connection_get_handles (
      (TpBaseConnection *) conn, TP_ENTITY_TYPE_CONTACT);
  TpHandle handle;
  const gchar *jid;

  jid = wocky_bare_contact_get_jid (contact);
  handle = tp_handle_ensure (contact_repo, jid, NULL, NULL);
  if (handle == 0)
    {
      DEBUG ("Invalid from: %s", jid);
      return;
    }

  if (NULL == item)
    {
      STANZA_DEBUG (stanza, "PEP event without item node, ignoring");
      return;
    }

  _grab_nickname (conn, handle, item);
}


static void
gabble_conn_aliasing_pep_nick_reply_handler (GabbleConnection *conn,
                                             WockyStanza *msg,
                                             TpHandle handle)
{
  WockyNode *pubsub_node, *items_node, *item_node;
  gboolean found = FALSE;
  WockyNodeIter i;

  pubsub_node = wocky_node_get_child_ns (
      wocky_stanza_get_top_node (msg), "pubsub", NS_PUBSUB);
  if (pubsub_node == NULL)
    {
      pubsub_node = wocky_node_get_child_ns (
        wocky_stanza_get_top_node (msg), "pubsub", NS_PUBSUB "#event");

      if (pubsub_node == NULL)
        {
          STANZA_DEBUG (msg, "PEP reply with no <pubsub>, ignoring");
          _cache_negatively (conn, handle);
          return;
        }
      else
        {
          STANZA_DEBUG (msg, "PEP reply from buggy server with #event "
              "on <pubsub> namespace");
        }
    }

  items_node = wocky_node_get_child (pubsub_node, "items");
  if (items_node == NULL)
    {
      STANZA_DEBUG (msg, "No items in PEP reply");
      _cache_negatively (conn, handle);
      return;
    }

  wocky_node_iter_init (&i, items_node, NULL, NULL);
  while (wocky_node_iter_next (&i, &item_node))
    {
      if (_grab_nickname (conn, handle, item_node))
        {
          /* FIXME: does this do the right thing on servers which return
           * multiple items? ejabberd only returns one anyway */
          found = TRUE;
          break;
        }
    }

  if (!found)
    {
      _cache_negatively (conn, handle);
    }
}

void
gabble_conn_aliasing_nickname_updated (GObject *object,
                                       TpHandle handle,
                                       gpointer user_data)
{
  GArray *handles;

  handles = g_array_sized_new (FALSE, FALSE, sizeof (TpHandle), 1);
  g_array_append_val (handles, handle);

  gabble_conn_aliasing_nicknames_updated (object, handles, user_data);

  g_array_unref (handles);
}

void
gabble_conn_aliasing_nicknames_updated (GObject *object,
                                        GArray *handles,
                                        gpointer user_data)
{
  GabbleConnection *conn = GABBLE_CONNECTION (user_data);
  GabbleConnectionAliasSource signal_source;
  GHashTable *aliases;
  guint i;

  g_return_if_fail (handles->len > 0);

  if (object == user_data)
    {
      /* actually PEP */
      signal_source = GABBLE_CONNECTION_ALIAS_FROM_PRESENCE;
    }
  else if (object == G_OBJECT (conn->roster))
    {
      signal_source = GABBLE_CONNECTION_ALIAS_FROM_ROSTER;
    }
  else if (object == G_OBJECT (conn->presence_cache))
    {
      signal_source = GABBLE_CONNECTION_ALIAS_FROM_PRESENCE;
    }
   else if (object == G_OBJECT (conn->vcard_manager))
     {
       signal_source = GABBLE_CONNECTION_ALIAS_FROM_VCARD;
     }
  else
    {
      g_assert_not_reached ();
      return;
    }

  aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);

  for (i = 0; i < handles->len; i++)
    {
      TpHandle handle = g_array_index (handles, TpHandle, i);
      GabbleConnectionAliasSource current_source;
      gchar *alias = NULL;

      current_source = _gabble_connection_get_cached_alias (conn, handle,
          &alias);
      g_assert (current_source != GABBLE_CONNECTION_ALIAS_NONE);

      /* if the active alias for this handle is already known and from
       * a higher priority, this signal is not interesting so we do
       * nothing */
      if (signal_source < current_source)
        {
          DEBUG ("ignoring boring alias change for handle %u, signal from %u "
              "but source %u has alias \"%s\"", handle, signal_source,
              current_source, alias);
          g_free (alias);
          continue;
        }

      g_hash_table_insert (aliases, GUINT_TO_POINTER (handle),
          g_strdup (alias));

      /* Check whether the roster has an entry for the handle and if so, set
       * the roster alias so the vCard isn't fetched on every connect. */
      if (signal_source < GABBLE_CONNECTION_ALIAS_FROM_ROSTER &&
          gabble_roster_handle_has_entry (conn->roster, handle))
        gabble_roster_handle_set_name (conn->roster, handle, alias, NULL);

      g_free (alias);
    }

  if (g_hash_table_size (aliases) > 0)
    tp_svc_connection_interface_aliasing1_emit_aliases_changed (conn, aliases);

  g_hash_table_unref (aliases);
}

static void
set_or_clear (gchar **target,
    gchar *source)
{
  if (target != NULL)
    *target = source;
  else
    g_free (source);
}

static void
maybe_set (gchar **target,
    const gchar *source)
{
  if (target != NULL)
    *target = g_strdup (source);
}

static GabbleConnectionAliasSource
get_cached_remote_alias (
    GabbleConnection *conn,
    TpHandleRepoIface *contact_handles,
    TpHandle handle,
    const gchar *jid,
    gchar **alias)
{
  TpBaseConnection *base = (TpBaseConnection *) conn;
  GabblePresence *pres;
  const gchar *tmp;
  gchar *resource;

  tmp = g_hash_table_lookup (conn->pep_alias_cache, GUINT_TO_POINTER (handle));

  if (tmp != NULL)
    {
      maybe_set (alias, tmp);
      return GABBLE_CONNECTION_ALIAS_FROM_PRESENCE;
    }

  pres = gabble_presence_cache_get (conn->presence_cache, handle);
  if (NULL != pres && NULL != pres->nickname)
    {
      maybe_set (alias, pres->nickname);
      return GABBLE_CONNECTION_ALIAS_FROM_PRESENCE;
    }

  /* XXX: should this be more important than the ones from presence? */
  /* if it's our own handle, use alias passed to the connmgr, if any */
  if (handle == tp_base_connection_get_self_handle (base))
    {
      gchar *cm_alias;

      g_object_get (conn,
          "alias", &cm_alias,
          NULL);

      if (cm_alias != NULL)
        {
          set_or_clear (alias, cm_alias);
          return GABBLE_CONNECTION_ALIAS_FROM_CONNMGR;
        }
    }

  /* MUC handles have the nickname in the resource */
  if (wocky_decode_jid (jid, NULL, NULL, &resource) &&
      NULL != resource)
    {
      set_or_clear (alias, resource);
      return GABBLE_CONNECTION_ALIAS_FROM_MUC_RESOURCE;
    }

  if (conn->vcard_manager != NULL)
    {
      /* if we've seen a nickname in their vCard, use that */
      tmp = gabble_vcard_manager_get_cached_alias (conn->vcard_manager,
          handle);
      if (NULL != tmp)
        {
          maybe_set (alias, tmp);
          return GABBLE_CONNECTION_ALIAS_FROM_VCARD;
        }
    }

  maybe_set (alias, NULL);
  return GABBLE_CONNECTION_ALIAS_NONE;
}

/*
 * _gabble_connection_get_cached_alias:
 * @conn: a connection
 * @handle: a handle
 * @alias: (allow-none): location at which to store @handle's alias. If
 *         provided, it will always be set to a non-NULL, non-empty string,
 *         which the caller must free.
 *
 * Gets the best possible alias for @handle, falling back to their JID if
 * necessary.
 *
 * Returns: the source of the alias.
 */
GabbleConnectionAliasSource
_gabble_connection_get_cached_alias (GabbleConnection *conn,
                                     TpHandle handle,
                                     gchar **alias)
{
  TpBaseConnection *base = (TpBaseConnection *) conn;
  TpHandleRepoIface *contact_handles = tp_base_connection_get_handles (base,
      TP_ENTITY_TYPE_CONTACT);
  const gchar *tmp, *jid;
  gboolean roster_alias_was_jid = FALSE;
  GabbleConnectionAliasSource source;

  g_return_val_if_fail (NULL != conn, GABBLE_CONNECTION_ALIAS_NONE);
  g_return_val_if_fail (GABBLE_IS_CONNECTION (conn), GABBLE_CONNECTION_ALIAS_NONE);
  g_return_val_if_fail (tp_handle_is_valid (contact_handles, handle, NULL),
      GABBLE_CONNECTION_ALIAS_NONE);

  jid = tp_handle_inspect (contact_handles, handle);
  g_assert (NULL != jid);

  tmp = gabble_roster_handle_get_name (conn->roster, handle);
  if (!tp_strdiff (tmp, jid))
    {
      /* Normally, we prefer whatever we've cached on the roster, to avoid
       * wasting bandwidth checking for aliases by repeatedly fetching the
       * vCard, and (more importantly) to prefer anything the local user set
       * over what the contact says their name is.
       *
       * However, if the alias stored on the roster is just the contact's JID,
       * we check for better aliases that we happen to have received from other
       * sources (maybe a PEP nick update, or a vCard we've fetched for the
       * avatar, or whatever). If we can't find anything better, we'll use the
       * JID, and still say that it came from the roster: this means we don't
       * defeat negative caching for contacts who genuinely don't have an
       * alias.
       */
      roster_alias_was_jid = TRUE;
    }
  else if (!tp_str_empty (tmp))
    {
      maybe_set (alias, tmp);
      return GABBLE_CONNECTION_ALIAS_FROM_ROSTER;
    }

  source = get_cached_remote_alias (conn, contact_handles, handle, jid, alias);
  if (source != GABBLE_CONNECTION_ALIAS_NONE)
    return source;

  /* otherwise just take their jid, which may have been specified on the roster
   * as the contact's alias. */
  maybe_set (alias, jid);
  return roster_alias_was_jid ? GABBLE_CONNECTION_ALIAS_FROM_ROSTER
      : GABBLE_CONNECTION_ALIAS_FROM_JID;
}

/*
 * _gabble_connection_get_cached_remote_alias:
 * @conn: a connection
 * @handle: a handle
 * @alias: (allow-none): location at which to store @handle's alias. If
 *         provided, it may be set to %NULL (if @handle has no cached remote
 *         alias) or a non-empty string which the caller must free.
 *
 * Gets the best cached alias for @handle as provided by them (such as via PEP
 * Nicknames, in their vCard, etc), not considering anything the local user has
 * specified on their roster.
 *
 * Returns: the source of the alias, or GABBLE_CONNECTION_ALIAS_NONE if we have
 *          no cached remote alias for @handle
 */
static GabbleConnectionAliasSource
_gabble_connection_get_cached_remote_alias (
    GabbleConnection *conn,
    TpHandle handle,
    gchar **alias)
{
  TpBaseConnection *base = (TpBaseConnection *) conn;
  TpHandleRepoIface *contact_handles = tp_base_connection_get_handles (base,
      TP_ENTITY_TYPE_CONTACT);
  const gchar *jid = tp_handle_inspect (contact_handles, handle);

  g_assert (NULL != jid);
  return get_cached_remote_alias (conn, contact_handles, handle, jid, alias);
}

static void
maybe_request_vcard (GabbleConnection *self, TpHandle handle,
  GabbleConnectionAliasSource source)
{
  TpBaseConnection *base = (TpBaseConnection *) self;

  /* If the source wasn't good enough then do a request */
  if (source < GABBLE_CONNECTION_ALIAS_FROM_VCARD &&
      tp_base_connection_get_status (base) == TP_CONNECTION_STATUS_CONNECTED &&
      !gabble_vcard_manager_has_cached_alias (self->vcard_manager, handle))
    {
      if (self->features & GABBLE_CONNECTION_FEATURES_PEP)
        {
          TpHandleRepoIface *contact_handles =
            tp_base_connection_get_handles (base, TP_ENTITY_TYPE_CONTACT);

          gabble_do_pep_request (self, handle, contact_handles,
            aliases_request_basic_pep_cb, GUINT_TO_POINTER (handle));
        }
      else
        {
          gabble_vcard_manager_request (self->vcard_manager,
             handle, 0, NULL, NULL, G_OBJECT (self));
        }
    }
}

gboolean
conn_aliasing_fill_contact_attributes (GabbleConnection *self,
    const gchar *dbus_interface,
    TpHandle handle,
    TpContactAttributeMap *attributes)
{
  if (!tp_strdiff (dbus_interface, TP_IFACE_CONNECTION_INTERFACE_ALIASING1))
    {
      GabbleConnectionAliasSource source;
      gchar *alias;
      GValue *val = tp_g_value_slice_new (G_TYPE_STRING);

      source = _gabble_connection_get_cached_alias (self, handle, &alias);
      g_assert (alias != NULL);

      g_value_take_string (val, alias);

      tp_contact_attribute_map_take_sliced_gvalue (attributes,
        handle, TP_TOKEN_CONNECTION_INTERFACE_ALIASING1_ALIAS,
        val);

      maybe_request_vcard (self, handle, source);
      return TRUE;
    }

  return FALSE;
}

void
conn_aliasing_init (GabbleConnection *conn)
{
  conn->pep_nick = wocky_pep_service_new (NS_NICK, TRUE);
  conn->pep_alias_cache = g_hash_table_new_full (NULL, NULL, NULL, g_free);

  g_signal_connect (conn->pep_nick, "changed",
      G_CALLBACK (pep_nick_node_changed), conn);
}

void
conn_aliasing_finalize (GabbleConnection *conn)
{
  tp_clear_pointer (&conn->pep_alias_cache, g_hash_table_unref);
}

void
conn_aliasing_iface_init (gpointer g_iface, gpointer iface_data)
{
  TpSvcConnectionInterfaceAliasing1Class *klass = g_iface;

#define IMPLEMENT(x) tp_svc_connection_interface_aliasing1_implement_##x (\
    klass, gabble_connection_##x)
  IMPLEMENT(request_aliases);
  IMPLEMENT(set_aliases);
#undef IMPLEMENT
}