summaryrefslogtreecommitdiff
path: root/backends/telepathy/lib/tpf-persona-store.vala
blob: 1e04efc9b07c9efa8cb74049ba552d2b5aacece7 (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
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
/*
 * Copyright (C) 2010 Collabora Ltd.
 * Copyright (C) 2013 Philip Withnall
 *
 * 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, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *       Travis Reitter <travis.reitter@collabora.co.uk>
 *       Philip Withnall <philip.withnall@collabora.co.uk>
 *       Xavier Claessens <xavier.claessens@collabora.co.uk>
 */

using GLib;
using Gee;
using TelepathyGLib;
using Folks;

extern const string G_LOG_DOMAIN;
extern const string BACKEND_NAME;

/**
 * A persona store which is associated with a single Telepathy account. It will
 * create {@link Persona}s for each of the contacts in the account's
 * contact list.
 *
 * User must define contact features it wants on the #TpSimpleClientFactory of
 * the default #TpAccountManager returned by tp_account_manager_dup() *before*
 * preparing telepathy stores. Note that this is a behaviour change since
 * 0.7.0, folks won't force preparing any feature anymore.
 */
public class Tpf.PersonaStore : Folks.PersonaStore
{
  private string[] _always_writeable_properties = {};

  /* Sets of Personas exposed by this store.
   * This is the roster + self_contact */
  private HashMap<string, Persona> _personas;
  private Map<string, Persona> _personas_ro;
  private HashSet<Persona> _persona_set;

  /* Map from weakly-referenced TpContacts to their Persona.
   * This map contains all the TpContact we know about, could be more than the
   * the roster. Persona is kept in the map until its TpContact is disposed. */
  private HashMap<unowned Contact, Persona> _contact_persona_map;

  /* TpContact IDs. Note that this should *not* be cleared in _reset().
   * See bgo#630822. */
  private SmallSet<string> _favourite_ids = new SmallSet<string> ();

  /* Mapping from Persona IIDs to their avatars. This allows avatars to persist
   * between the cached (offline) personas and the online personas. Note that
   * this should *not* be cleared in _reset(). */
  private HashMap<string, File> _avatars = new HashMap<string, File> ();

  private Connection? _conn; /* null when disconnected */
  private AccountManager? _account_manager; /* only null before prepare() */
  private Logger _logger;
  private Persona? _self_persona;

  /* Connection's capabilities */
  private MaybeBool _can_add_personas = MaybeBool.UNSET;
  private MaybeBool _can_alias_personas = MaybeBool.UNSET;
  private MaybeBool _can_group_personas = MaybeBool.UNSET;
  private MaybeBool _can_remove_personas = MaybeBool.UNSET;

  private bool _is_prepared = false;
  private bool _prepare_pending = false;
  private bool _is_quiescent = false;
  private bool _got_initial_members = false;
  private bool _got_initial_self_contact = false;
  /* true iff in the middle of storing/loading the cache while disconnecting */
  private bool _disconnect_pending = false;
  /* true iff the store should be removed after disconnection is complete */
  private bool _removal_pending = false;

  private Debug _debug;
  private PersonaStoreCache _cache;
  private Cancellable? _load_cache_cancellable = null;
  /* Whether data in memory is dirty and needs flushing to the cache at some
   * point. For example, this will be true if a contact has updated their avatar
   * while we've been online. */
  private bool _cache_needs_update = false;

  /* marshalled from ContactInfo.SupportedFields */
  private SmallSet<string> _supported_fields;
  private Set<string> _supported_fields_ro;

  private Account _account;

  private FolksTpZeitgeist.Controller _zg_controller;

  /**
   * The Telepathy account this store is based upon.
   */
  [Property(nick = "basis account",
      blurb = "Telepathy account this store is based upon")]
  public Account account
    {
      get { return this._account; }
      construct
        {
          this._account = value;
          this._account.invalidated.connect (this._account_invalidated_cb);
        }
    }

  /**
   * The type of persona store this is.
   *
   * See {@link Folks.PersonaStore.type_id}.
   */
  public override string type_id { get { return BACKEND_NAME; } }

  /**
   * Whether this PersonaStore can add {@link Folks.Persona}s.
   *
   * See {@link Folks.PersonaStore.can_add_personas}.
   *
   * @since 0.3.1
   */
  public override MaybeBool can_add_personas
    {
      get { return this._can_add_personas; }
    }

  /**
   * Whether this PersonaStore can set the alias of {@link Folks.Persona}s.
   *
   * See {@link Folks.PersonaStore.can_alias_personas}.
   *
   * @since 0.3.1
   */
  public override MaybeBool can_alias_personas
    {
      get { return this._can_alias_personas; }
    }

  /**
   * Whether this PersonaStore can set the groups of {@link Folks.Persona}s.
   *
   * See {@link Folks.PersonaStore.can_group_personas}.
   *
   * @since 0.3.1
   */
  public override MaybeBool can_group_personas
    {
      get { return this._can_group_personas; }
    }

  /**
   * Whether this PersonaStore can remove {@link Folks.Persona}s.
   *
   * See {@link Folks.PersonaStore.can_remove_personas}.
   *
   * @since 0.3.1
   */
  public override MaybeBool can_remove_personas
    {
      get { return this._can_remove_personas; }
    }

  /**
   * Whether this PersonaStore has been prepared.
   *
   * See {@link Folks.PersonaStore.is_prepared}.
   *
   * @since 0.3.0
   */
  public override bool is_prepared
    {
      get { return this._is_prepared; }
    }

  /**
   * {@inheritDoc}
   *
   * @since 0.6.2
   */
  public override string[] always_writeable_properties
    {
      get { return this._always_writeable_properties; }
    }

  /*
   * Whether this PersonaStore has reached a quiescent state.
   *
   * See {@link Folks.PersonaStore.is_quiescent}.
   *
   * @since 0.6.2
   */
  public override bool is_quiescent
    {
      get { return this._is_quiescent; }
    }

  private void _notify_if_is_quiescent ()
    {
      if (this._got_initial_members == true &&
          this._got_initial_self_contact == true &&
          this._is_quiescent == false)
        {
          this._is_quiescent = true;
          this.notify_property ("is-quiescent");
        }
    }

  private void _force_quiescent ()
    {
        this._got_initial_self_contact = true;
        this._got_initial_members = true;
        this._notify_if_is_quiescent ();
    }

  /**
   * The {@link Persona}s exposed by this PersonaStore.
   *
   * See {@link Folks.PersonaStore.personas}.
   */
  public override Map<string, Persona> personas
    {
      get { return this._personas_ro; }
    }

  internal Set<string> supported_fields
    {
      get { return this._supported_fields_ro; }
    }

  /**
   * Create a new PersonaStore.
   *
   * Create a new persona store to store the {@link Persona}s for the contacts
   * in the Telepathy account provided by ``account``.
   *
   * @param account the Telepathy account being represented by the persona store
   */
  public PersonaStore (Account account)
    {
      Object (account: account,
              display_name: account.display_name,
              id: account.get_object_path ());
    }

  construct
    {
      debug ("Creating new Tpf.PersonaStore %p ('%s') for TpAccount %p.",
          this, this.id, this.account);

      this._debug = Debug.dup ();
      this._debug.print_status.connect (this._debug_print_status);

      // Add to the map of persona stores by account
      PersonaStore._add_store_to_map (this);

      // Set up the cache
      this._cache = new PersonaStoreCache (this);

      this._reset ();
    }

  ~PersonaStore ()
    {
      debug ("Destroying Tpf.PersonaStore %p ('%s').", this, this.id);

      this._reset ();

      // Remove from the map of persona stores by account
      PersonaStore._remove_store_from_map (this);

      this._debug.print_status.disconnect (this._debug_print_status);
      this._debug = null;
      if (this._logger != null)
        this._logger.invalidated.disconnect (this._logger_invalidated_cb);

      this._account.invalidated.disconnect (this._account_invalidated_cb);

      if (this._account_manager != null)
        {
          this._account_manager.invalidated.disconnect (
              this._account_manager_invalidated_cb);
          this._account_manager = null;
        }

      this._zg_controller = null;
    }

  private string _format_maybe_bool (MaybeBool input)
    {
      switch (input)
        {
          case MaybeBool.UNSET:
            return "unset";
          case MaybeBool.TRUE:
            return "true";
          case MaybeBool.FALSE:
            return "false";
          default:
            assert_not_reached ();
        }
    }

  private void _debug_print_status (Debug debug)
    {
      const string domain = Debug.STATUS_LOG_DOMAIN;
      const LogLevelFlags level = LogLevelFlags.LEVEL_INFO;

      debug.print_heading (domain, level, "Tpf.PersonaStore (%p)", this);
      debug.print_key_value_pairs (domain, level,
          "ID", this.id,
          "Prepared?", this._is_prepared ? "yes" : "no",
          "Has initial members?", this._got_initial_members ? "yes" : "no",
          "Has self contact?", this._got_initial_self_contact ? "yes" : "no",
          "TpConnection", "%p".printf (this._conn),
          "TpAccountManager", "%p".printf (this._account_manager),
          "Self-Persona", "%p".printf (this._self_persona),
          "Can add personas?", this._format_maybe_bool (this._can_add_personas),
          "Can alias personas?",
              this._format_maybe_bool (this._can_alias_personas),
          "Can group personas?",
              this._format_maybe_bool (this._can_group_personas),
          "Can remove personas?",
              this._format_maybe_bool (this._can_remove_personas)
      );

      debug.print_line (domain, level, "%u Personas:", this._persona_set.size);
      debug.indent ();

      foreach (var persona in this._persona_set)
        {
          debug.print_heading (domain, level, "Persona (%p)", persona);
          debug.print_key_value_pairs (domain, level,
              "UID", persona.uid,
              "IID", persona.iid,
              "Display ID", persona.display_id,
              "User?", persona.is_user ? "yes" : "no",
              "In contact list?", persona.is_in_contact_list ? "yes" : "no",
              "TpContact", "%p".printf (persona.contact)
          );
        }

      debug.unindent ();

      debug.print_line (domain, level, "%u TpContact–Persona mappings:",
          this._contact_persona_map.size);
      debug.indent ();

      var iter1 = this._contact_persona_map.map_iterator ();
      while (iter1.next () == true)
        {
          debug.print_line (domain, level,
              "%s → %p", iter1.get_key ().get_identifier (), iter1.get_value ());
        }

      debug.unindent ();

      debug.print_line (domain, level, "%u favourite TpContact IDs:",
          this._favourite_ids.size);
      debug.indent ();

      foreach (var id in this._favourite_ids)
        {
          debug.print_line (domain, level, "%s", id);
        }

      debug.unindent ();

      debug.print_line (domain, level, "Cached avatars for %u personas:",
          this._avatars.size);
      debug.indent ();

      foreach (var id in this._avatars.keys)
        {
          debug.print_line (domain, level, "%s", id);
        }

      debug.unindent ();

      debug.print_line (domain, level, "");
    }

  private void _reset ()
    {
      debug ("Resetting Tpf.PersonaStore %p ('%s')", this, this.id);

      /* We do not trust local-xmpp or IRC at all, since Persona UIDs can be
       * faked by just changing hostname/username or nickname. */
      if (account.get_protocol () == "local-xmpp" ||
          account.get_protocol () == "irc")
        this.trust_level = PersonaStoreTrust.NONE;
      else
        this.trust_level = PersonaStoreTrust.PARTIAL;

      this._personas = new HashMap<string, Persona> ();
      this._personas_ro = this._personas.read_only_view;
      this._persona_set = new HashSet<Persona> ();
      this._cache_needs_update = false;

      if (this._conn != null)
        {
          this._conn.notify["self-contact"].disconnect (
              this._self_contact_changed_cb);
          this._conn.notify["contact-list-state"].disconnect (
              this._contact_list_state_changed_cb);
          this._conn.contact_list_changed.disconnect (
              this._contact_list_changed_cb);

          this._conn = null;
        }

      if (this._contact_persona_map != null)
        {
          var iter = this._contact_persona_map.map_iterator ();
          while (iter.next () == true)
            {
              var contact = iter.get_key ();
              contact.weak_unref (this._contact_weak_notify_cb);
            }
        }

      this._contact_persona_map = new HashMap<unowned Contact, Persona> ();

      this._supported_fields = new SmallSet<string> ();
      this._supported_fields_ro = this._supported_fields.read_only_view;
      this._self_persona = null;
    }

  private void _remove_store (Set<Persona> old_personas)
    {
      if (this._disconnect_pending == true)
        {
          /* The removal will be completed in _notify_connection_cb().
           * See: bgo#683390. */
          debug ("Delaying removing store %s (%p) due to pending disconnect.",
              this.id, this);
          this._removal_pending = true;
        }
      else
        {
          debug ("Removing store %s (%p)", this.id, this);
          this._removal_pending = false;

          this._emit_personas_changed (null, old_personas);
          this._cache.clear_cache.begin ();

          this.removed ();
        }
    }

  /**
   * Prepare the PersonaStore for use.
   *
   * See {@link Folks.PersonaStore.prepare}.
   *
   * @throws GLib.Error currently unused
   */
  public override async void prepare () throws GLib.Error
    {
      Internal.profiling_start ("preparing Tpf.PersonaStore (ID: %s)", this.id);

      if (this._is_prepared || this._prepare_pending)
        {
          return;
        }

      try
        {
          this._prepare_pending = true;

          this._account_manager = AccountManager.dup ();

          /* FIXME: Add all contact features on AM's factory. We should not
           * force preparing all features but let app define what it needs,
           * but this is for backward compatibility.
           * Note that if application already prepared TpContacts before
           * preparing this store, this will have no effect on existing
           * contacts. */
          var factory = this._account_manager.get_factory ();
          factory.add_contact_features ({
              ContactFeature.ALIAS,
              ContactFeature.AVATAR_DATA,
              ContactFeature.AVATAR_TOKEN,
              ContactFeature.CAPABILITIES,
              ContactFeature.CLIENT_TYPES,
              ContactFeature.PRESENCE,
              ContactFeature.CONTACT_INFO,
              ContactFeature.CONTACT_GROUPS
          });

          this._account_manager.invalidated.connect (
              this._account_manager_invalidated_cb);

          /* Note: For the three signal handlers below, we do *not* need to
           * store personas to the cache before removing the store, as
           * _remove_store() deletes the cache file. */
          this._account_manager.account_removed.connect ((a) =>
            {
              if (this.account == a)
                {
                  debug ("Account %p (‘%s’) removed.", a, a.display_name);
                  this._remove_store (this._persona_set);
                }
            });
          this._account_manager.account_validity_changed.connect (
              (a, valid) =>
                {
                  if (!valid && this.account == a)
                    {
                      debug ("Account %p (‘%s’) invalid.", a,
                          a.display_name);
                      this._remove_store (this._persona_set);
                    }
                });
          this._account_manager.account_disabled.connect ((a) =>
            {
              if (this.account == a)
                {
                  debug ("Account %p (‘%s’) disabled.", a, a.display_name);
                  this._remove_store (this._persona_set);
                }
            });

          Internal.profiling_point ("created account manager in " +
              "Tpf.PersonaStore (ID: %s)", this.id);

          this._avatars.clear ();

          this._favourite_ids.clear ();
          this._logger = new Logger (this.id);
          this._logger.invalidated.connect (
              this._logger_invalidated_cb);
          this._logger.favourite_contacts_changed.connect (
              this._favourite_contacts_changed_cb);
          Internal.profiling_start ("initialising favourite contacts in " +
              "Tpf.PersonaStore (ID: %s)", this.id);
          this._initialise_favourite_contacts.begin ((o, r) =>
            {
              try
                {
                  this._initialise_favourite_contacts.end (r);
                  Internal.profiling_end ("initialising favourite " +
                      "contacts in Tpf.PersonaStore (ID: %s)", this.id);
                }
              catch (GLib.Error e)
                {
                  debug ("Failed to initialise favourite contacts: %s",
                      e.message);
                  this._logger = null;
                }
            });

          Internal.profiling_point ("created logger in Tpf.PersonaStore " +
              "(ID: %s)", this.id);

          this.account.notify["connection"].connect (
              this._notify_connection_cb);

          /* immediately handle accounts which are not currently being
           * disconnected */
          if (this.account.connection != null)
            {
              this._notify_connection_cb (this.account, null);
            }
          else
            {
              /* If we're disconnected, advertise personas from the cache
               * instead. */
              yield this._load_cache (null);
              this._force_quiescent ();
            }

          Internal.profiling_point ("loaded cache in Tpf.PersonaStore " +
              "(ID: %s)", this.id);

          this._is_prepared = true;
          this.notify_property ("is-prepared");
        }
      finally
        {
          this._prepare_pending = false;
        }

      Internal.profiling_end ("preparing Tpf.PersonaStore (ID: %s)", this.id);
    }

  private void _account_manager_invalidated_cb (uint domain, int code,
      string message)
    {
      debug ("TpAccountManager invalidated (%u, %i, “%s”) for " +
          "Tpf.PersonaStore %p (‘%s’).", domain, code, message, this, this.id);
      this._remove_store (this._persona_set);
    }

  private void _account_invalidated_cb (uint domain, int code, string message)
    {
      debug ("TpAccount invalidated (%u, %i, “%s”) for " +
          "Tpf.PersonaStore %p (‘%s’).", domain, code, message, this, this.id);
      this._remove_store (this._persona_set);
    }

  private void _logger_invalidated_cb ()
    {
      this._logger.invalidated.disconnect (this._logger_invalidated_cb);

      debug ("Lost connection to the telepathy-logger service.");
      this._logger = null;
    }

  /* This method is not safe to call multiple times concurrently. */
  private async void _initialise_favourite_contacts () throws GLib.Error
    {
      if (this._logger == null)
        return;

      yield this._logger.prepare ();

      var contacts = yield this._logger.get_favourite_contacts ();
      this._favourite_contacts_changed_cb (contacts, {});

      this._always_writeable_properties += "is-favourite";
      this.notify_property ("always-writeable-properties");
    }

  private Persona? _lookup_persona_by_id (string id)
    {
      /* This is not efficient, but better than doing DBus roundtrip to get a
       * TpContact. */
      var iter = this._contact_persona_map.map_iterator ();
      while (iter.next ())
        {
          if (iter.get_key ().get_identifier () == id)
            {
              return iter.get_value ();
            }
        }
      return null;
    }

  private void _favourite_contacts_changed_cb (string[] added, string[] removed)
    {
      foreach (var id in added)
        {
          this._favourite_ids.add (id);
          var p = this._lookup_persona_by_id (id);
          if (p != null)
            {
              p._set_is_favourite (true);
            }
        }
      foreach (var id in removed)
        {
          this._favourite_ids.remove (id);
          var p = this._lookup_persona_by_id (id);
          if (p != null)
            {
              p._set_is_favourite (false);
            }
        }
    }

  /* This is called when we go online, when the user chooses to go offline, or
   * when a CM crashes. */
  private void _notify_connection_cb (Object s, ParamSpec? p)
    {
      var account = s as TelepathyGLib.Account;

      debug ("Account '%s' connection changed to %p", this.id,
          account.connection);

      /* account disconnected */
      if (account.connection == null)
        {
          this._supported_fields.clear ();
          this.notify_property ("supported-fields");

          /* When disconnecting, we want the PersonaStore to remain alive, but
           * all its Personas to be removed. We do *not* want the PersonaStore
           * to be destroyed, as that makes coming back online hard.
           *
           * We have to start advertising personas from the cache instead.
           * This will implicitly notify about removal of the existing persona
           * set and call this._reset().
           *
           * Before we do this, we store the current set of personas to the
           * cache, assuming we were connected before. */
          if (this._conn != null)
            {
              this._disconnect_pending = true;

              /* Call reset immediately, otherwise TpConnection's invalidation
               * will cause all contacts to weak notify. See bug #675141 */
              var old_personas = this._persona_set;
              var old_cache_needs_update = this._cache_needs_update;
              this._reset ();

              if (old_cache_needs_update)
                {
                  this._set_cache_needs_update ();
                }

              this._store_cache.begin (old_personas, (o, r) =>
                {
                  this._store_cache.end (r);

                  this._disconnect_pending = false;

                  if (this._removal_pending == false)
                    {
                      this._load_cache.begin (old_personas, (o2, r2) =>
                        {
                          this._load_cache.end (r2);
                        });
                    }
                  else
                    {
                      /* If the PersonaStore has been invalidated or disabled,
                       * remove it. This is done here rather than in the
                       * signal handlers for account-disabled or
                       * account-validity-changed so that the cache is handled
                       * properly. See: bgo#683390. */
                      assert (this._disconnect_pending == false);
                      this._remove_store (old_personas);
                    }
                });
            }

          /* If the persona store starts offline, we've reached a quiescent
           * state. */
          this._force_quiescent ();

          return;
        }

      this._notify_connection_cb_async.begin ();
    }

  private async void _notify_connection_cb_async () throws GLib.Error
    {
      debug ("_notify_connection_cb_async() for Tpf.PersonaStore %p ('%s').",
          this, this.id);

      Internal.profiling_start ("notify connection for Tpf.PersonaStore " +
          "(ID: %s)", this.id);

      /* Ensure the connection is prepared as necessary. */
      yield this.account.connection.prepare_async ({
          TelepathyGLib.Connection.get_feature_quark_contact_list (),
          TelepathyGLib.Connection.get_feature_quark_contact_groups (),
          TelepathyGLib.Connection.get_feature_quark_contact_info (),
          TelepathyGLib.Connection.get_feature_quark_connected (),
          0
      });

      if (!this.account.connection.has_interface_by_id (
          iface_quark_connection_interface_contact_list ()))
        {
          debug ("Connection does not implement ContactList iface; " +
              "legacy CMs are not supported any more.");

          this._remove_store (this._persona_set);

          return;
        }

      // We're connected, so can stop advertising personas from the cache
      this._unload_cache ();

      this._conn = this.account.connection;

      /* Connect signals early so that cleaning up is easier if the connection
       * is disconnected during the 'yield' below. */
      this._conn.notify["self-contact"].connect (
          this._self_contact_changed_cb);
      this._conn.notify["contact-list-state"].connect (
          this._contact_list_state_changed_cb);

      /* FIXME: TpConnection still does not have high-level API for this.
       * See fd.o#14540 */
      /* We have to do this before emitting the self persona so that code which
       * checks the self persona's writeable fields gets correct values. */
      var flags = 0;

      try
        {
          flags = yield FolksTpLowlevel.connection_get_alias_flags_async (
              this._conn);

          /* It's possible for the connection to have disconnected while in
           * the async function call. (See bgo#683093.) If so, bail. */
          if (this._conn == null)
            {
              return;
            }
        }
      catch (GLib.Error e)
        {
          GLib.warning (
              /* Translators: the first parameter is the display name for
               * the Telepathy account, and the second is an error
               * message. */
              _("Failed to determine whether we can set aliases on Telepathy account '%s': %s"),
              this.display_name, e.message);
        }

      /* Emit all the notifications after the 'yield' just in case the
       * connection disappears during it. This makes cleaning up easier. */
      this.freeze_notify ();
      this._marshall_supported_fields ();
      this.notify_property ("supported-fields");

      if (this._conn.get_group_storage () != ContactMetadataStorageType.NONE)
        {
          this._can_group_personas = MaybeBool.TRUE;

          this._always_writeable_properties += "groups";
          this.notify_property ("always-writeable-properties");
        }
      else
        {
          this._can_group_personas = MaybeBool.FALSE;
        }
      this.notify_property ("can-group-personas");

      if (this._conn.get_can_change_contact_list ())
        {
          this._can_add_personas = MaybeBool.TRUE;
          this._can_remove_personas = MaybeBool.TRUE;
        }
      else
        {
          this._can_add_personas = MaybeBool.FALSE;
          this._can_remove_personas = MaybeBool.FALSE;
        }
      this.notify_property ("can-add-personas");
      this.notify_property ("can-remove-personas");

      var new_can_alias = MaybeBool.FALSE;

      if ((flags & ConnectionAliasFlags.CONNECTION_ALIAS_FLAG_USER_SET) > 0)
        {
          new_can_alias = MaybeBool.TRUE;

          this._always_writeable_properties += "alias";
          this.notify_property ("always-writeable-properties");
        }

      this._can_alias_personas = new_can_alias;
      this.notify_property ("can-alias-personas");

      this.thaw_notify ();

      /* Add the local user */
      this._self_contact_changed_cb (this._conn, null);
      this._contact_list_state_changed_cb (this._conn, null);

      Internal.profiling_end ("notify connection for Tpf.PersonaStore " +
          "(ID: %s)", this.id);
    }

  private void _marshall_supported_fields ()
    {
      var connection = this.account.connection;
      if (connection != null)
        {
          this._supported_fields.clear ();

          var ci_flags = connection.get_contact_info_flags ();
          if ((ci_flags & ContactInfoFlags.CAN_SET) != 0)
            {
              var field_specs =
                connection.get_contact_info_supported_fields ();
              foreach (var field_spec in field_specs)
                {
                  /* XXX: we ignore the maximum count for each type of
                    * field since the common-sense count for each
                    * corresponding field (eg, full-name max = 1) in
                    * Folks is already reflected in our API and we have
                    * no other way to express it; but this seems a very
                    * minor problem */
                  this._supported_fields.add (field_spec.name);
                }
            }
        }
    }

  /**
   * If our account is disconnected, we want to continue to export a static
   * view of personas from the cache. old_personas will be notified as removed.
   *
   * This method is safe to call multiple times concurrently. Previous calls
   * will be cancelled by subsequent calls.
   */
  private async void _load_cache (HashSet<Persona>? old_personas)
    {
      /* Only load from the cache if the account is enabled and valid. */
      if (this.account.enabled == false || this.account.valid == false)
        {
          debug ("Skipping loading cache for Tpf.PersonaStore %p ('%s'): " +
              "enabled: %s, valid: %s.", this, this.id,
              this.account.enabled ? "yes" : "no",
              this.account.valid ? "yes" : "no");

          return;
        }

      debug ("Loading cache for Tpf.PersonaStore %p ('%s').", this, this.id);

      var cancellable = new Cancellable ();

      if (this._load_cache_cancellable != null)
        {
          debug ("    Cancelling ongoing loading operation (cancellable: %p).",
              this._load_cache_cancellable);
          this._load_cache_cancellable.cancel ();
        }

      this._load_cache_cancellable = cancellable;

      // Load the persona set from the cache and notify of the change
      var cached_personas = yield this._cache.load_objects (cancellable);

      /* If the load operation was cancelled, don't change the state
       * of the persona store at all. */
      if (cancellable.is_cancelled () == true)
        {
          debug ("    Cancelled (cancellable: %p).", cancellable);
          return;
        }

      this._reset ();

      this._persona_set = new HashSet<Persona> ();
      if (cached_personas != null)
        {
          foreach (var p in cached_personas)
            {
              this._add_persona (p);
            }
        }

      this._emit_personas_changed (cached_personas, old_personas,
          null, null, GroupDetails.ChangeReason.NONE);

      this._can_add_personas = MaybeBool.FALSE;
      this._can_alias_personas = MaybeBool.FALSE;
      this._can_group_personas = MaybeBool.FALSE;
      this._can_remove_personas = MaybeBool.FALSE;

      if (this._logger != null)
        {
          this._always_writeable_properties = { "is-favourite" };
        }
      else
        {
          this._always_writeable_properties = {};
        }

      this.notify_property ("always-writeable-properties");
    }

  /* This method is safe to call multiple times concurrently. */
  public override async void flush ()
    {
      debug ("Flushing Tpf.PersonaStore %p (‘%s’).", this, this.id);

      /* Store the cache if it needs an update. */
      yield this._store_cache (this._persona_set);
    }

  /**
   * Called when a contact property is set which is not accessible when either
   * the contact is offline or we're offline. For example, a contact's avatar.
   * This will cause the cache to be stored when the PersonaStore is destroyed.
   */
  internal void _set_cache_needs_update ()
    {
      debug ("Setting cache as needing an update for Tpf.PersonaStore " +
          "%p (‘%s’).", this, this.id);
      this._cache_needs_update = true;
    }

  /**
   * When we're about to disconnect, store the current set of personas to the
   * cache file so that we can access them once offline.
   *
   * This method is safe to call multiple times concurrently.
   */
  private async void _store_cache (HashSet<Persona> old_personas)
    {
      /* Only store/load the cache if the account is enabled and valid;
       * otherwise, the PersonaStore will get removed and the cache
       * deleted later anyway. */
      if (!this.account.enabled || !this.account.valid)
        {
          debug ("Skipping storing cache for Tpf.PersonaStore %p (‘%s’) as " +
              "its TpAccount is disabled or invalid.", this, this.id);
          return;
        }
      else if (this._cache_needs_update == false)
        {
          debug ("Skipping storing cache for Tpf.PersonaStore %p (‘%s’) as " +
              "it doesn’t need an update.", this, this.id);
          return;
        }

      debug ("Storing cache for Tpf.PersonaStore %p ('%s').", this, this.id);

      yield this._cache.store_objects (old_personas);
      this._cache_needs_update = false;
    }

  /**
   * When our account is connected again, we can unload the the personas which
   * we're advertising from the cache.
   */
  private void _unload_cache ()
    {
      debug ("Unloading cache for Tpf.PersonaStore %p ('%s').", this, this.id);

      // If we're in the process of loading from the cache, cancel that
      if (this._load_cache_cancellable != null)
        {
          debug ("    Cancelling ongoing loading operation (cancellable: %p).",
              this._load_cache_cancellable);
          this._load_cache_cancellable.cancel ();
        }

      this._emit_personas_changed (null, this._persona_set, null, null,
          GroupDetails.ChangeReason.NONE);

      this._reset ();
    }

  internal void _update_avatar_cache (string persona_iid, File? avatar_file)
    {
      if (avatar_file == null)
        {
          this._avatars.unset (persona_iid);
        }
      else
        {
          this._avatars.set (persona_iid, (!) avatar_file);
        }
    }

  internal File? _query_avatar_cache (string persona_iid)
    {
      return this._avatars.get (persona_iid);
    }

  private bool _add_persona (Persona p)
    {
      if (this._persona_set.add (p))
        {
          debug ("Add persona %p with uid %s", p, p.uid);
          this._personas.set (p.iid, p);
          return true;
        }

      return false;
    }

  private bool _remove_persona (Persona p)
    {
      if (this._persona_set.remove (p))
        {
          debug ("Remove persona %p with uid %s", p, p.uid);
          this._personas.unset (p.iid);
          if (this._self_persona == p)
            {
              this._self_persona = null;
            }

          return true;
        }

      return false;
    }

  private void _contact_weak_notify_cb (Object obj)
    {
      if (this._contact_persona_map == null)
        {
          return;
        }

      Contact contact = obj as Contact;
      debug ("Weak notify for TpContact %s", contact.get_identifier ());

      Persona? persona = null;
      this._contact_persona_map.unset (contact, out persona);
      if (persona == null)
        {
          return;
        }

      if (this._remove_persona (persona))
        {
          /* This should never happen because TpConnection keeps a ref on
           * self and roster TpContacts, so they should have been removed
           * already. But deal with it just in case... */
          warning ("A TpContact part of the ContactList is disposed");
          var personas = new SmallSet<Persona> ();
          personas.add (persona);
          this._emit_personas_changed (null, personas);
        }
    }

  /* Ensure that we have a Persona wrapping this TpContact. This will keep the
   * Persona internally only (won't emit personas_changed) and until the
   * TpContact is destroyed (we keep only weak ref). */
  internal Tpf.Persona _ensure_persona_for_contact (Contact contact)
    {
      Persona? persona = this._contact_persona_map[contact];
      if (persona != null)
        return (!) persona;

      persona = new Tpf.Persona (contact, this);
      this._contact_persona_map[contact] = persona;
      contact.weak_ref (this._contact_weak_notify_cb);

      var is_favourite = this._favourite_ids.contains (contact.get_identifier ());
      persona._set_is_favourite (is_favourite);

      debug ("Persona %p with uid %s created for TpContact %s, favourite: %s",
          persona, persona.uid, contact.get_identifier (),
          is_favourite ? "yes" : "no");

      return persona;
    }

  private void _self_contact_changed_cb (Object s, ParamSpec? p)
    {
      var contact = this._conn.self_contact;

      var personas_added = new SmallSet<Persona> ();
      var personas_removed = new SmallSet<Persona> ();

      /* Remove old self persona if not also part of roster. Keep a reference
       * to the persona so _remove_persona() doesn't unset it early. */
      var self_persona = this._self_persona;

      if (self_persona != null &&
          !self_persona.is_in_contact_list &&
          this._remove_persona (self_persona))
        {
          personas_removed.add (self_persona);
        }

      this._self_persona = null;

      if (contact != null)
        {
          /* Add the local user to roster */
          this._self_persona = this._ensure_persona_for_contact (contact);
          if (this._add_persona (this._self_persona))
            personas_added.add (this._self_persona);
        }

      this._emit_personas_changed (personas_added, personas_removed);

      this._got_initial_self_contact = true;
      this._notify_if_is_quiescent ();
    }

  private void _contact_list_state_changed_cb (Object s, ParamSpec? p)
    {
      /* Once the contact list is downloaded from server, state moves to
       * SUCCESS and won't change anymore */
      if (this._conn.contact_list_state != ContactListState.SUCCESS)
        return;

      this._conn.contact_list_changed.connect (this._contact_list_changed_cb);
      this._contact_list_changed_cb (this._conn.dup_contact_list (),
          new GLib.GenericArray<TelepathyGLib.Contact> ());

      this._got_initial_members = true;
      this._populate_counters.begin ();
      this._notify_if_is_quiescent ();
    }

  private void _contact_list_changed_cb (GLib.GenericArray<TelepathyGLib.Contact> added,
      GLib.GenericArray<TelepathyGLib.Contact> removed)
    {
      var personas_added = new HashSet<Persona> ();
      var personas_removed = new HashSet<Persona> ();

      debug ("contact list changed: %d added, %d removed",
          added.length, removed.length);

      foreach (Contact contact in added.data)
        {
          var persona = this._ensure_persona_for_contact (contact);

          if (!persona.is_in_contact_list)
            {
              persona.is_in_contact_list = true;
            }

          if (this._add_persona (persona))
            {
              personas_added.add (persona);
            }
        }

      foreach (Contact contact in removed.data)
        {
          var persona = this._contact_persona_map[contact];

          if (persona == null)
            {
              warning ("Unknown TpContact removed from ContactList: %s",
                  contact.get_identifier ());
              continue;
            }

          /* If self contact was also part of the roster but got removed,
           * we keep it in our persona store, but with is_in_contact_list=false.
           * This matches behaviour of _self_contact_changed_cb() where we add
           * the self persona into the user-visible set even if it is not part
           * of the roster. */
          if (persona == this._self_persona)
            {
              persona.is_in_contact_list = false;
              continue;
            }

          if (this._remove_persona (persona))
            {
              personas_removed.add (persona);
            }
        }

      this._emit_personas_changed (personas_added, personas_removed);
    }

  /**
   * Remove a {@link Persona} from the PersonaStore.
   *
   * See {@link Folks.PersonaStore.remove_persona}.
   *
   * @throws Folks.PersonaStoreError.UNSUPPORTED_ON_USER if ``persona`` is the
   * local user — removing the local user isn’t supported
   * @throws Folks.PersonaStoreError.REMOVE_FAILED if removing the contact
   * failed
   */
  public override async void remove_persona (Folks.Persona persona)
      throws Folks.PersonaStoreError
    {
      var tp_persona = (Tpf.Persona) persona;

      if (tp_persona.contact == null)
        {
          warning ("Skipping server-side removal of Tpf.Persona %p because " +
              "it has no attached TpContact", tp_persona);
          return;
        }

      if (persona == this._self_persona &&
          tp_persona.is_in_contact_list == false)
        {
          throw new PersonaStoreError.UNSUPPORTED_ON_USER (
              _("Telepathy contacts representing the local user may not be removed."));
        }

      try
        {
          yield tp_persona.contact.remove_async ();
        }
      catch (GLib.Error e)
        {
          /* Translators: the parameter is an error message. */
          throw new PersonaStoreError.REMOVE_FAILED (
              _("Failed to remove a persona from store: %s"), e.message);
        }
    }

  /* This method is safe to call multiple times concurrently for the same (or
   * different) contact ID, assuming Telepathy is safe. */
  private async Persona _ensure_persona_for_id (string contact_id)
      throws GLib.Error
    {
      var contact = yield this._conn.dup_contact_by_id_async (contact_id, {});
      return this._ensure_persona_for_contact (contact);
    }

  /**
   * Add a new {@link Persona} to the PersonaStore.
   *
   * See {@link Folks.PersonaStore.add_persona_from_details}.
   *
   * This method is safe to call multiple times concurrently for the same (or
   * different) contact IDs (assuming Telepathy is safe).
   *
   * @throws Folks.PersonaStoreError.INVALID_ARGUMENT if the ``contact`` key was
   * not provided in ``details``
   * @throws Folks.PersonaStoreError.STORE_OFFLINE if the CM is offline
   * @throws Folks.PersonaStoreError.CREATE_FAILED if adding the contact failed
   */
  public override async Folks.Persona? add_persona_from_details (
      HashTable<string, Value?> details) throws Folks.PersonaStoreError
    {
      var contact_id = TelepathyGLib.asv_get_string (details, "contact");
      if (contact_id == null)
        {
          throw new PersonaStoreError.INVALID_ARGUMENT (
              /* Translators: the first two parameters are store identifiers and
               * the third is a contact identifier. */
              _("Persona store (%s, %s) requires the following details:\n    contact (provided: '%s')\n"),
              this.type_id, this.id, contact_id);
        }

      // Optional message to pass to the new persona
      var add_message = TelepathyGLib.asv_get_string (details, "message");
      if (add_message == "")
        add_message = null;

      var status = this.account.get_connection_status (null);
      if ((status == TelepathyGLib.ConnectionStatus.DISCONNECTED) ||
          (status == TelepathyGLib.ConnectionStatus.CONNECTING) ||
          this._conn == null)
        {
          throw new PersonaStoreError.STORE_OFFLINE (
              _("Cannot create a new Telepathy contact while offline."));
        }

      try
        {
          var persona = yield this._ensure_persona_for_id (contact_id);
          var already_exists = persona.is_in_contact_list;
          var tp_persona = (Tpf.Persona) persona;
          yield tp_persona.contact.request_subscription_async (add_message);

          /* This function is supposed to return null if the persona was already
           * in the contact list. */
          return already_exists ? null : persona;
        }
      catch (GLib.Error e)
        {
          /* Translators: the parameter is an error message. */
          throw new PersonaStoreError.CREATE_FAILED (
              _("Failed to add a persona from details: %s"), e.message);
        }
    }

  /**
   * Change the favourite status of a persona in this store.
   *
   * This function is idempotent, but relies upon having a connection to the
   * Telepathy logger service, so may fail if that connection is not present.
   */
  internal async void change_is_favourite (Folks.Persona persona,
      bool is_favourite) throws PropertyError
    {
      /* It's possible for us to not be able to connect to the logger;
       * see _connection_ready_cb() */
      if (this._logger == null)
        {
          throw new PropertyError.UNKNOWN_ERROR (
              /* Translators: "telepathy-logger" is the name of an application,
               * and should not be translated. */
              _("Failed to change favorite without a connection to the telepathy-logger service."));
        }

      if (((Tpf.Persona) persona).contact == null)
        {
          throw new PropertyError.INVALID_VALUE (
              _("Failed to change favorite status of Telepathy Persona because it has no attached TpContact."));
        }

      try
        {
          /* Add or remove the persona to the list of favourites as
           * appropriate. */
          unowned string id = ((Tpf.Persona) persona).contact.get_identifier ();

          if (is_favourite)
            yield this._logger.add_favourite_contact (id);
          else
            yield this._logger.remove_favourite_contact (id);
        }
      catch (GLib.Error e)
        {
          throw new PropertyError.UNKNOWN_ERROR (
              /* Translators: the parameter is a contact identifier. */
              _("Failed to change favorite status for Telepathy contact ‘%s’."),
              ((Tpf.Persona) persona).contact.identifier);
        }
    }

  internal async void change_alias (Tpf.Persona persona, string alias)
      throws PropertyError
    {
      /* Deal with badly-behaved callers */
      if (alias == null)
        {
          alias = "";
        }

      if (persona.contact == null)
        {
          warning ("Skipping Tpf.Persona %p alias change to '%s' because it " +
              "has no attached TpContact", persona, alias);
          return;
        }

      try
        {
          debug ("Changing alias of persona %s to '%s'.",
              persona.contact.get_identifier (), alias);
          yield FolksTpLowlevel.connection_set_contact_alias_async (this._conn,
              (Handle) persona.contact.handle, alias);
        }
      catch (GLib.Error e1)
        {
          throw new PropertyError.UNKNOWN_ERROR (
              /* Translators: the parameter is an error message. */
              _("Failed to change contact's alias: %s"), e1.message);
        }
    }

  internal async void change_user_birthday (Tpf.Persona persona,
      DateTime? birthday) throws PersonaStoreError
    {
      string birthday_str;

      if (birthday == null)
        birthday_str = "";
      else
        birthday_str = birthday.to_string ();

      var info_set = new SmallSet<ContactInfoField> ();
      string[] values = { birthday_str };
      string[] parameters = { null };

      var field = new ContactInfoField ("bday", parameters, values);
      info_set.add (field);

      yield this._change_user_contact_info (persona, info_set);
    }

  internal async void change_user_full_name (Tpf.Persona persona,
      string full_name) throws PersonaStoreError
    {
      /* Deal with badly-behaved callers */
      if (full_name == null)
        {
          full_name = "";
        }

      var info_set = new SmallSet<ContactInfoField> ();
      string[] values = { full_name };
      string[] parameters = { null };

      var field = new ContactInfoField ("fn", parameters, values);
      info_set.add (field);

      yield this._change_user_contact_info (persona, info_set);
    }

  internal async void _change_user_details (
      Tpf.Persona persona, Set<AbstractFieldDetails<string>> details,
      string field_name)
        throws PersonaStoreError
    {
      var info_set = new SmallSet<ContactInfoField> ();

      foreach (var afd in details)
        {
          string[] values = { afd.value };
          string[] parameters = {};

          var iter = afd.parameters.map_iterator ();

          while (iter.next ())
            {
              var param_name = iter.get_key ();
              var param_value = iter.get_value ();

              parameters += @"$param_name=$param_value";
            }

          if (parameters.length == 0)
            parameters = { null };

          var field = new ContactInfoField (field_name, parameters, values);
          info_set.add (field);
        }

      yield this._change_user_contact_info (persona, info_set);
    }

  private async void _change_user_contact_info (Tpf.Persona persona,
      SmallSet<ContactInfoField> info_set) throws PersonaStoreError
    {
      if (!persona.is_user)
        {
          throw new PersonaStoreError.UNSUPPORTED_ON_NON_USER (
              _("Extended information may only be set on the user's Telepathy contact."));
        }

      var info_list = PersonaStore._contact_info_set_to_list (info_set);
      if (this.account.connection != null)
        {
          GLib.Error? error = null;
          bool success = false;
          try
            {
              success =
                yield this._conn.set_contact_info_async (
                  info_list);
            }
          catch (GLib.Error e)
            {
              error = e;
            }

          if (error != null || !success)
            {
              warning ("Failed to set extended information on user's " +
                  "Telepathy contact: %s",
                  error != null ? error.message : "(reason unknown)");
            }
        }
      else
        {
          throw new PersonaStoreError.STORE_OFFLINE (
              _("Extended information cannot be written because the store is disconnected."));
        }
    }

  private static GLib.List<ContactInfoField> _contact_info_set_to_list (
      SmallSet<ContactInfoField> info_set)
    {
      var info_list = new GLib.List<ContactInfoField> ();
      foreach (var info_field in info_set)
        {
          info_list.prepend (new ContactInfoField (
                info_field.field_name, info_field.parameters,
                info_field.field_value));
        }
      info_list.reverse ();

      return info_list;
    }

  /* Must be locked before being accessed. A ref. is held on each PersonaStore,
   * and they're only removed when they're finalised or their removed signal is
   * emitted. The map as a whole is lazily constructed and destroyed according
   * to when PersonaStores are constructed and destroyed. */
  private static HashMap<string /* Account object path */, PersonaStore>
      _persona_stores_by_account = null;
  private static Map<string, PersonaStore> _persona_stores_by_account_ro = null;

  /**
   * Get a map of all the currently constructed {@link Tpf.PersonaStore}s.
   *
   * If a {@link Folks.BackendStore} has been prepared, this map will be
   * complete, containing every store known to the Telepathy account manager. If
   * no {@link Folks.BackendStore} has been prepared, this map will only contain
   * the stores which have been created by calling
   * {@link Tpf.PersonaStore.dup_for_account}.
   *
   * This map is read-only. Use {@link Folks.BackendStore} or
   * {@link Tpf.PersonaStore.dup_for_account} to add stores.
   *
   * @return map from {@link Folks.PersonaStore.id} to {@link Tpf.PersonaStore}
   * @since 0.6.6
   */
  public static unowned Map<string, PersonaStore> list_persona_stores ()
    {
      unowned Map<string, PersonaStore> store;

      lock (PersonaStore._persona_stores_by_account)
        {
          if (PersonaStore._persona_stores_by_account == null)
            {
              PersonaStore._persona_stores_by_account =
                  new HashMap<string, PersonaStore> ();
              PersonaStore._persona_stores_by_account_ro =
                  PersonaStore._persona_stores_by_account.read_only_view;
            }

          store = PersonaStore._persona_stores_by_account_ro;
        }

      return store;
    }

  private static void _store_removed_cb (Folks.PersonaStore store)
    {
      /* Remove the store from the map. */
      PersonaStore._remove_store_from_map ((Tpf.PersonaStore) store);
    }

  private static void _add_store_to_map (PersonaStore store)
    {
      debug ("Adding PersonaStore %p ('%s') to map.", store, store.id);

      lock (PersonaStore._persona_stores_by_account)
        {
          /* Lazy construction. */
          if (PersonaStore._persona_stores_by_account == null)
            {
              PersonaStore._persona_stores_by_account =
                  new HashMap<string, PersonaStore> ();
              PersonaStore._persona_stores_by_account_ro =
                  PersonaStore._persona_stores_by_account.read_only_view;
            }

          /* Bail if a store already exists for this account. */
          return_if_fail (
              !PersonaStore._persona_stores_by_account.has_key (store.id));

          /* Add the store. */
          PersonaStore._persona_stores_by_account.set (store.id, store);
          store.removed.connect (PersonaStore._store_removed_cb);
        }
    }

  private static void _remove_store_from_map (PersonaStore store)
    {
      debug ("Removing PersonaStore %p ('%s') from map.", store, store.id);

      lock (PersonaStore._persona_stores_by_account)
        {
          /* Bail if no store existed for this account. This can happen if the
           * store emits its removed() signal (correctly) before being
           * finalised; we remove the store from the map in both cases. */
          if (PersonaStore._persona_stores_by_account == null ||
              !PersonaStore._persona_stores_by_account.unset (store.id))
            {
              return;
            }

          store.removed.disconnect (PersonaStore._store_removed_cb);

          /* Lazy destruction. */
          if (PersonaStore._persona_stores_by_account.size == 0)
            {
              PersonaStore._persona_stores_by_account_ro = null;
              PersonaStore._persona_stores_by_account = null;
            }
        }
    }

  /**
   * Look up a {@link Tpf.PersonaStore} by its {@link TelepathyGLib.Account}.
   *
   * If found, a new reference to the persona store will be returned. If not
   * found, a new {@link Tpf.PersonaStore} will be created for the account.
   *
   * See the documentation for {@link Tpf.PersonaStore.list_persona_stores} for
   * information on the lifecycle of these stores when a
   * {@link Folks.BackendStore} is and is not present.
   *
   * @param account the Telepathy account of the persona store
   * @return the persona store associated with the account
   * @since 0.6.6
   */
  public static PersonaStore dup_for_account (Account account)
    {
      PersonaStore? store = null;

      debug ("Tpf.PersonaStore.dup_for_account (%p):", account);

      lock (PersonaStore._persona_stores_by_account)
        {
          /* If the store already exists, return it. */
          if (PersonaStore._persona_stores_by_account != null)
            {
              store =
                  PersonaStore._persona_stores_by_account.get (
                      account.get_object_path ());
            }

          /* Otherwise, we have to create it. It's added to the map in its
           * constructor. */
          if (store == null)
            {
              debug ("    Creating new PersonaStore.");
              store = new PersonaStore (account);
            }
          else
            {
              debug ("    Found existing PersonaStore %p ('%s').", store,
                  store.id);
            }
        }

      return store;
    }

  /* This method is safe to call multiple times concurrently. */
  private async void _populate_counters ()
    {
      this._zg_controller = new FolksTpZeitgeist.Controller (this,
          this.account.protocol, (p, dt) =>
        {
          var persona = p as Tpf.Persona;
          assert (persona != null);
          persona._increase_im_interaction_counter (dt);
        },
          (p, dt) =>
        {
          var persona = p as Tpf.Persona;
          assert (persona != null);
          persona._increase_last_call_interaction_counter (dt);
        });
      yield this._zg_controller.populate_counters ();
      this._notify_if_is_quiescent ();
    }
}