summary refs log tree commit diff
path: root/tests/rest/client/test_relations.py
blob: d3f619199684511d0b88f2970b760766aaa10b8b (plain) (blame)
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
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
# Copyright 2019 New Vector Ltd
# Copyright 2021 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import urllib.parse
from typing import Any, Callable, Dict, List, Optional, Tuple
from unittest.mock import AsyncMock, patch

from twisted.test.proto_helpers import MemoryReactor

from synapse.api.constants import AccountDataTypes, EventTypes, RelationTypes
from synapse.rest import admin
from synapse.rest.client import login, register, relations, room, sync
from synapse.server import HomeServer
from synapse.types import JsonDict
from synapse.util import Clock

from tests import unittest
from tests.server import FakeChannel
from tests.test_utils.event_injection import inject_event
from tests.unittest import override_config


class BaseRelationsTestCase(unittest.HomeserverTestCase):
    servlets = [
        relations.register_servlets,
        room.register_servlets,
        sync.register_servlets,
        login.register_servlets,
        register.register_servlets,
        admin.register_servlets_for_client_rest_resource,
    ]
    hijack_auth = False

    def default_config(self) -> Dict[str, Any]:
        # We need to enable msc1849 support for aggregations
        config = super().default_config()

        # We enable frozen dicts as relations/edits change event contents, so we
        # want to test that we don't modify the events in the caches.
        config["use_frozen_dicts"] = True

        return config

    def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
        self.store = hs.get_datastores().main

        self.user_id, self.user_token = self._create_user("alice")
        self.user2_id, self.user2_token = self._create_user("bob")

        self.room = self.helper.create_room_as(self.user_id, tok=self.user_token)
        self.helper.join(self.room, user=self.user2_id, tok=self.user2_token)
        res = self.helper.send(self.room, body="Hi!", tok=self.user_token)
        self.parent_id = res["event_id"]

    def _create_user(self, localpart: str) -> Tuple[str, str]:
        user_id = self.register_user(localpart, "abc123")
        access_token = self.login(localpart, "abc123")

        return user_id, access_token

    def _send_relation(
        self,
        relation_type: str,
        event_type: str,
        key: Optional[str] = None,
        content: Optional[dict] = None,
        access_token: Optional[str] = None,
        parent_id: Optional[str] = None,
        expected_response_code: int = 200,
    ) -> FakeChannel:
        """Helper function to send a relation pointing at `self.parent_id`

        Args:
            relation_type: One of `RelationTypes`
            event_type: The type of the event to create
            key: The aggregation key used for m.annotation relation type.
            content: The content of the created event. Will be modified to configure
                the m.relates_to key based on the other provided parameters.
            access_token: The access token used to send the relation, defaults
                to `self.user_token`
            parent_id: The event_id this relation relates to. If None, then self.parent_id

        Returns:
            FakeChannel
        """
        if not access_token:
            access_token = self.user_token

        original_id = parent_id if parent_id else self.parent_id

        if content is None:
            content = {}
        content["m.relates_to"] = {
            "event_id": original_id,
            "rel_type": relation_type,
        }
        if key is not None:
            content["m.relates_to"]["key"] = key

        channel = self.make_request(
            "POST",
            f"/_matrix/client/v3/rooms/{self.room}/send/{event_type}",
            content,
            access_token=access_token,
        )
        self.assertEqual(expected_response_code, channel.code, channel.json_body)
        return channel

    def _get_related_events(self) -> List[str]:
        """
        Requests /relations on the parent ID and returns a list of event IDs.
        """
        # Request the relations of the event.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        return [ev["event_id"] for ev in channel.json_body["chunk"]]

    def _get_bundled_aggregations(self) -> JsonDict:
        """
        Requests /event on the parent ID and returns the m.relations field (from unsigned), if it exists.
        """
        # Fetch the bundled aggregations of the event.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v3/rooms/{self.room}/event/{self.parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        return channel.json_body["unsigned"].get("m.relations", {})

    def _find_event_in_chunk(self, events: List[JsonDict]) -> JsonDict:
        """
        Find the parent event in a chunk of events and assert that it has the proper bundled aggregations.
        """
        for event in events:
            if event["event_id"] == self.parent_id:
                return event

        raise AssertionError(f"Event {self.parent_id} not found in chunk")


class RelationsTestCase(BaseRelationsTestCase):
    def test_send_relation(self) -> None:
        """Tests that sending a relation works."""
        channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
        event_id = channel.json_body["event_id"]

        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{event_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)

        self.assert_dict(
            {
                "type": "m.reaction",
                "sender": self.user_id,
                "content": {
                    "m.relates_to": {
                        "event_id": self.parent_id,
                        "key": "👍",
                        "rel_type": RelationTypes.ANNOTATION,
                    }
                },
            },
            channel.json_body,
        )

    def test_deny_invalid_event(self) -> None:
        """Test that we deny relations on non-existant events"""
        self._send_relation(
            RelationTypes.ANNOTATION,
            EventTypes.Message,
            parent_id="foo",
            content={"body": "foo", "msgtype": "m.text"},
            expected_response_code=400,
        )

        # Unless that event is referenced from another event!
        self.get_success(
            self.hs.get_datastores().main.db_pool.simple_insert(
                table="event_relations",
                values={
                    "event_id": "bar",
                    "relates_to_id": "foo",
                    "relation_type": RelationTypes.THREAD,
                },
                desc="test_deny_invalid_event",
            )
        )
        self._send_relation(
            RelationTypes.THREAD,
            EventTypes.Message,
            parent_id="foo",
            content={"body": "foo", "msgtype": "m.text"},
        )

    def test_deny_invalid_room(self) -> None:
        """Test that we deny relations on non-existant events"""
        # Create another room and send a message in it.
        room2 = self.helper.create_room_as(self.user_id, tok=self.user_token)
        res = self.helper.send(room2, body="Hi!", tok=self.user_token)
        parent_id = res["event_id"]

        # Attempt to send an annotation to that event.
        self._send_relation(
            RelationTypes.ANNOTATION,
            "m.reaction",
            parent_id=parent_id,
            key="A",
            expected_response_code=400,
        )

    def test_deny_double_react(self) -> None:
        """Test that we deny relations on membership events"""
        self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
        self._send_relation(
            RelationTypes.ANNOTATION, "m.reaction", "a", expected_response_code=400
        )

    def test_deny_forked_thread(self) -> None:
        """It is invalid to start a thread off a thread."""
        channel = self._send_relation(
            RelationTypes.THREAD,
            "m.room.message",
            content={"msgtype": "m.text", "body": "foo"},
            parent_id=self.parent_id,
        )
        parent_id = channel.json_body["event_id"]

        self._send_relation(
            RelationTypes.THREAD,
            "m.room.message",
            content={"msgtype": "m.text", "body": "foo"},
            parent_id=parent_id,
            expected_response_code=400,
        )

    def test_ignore_invalid_room(self) -> None:
        """Test that we ignore invalid relations over federation."""
        # Create another room and send a message in it.
        room2 = self.helper.create_room_as(self.user_id, tok=self.user_token)
        res = self.helper.send(room2, body="Hi!", tok=self.user_token)
        parent_id = res["event_id"]

        # Disable the validation to pretend this came over federation.
        with patch(
            "synapse.handlers.message.EventCreationHandler._validate_event_relation",
            new_callable=AsyncMock,
            return_value=None,
        ):
            # Generate a various relations from a different room.
            self.get_success(
                inject_event(
                    self.hs,
                    room_id=self.room,
                    type="m.reaction",
                    sender=self.user_id,
                    content={
                        "m.relates_to": {
                            "rel_type": RelationTypes.ANNOTATION,
                            "event_id": parent_id,
                            "key": "A",
                        }
                    },
                )
            )

            self.get_success(
                inject_event(
                    self.hs,
                    room_id=self.room,
                    type="m.room.message",
                    sender=self.user_id,
                    content={
                        "body": "foo",
                        "msgtype": "m.text",
                        "m.relates_to": {
                            "rel_type": RelationTypes.REFERENCE,
                            "event_id": parent_id,
                        },
                    },
                )
            )

            self.get_success(
                inject_event(
                    self.hs,
                    room_id=self.room,
                    type="m.room.message",
                    sender=self.user_id,
                    content={
                        "body": "foo",
                        "msgtype": "m.text",
                        "m.relates_to": {
                            "rel_type": RelationTypes.THREAD,
                            "event_id": parent_id,
                        },
                    },
                )
            )

            self.get_success(
                inject_event(
                    self.hs,
                    room_id=self.room,
                    type="m.room.message",
                    sender=self.user_id,
                    content={
                        "body": "foo",
                        "msgtype": "m.text",
                        "new_content": {
                            "body": "new content",
                            "msgtype": "m.text",
                        },
                        "m.relates_to": {
                            "rel_type": RelationTypes.REPLACE,
                            "event_id": parent_id,
                        },
                    },
                )
            )

        # They should be ignored when fetching relations.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{room2}/relations/{parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual(channel.json_body["chunk"], [])

        # And for bundled aggregations.
        channel = self.make_request(
            "GET",
            f"/rooms/{room2}/event/{parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertNotIn("m.relations", channel.json_body["unsigned"])

    def _assert_edit_bundle(
        self, event_json: JsonDict, edit_event_id: str, edit_event_content: JsonDict
    ) -> None:
        """
        Assert that the given event has a correctly-serialised edit event in its
        bundled aggregations

        Args:
            event_json: the serialised event to be checked
            edit_event_id: the ID of the edit event that we expect to be bundled
            edit_event_content: the content of that event, excluding the 'm.relates_to`
               property
        """
        relations_dict = event_json["unsigned"].get("m.relations")
        self.assertIn(RelationTypes.REPLACE, relations_dict)

        m_replace_dict = relations_dict[RelationTypes.REPLACE]
        for key in [
            "event_id",
            "sender",
            "origin_server_ts",
            "content",
            "type",
            "unsigned",
        ]:
            self.assertIn(key, m_replace_dict)

        expected_edit_content = {
            "m.relates_to": {
                "event_id": event_json["event_id"],
                "rel_type": "m.replace",
            }
        }
        expected_edit_content.update(edit_event_content)

        self.assert_dict(
            {
                "event_id": edit_event_id,
                "sender": self.user_id,
                "content": expected_edit_content,
                "type": "m.room.message",
            },
            m_replace_dict,
        )

    def test_edit(self) -> None:
        """Test that a simple edit works."""
        orig_body = {"body": "Hi!", "msgtype": "m.text"}
        new_body = {"msgtype": "m.text", "body": "I've been edited!"}
        edit_event_content = {
            "msgtype": "m.text",
            "body": "foo",
            "m.new_content": new_body,
        }
        channel = self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message",
            content=edit_event_content,
        )
        edit_event_id = channel.json_body["event_id"]

        # /event should return the *original* event
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{self.parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual(channel.json_body["content"], orig_body)
        self._assert_edit_bundle(channel.json_body, edit_event_id, edit_event_content)

        # Request the room messages.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/messages?dir=b",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self._assert_edit_bundle(
            self._find_event_in_chunk(channel.json_body["chunk"]),
            edit_event_id,
            edit_event_content,
        )

        # Request the room context.
        # /context should return the event.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/context/{self.parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self._assert_edit_bundle(
            channel.json_body["event"], edit_event_id, edit_event_content
        )
        self.assertEqual(channel.json_body["event"]["content"], orig_body)

        # Request sync, but limit the timeline so it becomes limited (and includes
        # bundled aggregations).
        filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 2}}}')
        channel = self.make_request(
            "GET", f"/sync?filter={filter}", access_token=self.user_token
        )
        self.assertEqual(200, channel.code, channel.json_body)
        room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
        self.assertTrue(room_timeline["limited"])
        self._assert_edit_bundle(
            self._find_event_in_chunk(room_timeline["events"]),
            edit_event_id,
            edit_event_content,
        )

        # Request search.
        channel = self.make_request(
            "POST",
            "/search",
            # Search term matches the parent message.
            content={"search_categories": {"room_events": {"search_term": "Hi"}}},
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        chunk = [
            result["result"]
            for result in channel.json_body["search_categories"]["room_events"][
                "results"
            ]
        ]
        self._assert_edit_bundle(
            self._find_event_in_chunk(chunk),
            edit_event_id,
            edit_event_content,
        )

    def test_multi_edit(self) -> None:
        """Test that multiple edits, including attempts by people who
        shouldn't be allowed, are correctly handled.
        """
        orig_body = orig_body = {"body": "Hi!", "msgtype": "m.text"}
        self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message",
            content={
                "msgtype": "m.text",
                "body": "Wibble",
                "m.new_content": {"msgtype": "m.text", "body": "First edit"},
            },
        )

        new_body = {"msgtype": "m.text", "body": "I've been edited!"}
        edit_event_content = {
            "msgtype": "m.text",
            "body": "foo",
            "m.new_content": new_body,
        }
        channel = self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message",
            content=edit_event_content,
        )
        edit_event_id = channel.json_body["event_id"]

        self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message.WRONG_TYPE",
            content={
                "msgtype": "m.text",
                "body": "Wibble",
                "m.new_content": {"msgtype": "m.text", "body": "Edit, but wrong type"},
            },
        )

        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/context/{self.parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)

        self.assertEqual(channel.json_body["event"]["content"], orig_body)
        self._assert_edit_bundle(
            channel.json_body["event"], edit_event_id, edit_event_content
        )

    def test_edit_reply(self) -> None:
        """Test that editing a reply works."""

        # Create a reply to edit.
        original_body = {"msgtype": "m.text", "body": "A reply!"}
        channel = self._send_relation(
            RelationTypes.REFERENCE, "m.room.message", content=original_body
        )
        reply = channel.json_body["event_id"]

        edit_event_content = {
            "msgtype": "m.text",
            "body": "foo",
            "m.new_content": {"msgtype": "m.text", "body": "I've been edited!"},
        }
        channel = self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message",
            content=edit_event_content,
            parent_id=reply,
        )
        edit_event_id = channel.json_body["event_id"]

        # /event returns the original event
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{reply}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        event_result = channel.json_body
        self.assertDictContainsSubset(original_body, event_result["content"])

        # also check /context, which returns the *edited* event
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/context/{reply}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        context_result = channel.json_body["event"]

        # check that the relations are correct for both APIs
        for result_event_dict, desc in (
            (event_result, "/event"),
            (context_result, "/context"),
        ):
            # The reference metadata should still be intact.
            self.assertDictContainsSubset(
                {
                    "m.relates_to": {
                        "event_id": self.parent_id,
                        "rel_type": "m.reference",
                    }
                },
                result_event_dict["content"],
                desc,
            )

            # We expect that the edit relation appears in the unsigned relations
            # section.
            self._assert_edit_bundle(
                result_event_dict, edit_event_id, edit_event_content
            )

    def test_edit_edit(self) -> None:
        """Test that an edit cannot be edited."""
        orig_body = {"body": "Hi!", "msgtype": "m.text"}
        new_body = {"msgtype": "m.text", "body": "Initial edit"}
        edit_event_content = {
            "msgtype": "m.text",
            "body": "Wibble",
            "m.new_content": new_body,
        }
        channel = self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message",
            content=edit_event_content,
        )
        edit_event_id = channel.json_body["event_id"]

        # Edit the edit event.
        self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message",
            content={
                "msgtype": "m.text",
                "body": "foo",
                "m.new_content": {"msgtype": "m.text", "body": "Ignored edit"},
            },
            parent_id=edit_event_id,
        )

        # Request the original event.
        # /event should return the original event.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{self.parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual(channel.json_body["content"], orig_body)

        # The relations information should not include the edit to the edit.
        self._assert_edit_bundle(channel.json_body, edit_event_id, edit_event_content)

        # /context should return the bundled edit for the *first* edit
        # (The edit to the edit should be ignored.)
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/context/{self.parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual(channel.json_body["event"]["content"], orig_body)
        self._assert_edit_bundle(
            channel.json_body["event"], edit_event_id, edit_event_content
        )

        # Directly requesting the edit should not have the edit to the edit applied.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{edit_event_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual("Wibble", channel.json_body["content"]["body"])
        self.assertIn("m.new_content", channel.json_body["content"])

        # The relations information should not include the edit to the edit.
        self.assertNotIn("m.relations", channel.json_body["unsigned"])

    def test_unknown_relations(self) -> None:
        """Unknown relations should be accepted."""
        channel = self._send_relation("m.relation.test", "m.room.test")
        event_id = channel.json_body["event_id"]

        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)

        # We expect to get back a single pagination result, which is the full
        # relation event we sent above.
        self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
        self.assert_dict(
            {"event_id": event_id, "sender": self.user_id, "type": "m.room.test"},
            channel.json_body["chunk"][0],
        )

        # We also expect to get the original event (the id of which is self.parent_id)
        # when requesting the unstable endpoint.
        self.assertNotIn("original_event", channel.json_body)
        channel = self.make_request(
            "GET",
            f"/_matrix/client/unstable/rooms/{self.room}/relations/{self.parent_id}?limit=1",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual(
            channel.json_body["original_event"]["event_id"], self.parent_id
        )

        # When bundling the unknown relation is not included.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{self.parent_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertNotIn("m.relations", channel.json_body["unsigned"])

    def test_background_update(self) -> None:
        """Test the event_arbitrary_relations background update."""
        channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
        annotation_event_id_good = channel.json_body["event_id"]

        channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="A")
        annotation_event_id_bad = channel.json_body["event_id"]

        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        thread_event_id = channel.json_body["event_id"]

        # Clean-up the table as if the inserts did not happen during event creation.
        self.get_success(
            self.store.db_pool.simple_delete_many(
                table="event_relations",
                column="event_id",
                iterable=(annotation_event_id_bad, thread_event_id),
                keyvalues={},
                desc="RelationsTestCase.test_background_update",
            )
        )

        # Only the "good" annotation should be found.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=10",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual(
            [ev["event_id"] for ev in channel.json_body["chunk"]],
            [annotation_event_id_good],
        )

        # Insert and run the background update.
        self.get_success(
            self.store.db_pool.simple_insert(
                "background_updates",
                {"update_name": "event_arbitrary_relations", "progress_json": "{}"},
            )
        )

        # Ugh, have to reset this flag
        self.store.db_pool.updates._all_done = False
        self.wait_for_background_updates()

        # The "good" annotation and the thread should be found, but not the "bad"
        # annotation.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=10",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertCountEqual(
            [ev["event_id"] for ev in channel.json_body["chunk"]],
            [annotation_event_id_good, thread_event_id],
        )


class RelationPaginationTestCase(BaseRelationsTestCase):
    def test_basic_paginate_relations(self) -> None:
        """Tests that calling pagination API correctly the latest relations."""
        channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
        first_annotation_id = channel.json_body["event_id"]

        channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
        second_annotation_id = channel.json_body["event_id"]

        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)

        # We expect to get back a single pagination result, which is the latest
        # full relation event we sent above.
        self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
        self.assert_dict(
            {
                "event_id": second_annotation_id,
                "sender": self.user_id,
                "type": "m.reaction",
            },
            channel.json_body["chunk"][0],
        )

        # Make sure next_batch has something in it that looks like it could be a
        # valid token.
        self.assertIsInstance(
            channel.json_body.get("next_batch"), str, channel.json_body
        )

        # Request the relations again, but with a different direction.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations"
            f"/{self.parent_id}?limit=1&dir=f",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)

        # We expect to get back a single pagination result, which is the earliest
        # full relation event we sent above.
        self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
        self.assert_dict(
            {
                "event_id": first_annotation_id,
                "sender": self.user_id,
                "type": "m.reaction",
            },
            channel.json_body["chunk"][0],
        )

    def test_repeated_paginate_relations(self) -> None:
        """Test that if we paginate using a limit and tokens then we get the
        expected events.
        """

        expected_event_ids = []
        for idx in range(10):
            channel = self._send_relation(
                RelationTypes.ANNOTATION, "m.reaction", chr(ord("a") + idx)
            )
            expected_event_ids.append(channel.json_body["event_id"])

        prev_token: Optional[str] = ""
        found_event_ids: List[str] = []
        for _ in range(20):
            from_token = ""
            if prev_token:
                from_token = "&from=" + prev_token

            channel = self.make_request(
                "GET",
                f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=3{from_token}",
                access_token=self.user_token,
            )
            self.assertEqual(200, channel.code, channel.json_body)

            found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
            next_batch = channel.json_body.get("next_batch")

            self.assertNotEqual(prev_token, next_batch)
            prev_token = next_batch

            if not prev_token:
                break

        # We paginated backwards, so reverse
        found_event_ids.reverse()
        self.assertEqual(found_event_ids, expected_event_ids)

        # Test forward pagination.
        prev_token = ""
        found_event_ids = []
        for _ in range(20):
            from_token = ""
            if prev_token:
                from_token = "&from=" + prev_token

            channel = self.make_request(
                "GET",
                f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?dir=f&limit=3{from_token}",
                access_token=self.user_token,
            )
            self.assertEqual(200, channel.code, channel.json_body)

            found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
            next_batch = channel.json_body.get("next_batch")

            self.assertNotEqual(prev_token, next_batch)
            prev_token = next_batch

            if not prev_token:
                break

        self.assertEqual(found_event_ids, expected_event_ids)

    def test_pagination_from_sync_and_messages(self) -> None:
        """Pagination tokens from /sync and /messages can be used to paginate /relations."""
        channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "A")
        annotation_id = channel.json_body["event_id"]
        # Send an event after the relation events.
        self.helper.send(self.room, body="Latest event", tok=self.user_token)

        # Request /sync, limiting it such that only the latest event is returned
        # (and not the relation).
        filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 1}}}')
        channel = self.make_request(
            "GET", f"/sync?filter={filter}", access_token=self.user_token
        )
        self.assertEqual(200, channel.code, channel.json_body)
        room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
        sync_prev_batch = room_timeline["prev_batch"]
        self.assertIsNotNone(sync_prev_batch)
        # Ensure the relation event is not in the batch returned from /sync.
        self.assertNotIn(
            annotation_id, [ev["event_id"] for ev in room_timeline["events"]]
        )

        # Request /messages, limiting it such that only the latest event is
        # returned (and not the relation).
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/messages?dir=b&limit=1",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        messages_end = channel.json_body["end"]
        self.assertIsNotNone(messages_end)
        # Ensure the relation event is not in the chunk returned from /messages.
        self.assertNotIn(
            annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
        )

        # Request /relations with the pagination tokens received from both the
        # /sync and /messages responses above, in turn.
        #
        # This is a tiny bit silly since the client wouldn't know the parent ID
        # from the requests above; consider the parent ID to be known from a
        # previous /sync.
        for from_token in (sync_prev_batch, messages_end):
            channel = self.make_request(
                "GET",
                f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?from={from_token}",
                access_token=self.user_token,
            )
            self.assertEqual(200, channel.code, channel.json_body)

            # The relation should be in the returned chunk.
            self.assertIn(
                annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
            )


class RecursiveRelationTestCase(BaseRelationsTestCase):
    @override_config({"experimental_features": {"msc3981_recurse_relations": True}})
    def test_recursive_relations(self) -> None:
        """Generate a complex, multi-level relationship tree and query it."""
        # Create a thread with a few messages in it.
        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        thread_1 = channel.json_body["event_id"]

        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        thread_2 = channel.json_body["event_id"]

        # Add annotations.
        channel = self._send_relation(
            RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=thread_2
        )
        annotation_1 = channel.json_body["event_id"]

        channel = self._send_relation(
            RelationTypes.ANNOTATION, "m.reaction", "b", parent_id=thread_1
        )
        annotation_2 = channel.json_body["event_id"]

        # Add a reference to part of the thread, then edit the reference and annotate it.
        channel = self._send_relation(
            RelationTypes.REFERENCE, "m.room.test", parent_id=thread_2
        )
        reference_1 = channel.json_body["event_id"]

        channel = self._send_relation(
            RelationTypes.ANNOTATION, "m.reaction", "c", parent_id=reference_1
        )
        annotation_3 = channel.json_body["event_id"]

        channel = self._send_relation(
            RelationTypes.REPLACE,
            "m.room.test",
            parent_id=reference_1,
        )
        edit = channel.json_body["event_id"]

        # Also more events off the root.
        channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "d")
        annotation_4 = channel.json_body["event_id"]

        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}"
            "?dir=f&limit=20&org.matrix.msc3981.recurse=true",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)

        # The above events should be returned in creation order.
        event_ids = [ev["event_id"] for ev in channel.json_body["chunk"]]
        self.assertEqual(
            event_ids,
            [
                thread_1,
                thread_2,
                annotation_1,
                annotation_2,
                reference_1,
                annotation_3,
                edit,
                annotation_4,
            ],
        )

    @override_config({"experimental_features": {"msc3981_recurse_relations": True}})
    def test_recursive_relations_with_filter(self) -> None:
        """The event_type and rel_type still apply."""
        # Create a thread with a few messages in it.
        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        thread_1 = channel.json_body["event_id"]

        # Add annotations.
        channel = self._send_relation(
            RelationTypes.ANNOTATION, "m.reaction", "b", parent_id=thread_1
        )
        annotation_1 = channel.json_body["event_id"]

        # Add a reference to part of the thread, then edit the reference and annotate it.
        channel = self._send_relation(
            RelationTypes.REFERENCE, "m.room.test", parent_id=thread_1
        )
        reference_1 = channel.json_body["event_id"]

        channel = self._send_relation(
            RelationTypes.ANNOTATION, "org.matrix.reaction", "c", parent_id=reference_1
        )
        annotation_2 = channel.json_body["event_id"]

        # Fetch only annotations, but recursively.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}/{RelationTypes.ANNOTATION}"
            "?dir=f&limit=20&org.matrix.msc3981.recurse=true",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)

        # The above events should be returned in creation order.
        event_ids = [ev["event_id"] for ev in channel.json_body["chunk"]]
        self.assertEqual(event_ids, [annotation_1, annotation_2])

        # Fetch only m.reactions, but recursively.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}/{RelationTypes.ANNOTATION}/m.reaction"
            "?dir=f&limit=20&org.matrix.msc3981.recurse=true",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)

        # The above events should be returned in creation order.
        event_ids = [ev["event_id"] for ev in channel.json_body["chunk"]]
        self.assertEqual(event_ids, [annotation_1])


class BundledAggregationsTestCase(BaseRelationsTestCase):
    """
    See RelationsTestCase.test_edit for a similar test for edits.

    Note that this doesn't test against /relations since only thread relations
    get bundled via that API. See test_aggregation_get_event_for_thread.
    """

    def _test_bundled_aggregations(
        self,
        relation_type: str,
        assertion_callable: Callable[[JsonDict], None],
        expected_db_txn_for_event: int,
        access_token: Optional[str] = None,
    ) -> None:
        """
        Makes requests to various endpoints which should include bundled aggregations
        and then calls an assertion function on the bundled aggregations.

        Args:
            relation_type: The field to search for in the `m.relations` field in unsigned.
            assertion_callable: Called with the contents of unsigned["m.relations"][relation_type]
                for relation-specific assertions.
            expected_db_txn_for_event: The number of database transactions which
                are expected for a call to /event/.
            access_token: The access token to user, defaults to self.user_token.
        """
        access_token = access_token or self.user_token

        def assert_bundle(event_json: JsonDict) -> None:
            """Assert the expected values of the bundled aggregations."""
            relations_dict = event_json["unsigned"].get("m.relations")

            # Ensure the fields are as expected.
            self.assertCountEqual(relations_dict.keys(), (relation_type,))
            assertion_callable(relations_dict[relation_type])

        # Request the event directly.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{self.parent_id}",
            access_token=access_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        assert_bundle(channel.json_body)
        assert channel.resource_usage is not None
        self.assertEqual(channel.resource_usage.db_txn_count, expected_db_txn_for_event)

        # Request the room messages.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/messages?dir=b",
            access_token=access_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        assert_bundle(self._find_event_in_chunk(channel.json_body["chunk"]))

        # Request the room context.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/context/{self.parent_id}",
            access_token=access_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        assert_bundle(channel.json_body["event"])

        # Request sync.
        filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 4}}}')
        channel = self.make_request(
            "GET", f"/sync?filter={filter}", access_token=access_token
        )
        self.assertEqual(200, channel.code, channel.json_body)
        room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
        self.assertTrue(room_timeline["limited"])
        assert_bundle(self._find_event_in_chunk(room_timeline["events"]))

        # Request search.
        channel = self.make_request(
            "POST",
            "/search",
            # Search term matches the parent message.
            content={"search_categories": {"room_events": {"search_term": "Hi"}}},
            access_token=access_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        chunk = [
            result["result"]
            for result in channel.json_body["search_categories"]["room_events"][
                "results"
            ]
        ]
        assert_bundle(self._find_event_in_chunk(chunk))

    def test_reference(self) -> None:
        """
        Test that references get correctly bundled.
        """
        channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
        reply_1 = channel.json_body["event_id"]

        channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
        reply_2 = channel.json_body["event_id"]

        def assert_annotations(bundled_aggregations: JsonDict) -> None:
            self.assertEqual(
                {"chunk": [{"event_id": reply_1}, {"event_id": reply_2}]},
                bundled_aggregations,
            )

        self._test_bundled_aggregations(RelationTypes.REFERENCE, assert_annotations, 6)

    def test_thread(self) -> None:
        """
        Test that threads get correctly bundled.
        """
        # The root message is from "user", send replies as "user2".
        self._send_relation(
            RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
        )
        channel = self._send_relation(
            RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
        )
        thread_2 = channel.json_body["event_id"]

        # This needs two assertion functions which are identical except for whether
        # the current_user_participated flag is True, create a factory for the
        # two versions.
        def _gen_assert(participated: bool) -> Callable[[JsonDict], None]:
            def assert_thread(bundled_aggregations: JsonDict) -> None:
                self.assertEqual(2, bundled_aggregations.get("count"))
                self.assertEqual(
                    participated, bundled_aggregations.get("current_user_participated")
                )
                # The latest thread event has some fields that don't matter.
                self.assertIn("latest_event", bundled_aggregations)
                self.assert_dict(
                    {
                        "content": {
                            "m.relates_to": {
                                "event_id": self.parent_id,
                                "rel_type": RelationTypes.THREAD,
                            }
                        },
                        "event_id": thread_2,
                        "sender": self.user2_id,
                        "type": "m.room.test",
                    },
                    bundled_aggregations["latest_event"],
                )

            return assert_thread

        # The "user" sent the root event and is making queries for the bundled
        # aggregations: they have participated.
        self._test_bundled_aggregations(RelationTypes.THREAD, _gen_assert(True), 6)
        # The "user2" sent replies in the thread and is making queries for the
        # bundled aggregations: they have participated.
        #
        # Note that this re-uses some cached values, so the total number of
        # queries is much smaller.
        self._test_bundled_aggregations(
            RelationTypes.THREAD, _gen_assert(True), 3, access_token=self.user2_token
        )

        # A user with no interactions with the thread: they have not participated.
        user3_id, user3_token = self._create_user("charlie")
        self.helper.join(self.room, user=user3_id, tok=user3_token)
        self._test_bundled_aggregations(
            RelationTypes.THREAD, _gen_assert(False), 3, access_token=user3_token
        )

    def test_thread_with_bundled_aggregations_for_latest(self) -> None:
        """
        Bundled aggregations should get applied to the latest thread event.
        """
        self._send_relation(RelationTypes.THREAD, "m.room.test")
        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        thread_2 = channel.json_body["event_id"]

        channel = self._send_relation(
            RelationTypes.REFERENCE, "org.matrix.test", parent_id=thread_2
        )
        reference_event_id = channel.json_body["event_id"]

        def assert_thread(bundled_aggregations: JsonDict) -> None:
            self.assertEqual(2, bundled_aggregations.get("count"))
            self.assertTrue(bundled_aggregations.get("current_user_participated"))
            # The latest thread event has some fields that don't matter.
            self.assertIn("latest_event", bundled_aggregations)
            self.assert_dict(
                {
                    "content": {
                        "m.relates_to": {
                            "event_id": self.parent_id,
                            "rel_type": RelationTypes.THREAD,
                        }
                    },
                    "event_id": thread_2,
                    "sender": self.user_id,
                    "type": "m.room.test",
                },
                bundled_aggregations["latest_event"],
            )
            # Check the unsigned field on the latest event.
            self.assert_dict(
                {
                    "m.relations": {
                        RelationTypes.REFERENCE: {
                            "chunk": [{"event_id": reference_event_id}]
                        },
                    }
                },
                bundled_aggregations["latest_event"].get("unsigned"),
            )

        self._test_bundled_aggregations(RelationTypes.THREAD, assert_thread, 6)

    def test_nested_thread(self) -> None:
        """
        Ensure that a nested thread gets ignored by bundled aggregations, as
        those are forbidden.
        """

        # Start a thread.
        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        reply_event_id = channel.json_body["event_id"]

        # Disable the validation to pretend this came over federation, since it is
        # not an event the Client-Server API will allow..
        with patch(
            "synapse.handlers.message.EventCreationHandler._validate_event_relation",
            new_callable=AsyncMock,
            return_value=None,
        ):
            # Create a sub-thread off the thread, which is not allowed.
            self._send_relation(
                RelationTypes.THREAD, "m.room.test", parent_id=reply_event_id
            )

        # Fetch the thread root, to get the bundled aggregation for the thread.
        relations_from_event = self._get_bundled_aggregations()

        # Ensure that requesting the room messages also does not return the sub-thread.
        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/messages?dir=b",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        event = self._find_event_in_chunk(channel.json_body["chunk"])
        relations_from_messages = event["unsigned"]["m.relations"]

        # Check the bundled aggregations from each point.
        for aggregations, desc in (
            (relations_from_event, "/event"),
            (relations_from_messages, "/messages"),
        ):
            # The latest event should have bundled aggregations.
            self.assertIn(RelationTypes.THREAD, aggregations, desc)
            thread_summary = aggregations[RelationTypes.THREAD]
            self.assertIn("latest_event", thread_summary, desc)
            self.assertEqual(
                thread_summary["latest_event"]["event_id"], reply_event_id, desc
            )

            # The latest event should not have any bundled aggregations (since the
            # only relation to it is another thread, which is invalid).
            self.assertNotIn(
                "m.relations", thread_summary["latest_event"]["unsigned"], desc
            )

    def test_thread_edit_latest_event(self) -> None:
        """Test that editing the latest event in a thread works."""

        # Create a thread and edit the last event.
        channel = self._send_relation(
            RelationTypes.THREAD,
            "m.room.message",
            content={"msgtype": "m.text", "body": "A threaded reply!"},
        )
        threaded_event_id = channel.json_body["event_id"]

        new_body = {"msgtype": "m.text", "body": "I've been edited!"}
        channel = self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message",
            content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
            parent_id=threaded_event_id,
        )
        edit_event_id = channel.json_body["event_id"]

        # Fetch the thread root, to get the bundled aggregation for the thread.
        relations_dict = self._get_bundled_aggregations()

        # We expect that the edit message appears in the thread summary in the
        # unsigned relations section.
        self.assertIn(RelationTypes.THREAD, relations_dict)

        thread_summary = relations_dict[RelationTypes.THREAD]
        self.assertIn("latest_event", thread_summary)
        latest_event_in_thread = thread_summary["latest_event"]
        # The latest event in the thread should have the edit appear under the
        # bundled aggregations.
        self.assertDictContainsSubset(
            {"event_id": edit_event_id, "sender": "@alice:test"},
            latest_event_in_thread["unsigned"]["m.relations"][RelationTypes.REPLACE],
        )

    def test_aggregation_get_event_for_annotation(self) -> None:
        """Test that annotations do not get bundled aggregations included
        when directly requested.
        """
        channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
        annotation_id = channel.json_body["event_id"]

        # Annotate the annotation.
        self._send_relation(
            RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=annotation_id
        )

        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{annotation_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertIsNone(channel.json_body["unsigned"].get("m.relations"))

    def test_aggregation_get_event_for_thread(self) -> None:
        """Test that threads get bundled aggregations included when directly requested."""
        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        thread_id = channel.json_body["event_id"]

        # Make a reference to the thread.
        channel = self._send_relation(
            RelationTypes.REFERENCE, "org.matrix.test", parent_id=thread_id
        )
        reference_event_id = channel.json_body["event_id"]

        channel = self.make_request(
            "GET",
            f"/rooms/{self.room}/event/{thread_id}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual(
            channel.json_body["unsigned"].get("m.relations"),
            {
                RelationTypes.REFERENCE: {"chunk": [{"event_id": reference_event_id}]},
            },
        )

        # It should also be included when the entire thread is requested.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        self.assertEqual(len(channel.json_body["chunk"]), 1)

        thread_message = channel.json_body["chunk"][0]
        self.assertEqual(
            thread_message["unsigned"].get("m.relations"),
            {
                RelationTypes.REFERENCE: {"chunk": [{"event_id": reference_event_id}]},
            },
        )

    def test_bundled_aggregations_with_filter(self) -> None:
        """
        If "unsigned" is an omitted field (due to filtering), adding the bundled
        aggregations should not break.

        Note that the spec allows for a server to return additional fields beyond
        what is specified.
        """
        channel = self._send_relation(RelationTypes.REFERENCE, "org.matrix.test")
        reference_event_id = channel.json_body["event_id"]

        # Note that the sync filter does not include "unsigned" as a field.
        filter = urllib.parse.quote_plus(
            b'{"event_fields": ["content", "event_id"], "room": {"timeline": {"limit": 3}}}'
        )
        channel = self.make_request(
            "GET", f"/sync?filter={filter}", access_token=self.user_token
        )
        self.assertEqual(200, channel.code, channel.json_body)

        # Ensure the timeline is limited, find the parent event.
        room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
        self.assertTrue(room_timeline["limited"])
        parent_event = self._find_event_in_chunk(room_timeline["events"])

        # Ensure there's bundled aggregations on it.
        self.assertIn("unsigned", parent_event)
        self.assertEqual(
            parent_event["unsigned"].get("m.relations"),
            {
                RelationTypes.REFERENCE: {"chunk": [{"event_id": reference_event_id}]},
            },
        )


class RelationIgnoredUserTestCase(BaseRelationsTestCase):
    """Relations sent from an ignored user should be ignored."""

    def _test_ignored_user(
        self,
        relation_type: str,
        allowed_event_ids: List[str],
        ignored_event_ids: List[str],
    ) -> Tuple[JsonDict, JsonDict]:
        """
        Fetch the relations and ensure they're all there, then ignore user2, and
        repeat.

        Returns:
            A tuple of two JSON dictionaries, each are bundled aggregations, the
            first is from before the user is ignored, and the second is after.
        """
        # Get the relations.
        event_ids = self._get_related_events()
        self.assertCountEqual(event_ids, allowed_event_ids + ignored_event_ids)

        # And the bundled aggregations.
        before_aggregations = self._get_bundled_aggregations()
        self.assertIn(relation_type, before_aggregations)

        # Ignore user2 and re-do the requests.
        self.get_success(
            self.store.add_account_data_for_user(
                self.user_id,
                AccountDataTypes.IGNORED_USER_LIST,
                {"ignored_users": {self.user2_id: {}}},
            )
        )

        # Get the relations.
        event_ids = self._get_related_events()
        self.assertCountEqual(event_ids, allowed_event_ids)

        # And the bundled aggregations.
        after_aggregations = self._get_bundled_aggregations()
        self.assertIn(relation_type, after_aggregations)

        return before_aggregations[relation_type], after_aggregations[relation_type]

    def test_reference(self) -> None:
        """Aggregations should exclude reference relations from ignored users"""
        channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
        allowed_event_ids = [channel.json_body["event_id"]]

        channel = self._send_relation(
            RelationTypes.REFERENCE, "m.room.test", access_token=self.user2_token
        )
        ignored_event_ids = [channel.json_body["event_id"]]

        before_aggregations, after_aggregations = self._test_ignored_user(
            RelationTypes.REFERENCE, allowed_event_ids, ignored_event_ids
        )

        self.assertCountEqual(
            [e["event_id"] for e in before_aggregations["chunk"]],
            allowed_event_ids + ignored_event_ids,
        )

        self.assertCountEqual(
            [e["event_id"] for e in after_aggregations["chunk"]], allowed_event_ids
        )

    def test_thread(self) -> None:
        """Aggregations should exclude thread releations from ignored users"""
        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        allowed_event_ids = [channel.json_body["event_id"]]

        channel = self._send_relation(
            RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
        )
        ignored_event_ids = [channel.json_body["event_id"]]

        before_aggregations, after_aggregations = self._test_ignored_user(
            RelationTypes.THREAD, allowed_event_ids, ignored_event_ids
        )

        self.assertEqual(before_aggregations["count"], 2)
        self.assertTrue(before_aggregations["current_user_participated"])
        # The latest thread event has some fields that don't matter.
        self.assertEqual(
            before_aggregations["latest_event"]["event_id"], ignored_event_ids[0]
        )

        self.assertEqual(after_aggregations["count"], 1)
        self.assertTrue(after_aggregations["current_user_participated"])
        # The latest thread event has some fields that don't matter.
        self.assertEqual(
            after_aggregations["latest_event"]["event_id"], allowed_event_ids[0]
        )


class RelationRedactionTestCase(BaseRelationsTestCase):
    """
    Test the behaviour of relations when the parent or child event is redacted.

    The behaviour of each relation type is subtly different which causes the tests
    to be a bit repetitive, they follow a naming scheme of:

        test_redact_(relation|parent)_{relation_type}

    The first bit of "relation" means that the event with the relation defined
    on it (the child event) is to be redacted. A "parent" means that the target
    of the relation (the parent event) is to be redacted.

    The relation_type describes which type of relation is under test (i.e. it is
    related to the value of rel_type in the event content).
    """

    def _redact(self, event_id: str) -> None:
        channel = self.make_request(
            "POST",
            f"/_matrix/client/r0/rooms/{self.room}/redact/{event_id}",
            access_token=self.user_token,
            content={},
        )
        self.assertEqual(200, channel.code, channel.json_body)

    def _get_threads(self) -> List[Tuple[str, str]]:
        """Request the threads in the room and returns a list of thread ID and latest event ID."""
        # Request the threads in the room.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/threads",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        threads = channel.json_body["chunk"]
        return [
            (
                t["event_id"],
                t["unsigned"]["m.relations"][RelationTypes.THREAD]["latest_event"][
                    "event_id"
                ],
            )
            for t in threads
        ]

    def test_redact_relation_thread(self) -> None:
        """
        Test that thread replies are properly handled after the thread reply redacted.

        The redacted event should not be included in bundled aggregations or
        the response to relations.
        """
        # Create a thread with a few events in it.
        thread_replies = []
        for i in range(3):
            channel = self._send_relation(
                RelationTypes.THREAD,
                EventTypes.Message,
                content={"body": f"reply {i}", "msgtype": "m.text"},
            )
            thread_replies.append(channel.json_body["event_id"])

        ##################################################
        # Check the test data is configured as expected. #
        ##################################################
        self.assertEqual(self._get_related_events(), list(reversed(thread_replies)))
        relations = self._get_bundled_aggregations()
        self.assertDictContainsSubset(
            {"count": 3, "current_user_participated": True},
            relations[RelationTypes.THREAD],
        )
        # The latest event is the last sent event.
        self.assertEqual(
            relations[RelationTypes.THREAD]["latest_event"]["event_id"],
            thread_replies[-1],
        )

        # There should be one thread, the latest event is the event that will be redacted.
        self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])

        ##########################
        # Redact the last event. #
        ##########################
        self._redact(thread_replies.pop())

        # The thread should still exist, but the latest event should be updated.
        self.assertEqual(self._get_related_events(), list(reversed(thread_replies)))
        relations = self._get_bundled_aggregations()
        self.assertDictContainsSubset(
            {"count": 2, "current_user_participated": True},
            relations[RelationTypes.THREAD],
        )
        # And the latest event is the last unredacted event.
        self.assertEqual(
            relations[RelationTypes.THREAD]["latest_event"]["event_id"],
            thread_replies[-1],
        )
        self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])

        ###########################################
        # Redact the *first* event in the thread. #
        ###########################################
        self._redact(thread_replies.pop(0))

        # Nothing should have changed (except the thread count).
        self.assertEqual(self._get_related_events(), thread_replies)
        relations = self._get_bundled_aggregations()
        self.assertDictContainsSubset(
            {"count": 1, "current_user_participated": True},
            relations[RelationTypes.THREAD],
        )
        # And the latest event is the last unredacted event.
        self.assertEqual(
            relations[RelationTypes.THREAD]["latest_event"]["event_id"],
            thread_replies[-1],
        )
        self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])

        ####################################
        # Redact the last remaining event. #
        ####################################
        self._redact(thread_replies.pop(0))
        self.assertEqual(thread_replies, [])

        # The event should no longer be considered a thread.
        self.assertEqual(self._get_related_events(), [])
        self.assertEqual(self._get_bundled_aggregations(), {})
        self.assertEqual(self._get_threads(), [])

    def test_redact_parent_edit(self) -> None:
        """Test that edits of an event are redacted when the original event
        is redacted.
        """
        # Add a relation
        self._send_relation(
            RelationTypes.REPLACE,
            "m.room.message",
            parent_id=self.parent_id,
            content={
                "msgtype": "m.text",
                "body": "Wibble",
                "m.new_content": {"msgtype": "m.text", "body": "First edit"},
            },
        )

        # Check the relation is returned
        event_ids = self._get_related_events()
        relations = self._get_bundled_aggregations()
        self.assertEqual(len(event_ids), 1)
        self.assertIn(RelationTypes.REPLACE, relations)

        # Redact the original event
        self._redact(self.parent_id)

        # The relations are not returned.
        event_ids = self._get_related_events()
        relations = self._get_bundled_aggregations()
        self.assertEqual(len(event_ids), 0)
        self.assertEqual(relations, {})

    def test_redact_parent_annotation(self) -> None:
        """Test that annotations of an event are viewable when the original event
        is redacted.
        """
        # Add a relation
        channel = self._send_relation(RelationTypes.REFERENCE, "org.matrix.test")
        related_event_id = channel.json_body["event_id"]

        # The relations should exist.
        event_ids = self._get_related_events()
        relations = self._get_bundled_aggregations()
        self.assertEqual(len(event_ids), 1)
        self.assertIn(RelationTypes.REFERENCE, relations)

        # Redact the original event.
        self._redact(self.parent_id)

        # The relations are returned.
        event_ids = self._get_related_events()
        relations = self._get_bundled_aggregations()
        self.assertEqual(event_ids, [related_event_id])
        self.assertEqual(
            relations[RelationTypes.REFERENCE],
            {"chunk": [{"event_id": related_event_id}]},
        )

    def test_redact_parent_thread(self) -> None:
        """
        Test that thread replies are still available when the root event is redacted.
        """
        channel = self._send_relation(
            RelationTypes.THREAD,
            EventTypes.Message,
            content={"body": "reply 1", "msgtype": "m.text"},
        )
        related_event_id = channel.json_body["event_id"]

        # Redact one of the reactions.
        self._redact(self.parent_id)

        # The unredacted relation should still exist.
        event_ids = self._get_related_events()
        relations = self._get_bundled_aggregations()
        self.assertEqual(len(event_ids), 1)
        self.assertDictContainsSubset(
            {
                "count": 1,
                "current_user_participated": True,
            },
            relations[RelationTypes.THREAD],
        )
        self.assertEqual(
            relations[RelationTypes.THREAD]["latest_event"]["event_id"],
            related_event_id,
        )


class ThreadsTestCase(BaseRelationsTestCase):
    def _get_threads(self, body: JsonDict) -> List[Tuple[str, str]]:
        return [
            (
                ev["event_id"],
                ev["unsigned"]["m.relations"]["m.thread"]["latest_event"]["event_id"],
            )
            for ev in body["chunk"]
        ]

    def test_threads(self) -> None:
        """Create threads and ensure the ordering is due to their latest event."""
        # Create 2 threads.
        thread_1 = self.parent_id
        res = self.helper.send(self.room, body="Thread Root!", tok=self.user_token)
        thread_2 = res["event_id"]

        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        reply_1 = channel.json_body["event_id"]
        channel = self._send_relation(
            RelationTypes.THREAD, "m.room.test", parent_id=thread_2
        )
        reply_2 = channel.json_body["event_id"]

        # Request the threads in the room.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/threads",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        threads = self._get_threads(channel.json_body)
        self.assertEqual(threads, [(thread_2, reply_2), (thread_1, reply_1)])

        # Update the first thread, the ordering should swap.
        channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
        reply_3 = channel.json_body["event_id"]

        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/threads",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        # Tuple of (thread ID, latest event ID) for each thread.
        threads = self._get_threads(channel.json_body)
        self.assertEqual(threads, [(thread_1, reply_3), (thread_2, reply_2)])

    def test_pagination(self) -> None:
        """Create threads and paginate through them."""
        # Create 2 threads.
        thread_1 = self.parent_id
        res = self.helper.send(self.room, body="Thread Root!", tok=self.user_token)
        thread_2 = res["event_id"]

        self._send_relation(RelationTypes.THREAD, "m.room.test")
        self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)

        # Request the threads in the room.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/threads?limit=1",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
        self.assertEqual(thread_roots, [thread_2])

        # Make sure next_batch has something in it that looks like it could be a
        # valid token.
        next_batch = channel.json_body.get("next_batch")
        self.assertIsInstance(next_batch, str, channel.json_body)

        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/threads?limit=1&from={next_batch}",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
        self.assertEqual(thread_roots, [thread_1], channel.json_body)

        self.assertNotIn("next_batch", channel.json_body, channel.json_body)

    def test_include(self) -> None:
        """Filtering threads to all or participated in should work."""
        # Thread 1 has the user as the root event.
        thread_1 = self.parent_id
        self._send_relation(
            RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
        )

        # Thread 2 has the user replying.
        res = self.helper.send(self.room, body="Thread Root!", tok=self.user2_token)
        thread_2 = res["event_id"]
        self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)

        # Thread 3 has the user not participating in.
        res = self.helper.send(self.room, body="Another thread!", tok=self.user2_token)
        thread_3 = res["event_id"]
        self._send_relation(
            RelationTypes.THREAD,
            "m.room.test",
            access_token=self.user2_token,
            parent_id=thread_3,
        )

        # All threads in the room.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/threads",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
        self.assertEqual(
            thread_roots, [thread_3, thread_2, thread_1], channel.json_body
        )

        # Only participated threads.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/threads?include=participated",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
        self.assertEqual(thread_roots, [thread_2, thread_1], channel.json_body)

    def test_ignored_user(self) -> None:
        """Events from ignored users should be ignored."""
        # Thread 1 has a reply from an ignored user.
        thread_1 = self.parent_id
        self._send_relation(
            RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
        )

        # Thread 2 is created by an ignored user.
        res = self.helper.send(self.room, body="Thread Root!", tok=self.user2_token)
        thread_2 = res["event_id"]
        self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)

        # Ignore user2.
        self.get_success(
            self.store.add_account_data_for_user(
                self.user_id,
                AccountDataTypes.IGNORED_USER_LIST,
                {"ignored_users": {self.user2_id: {}}},
            )
        )

        # Only thread 1 is returned.
        channel = self.make_request(
            "GET",
            f"/_matrix/client/v1/rooms/{self.room}/threads",
            access_token=self.user_token,
        )
        self.assertEqual(200, channel.code, channel.json_body)
        thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
        self.assertEqual(thread_roots, [thread_1], channel.json_body)