test_relations.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  1. # Copyright 2019 New Vector Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import urllib.parse
  16. from typing import Any, Callable, Dict, List, Optional, Tuple
  17. from unittest.mock import patch
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.api.constants import AccountDataTypes, EventTypes, RelationTypes
  20. from synapse.rest import admin
  21. from synapse.rest.client import login, register, relations, room, sync
  22. from synapse.server import HomeServer
  23. from synapse.types import JsonDict
  24. from synapse.util import Clock
  25. from tests import unittest
  26. from tests.server import FakeChannel
  27. from tests.test_utils import make_awaitable
  28. from tests.test_utils.event_injection import inject_event
  29. class BaseRelationsTestCase(unittest.HomeserverTestCase):
  30. servlets = [
  31. relations.register_servlets,
  32. room.register_servlets,
  33. sync.register_servlets,
  34. login.register_servlets,
  35. register.register_servlets,
  36. admin.register_servlets_for_client_rest_resource,
  37. ]
  38. hijack_auth = False
  39. def default_config(self) -> Dict[str, Any]:
  40. # We need to enable msc1849 support for aggregations
  41. config = super().default_config()
  42. # We enable frozen dicts as relations/edits change event contents, so we
  43. # want to test that we don't modify the events in the caches.
  44. config["use_frozen_dicts"] = True
  45. return config
  46. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  47. self.store = hs.get_datastores().main
  48. self.user_id, self.user_token = self._create_user("alice")
  49. self.user2_id, self.user2_token = self._create_user("bob")
  50. self.room = self.helper.create_room_as(self.user_id, tok=self.user_token)
  51. self.helper.join(self.room, user=self.user2_id, tok=self.user2_token)
  52. res = self.helper.send(self.room, body="Hi!", tok=self.user_token)
  53. self.parent_id = res["event_id"]
  54. def _create_user(self, localpart: str) -> Tuple[str, str]:
  55. user_id = self.register_user(localpart, "abc123")
  56. access_token = self.login(localpart, "abc123")
  57. return user_id, access_token
  58. def _send_relation(
  59. self,
  60. relation_type: str,
  61. event_type: str,
  62. key: Optional[str] = None,
  63. content: Optional[dict] = None,
  64. access_token: Optional[str] = None,
  65. parent_id: Optional[str] = None,
  66. expected_response_code: int = 200,
  67. ) -> FakeChannel:
  68. """Helper function to send a relation pointing at `self.parent_id`
  69. Args:
  70. relation_type: One of `RelationTypes`
  71. event_type: The type of the event to create
  72. key: The aggregation key used for m.annotation relation type.
  73. content: The content of the created event. Will be modified to configure
  74. the m.relates_to key based on the other provided parameters.
  75. access_token: The access token used to send the relation, defaults
  76. to `self.user_token`
  77. parent_id: The event_id this relation relates to. If None, then self.parent_id
  78. Returns:
  79. FakeChannel
  80. """
  81. if not access_token:
  82. access_token = self.user_token
  83. original_id = parent_id if parent_id else self.parent_id
  84. if content is None:
  85. content = {}
  86. content["m.relates_to"] = {
  87. "event_id": original_id,
  88. "rel_type": relation_type,
  89. }
  90. if key is not None:
  91. content["m.relates_to"]["key"] = key
  92. channel = self.make_request(
  93. "POST",
  94. f"/_matrix/client/v3/rooms/{self.room}/send/{event_type}",
  95. content,
  96. access_token=access_token,
  97. )
  98. self.assertEqual(expected_response_code, channel.code, channel.json_body)
  99. return channel
  100. def _get_related_events(self) -> List[str]:
  101. """
  102. Requests /relations on the parent ID and returns a list of event IDs.
  103. """
  104. # Request the relations of the event.
  105. channel = self.make_request(
  106. "GET",
  107. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}",
  108. access_token=self.user_token,
  109. )
  110. self.assertEquals(200, channel.code, channel.json_body)
  111. return [ev["event_id"] for ev in channel.json_body["chunk"]]
  112. def _get_bundled_aggregations(self) -> JsonDict:
  113. """
  114. Requests /event on the parent ID and returns the m.relations field (from unsigned), if it exists.
  115. """
  116. # Fetch the bundled aggregations of the event.
  117. channel = self.make_request(
  118. "GET",
  119. f"/_matrix/client/v3/rooms/{self.room}/event/{self.parent_id}",
  120. access_token=self.user_token,
  121. )
  122. self.assertEquals(200, channel.code, channel.json_body)
  123. return channel.json_body["unsigned"].get("m.relations", {})
  124. def _find_event_in_chunk(self, events: List[JsonDict]) -> JsonDict:
  125. """
  126. Find the parent event in a chunk of events and assert that it has the proper bundled aggregations.
  127. """
  128. for event in events:
  129. if event["event_id"] == self.parent_id:
  130. return event
  131. raise AssertionError(f"Event {self.parent_id} not found in chunk")
  132. class RelationsTestCase(BaseRelationsTestCase):
  133. def test_send_relation(self) -> None:
  134. """Tests that sending a relation works."""
  135. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  136. event_id = channel.json_body["event_id"]
  137. channel = self.make_request(
  138. "GET",
  139. f"/rooms/{self.room}/event/{event_id}",
  140. access_token=self.user_token,
  141. )
  142. self.assertEqual(200, channel.code, channel.json_body)
  143. self.assert_dict(
  144. {
  145. "type": "m.reaction",
  146. "sender": self.user_id,
  147. "content": {
  148. "m.relates_to": {
  149. "event_id": self.parent_id,
  150. "key": "👍",
  151. "rel_type": RelationTypes.ANNOTATION,
  152. }
  153. },
  154. },
  155. channel.json_body,
  156. )
  157. def test_deny_invalid_event(self) -> None:
  158. """Test that we deny relations on non-existant events"""
  159. self._send_relation(
  160. RelationTypes.ANNOTATION,
  161. EventTypes.Message,
  162. parent_id="foo",
  163. content={"body": "foo", "msgtype": "m.text"},
  164. expected_response_code=400,
  165. )
  166. # Unless that event is referenced from another event!
  167. self.get_success(
  168. self.hs.get_datastores().main.db_pool.simple_insert(
  169. table="event_relations",
  170. values={
  171. "event_id": "bar",
  172. "relates_to_id": "foo",
  173. "relation_type": RelationTypes.THREAD,
  174. },
  175. desc="test_deny_invalid_event",
  176. )
  177. )
  178. self._send_relation(
  179. RelationTypes.THREAD,
  180. EventTypes.Message,
  181. parent_id="foo",
  182. content={"body": "foo", "msgtype": "m.text"},
  183. )
  184. def test_deny_invalid_room(self) -> None:
  185. """Test that we deny relations on non-existant events"""
  186. # Create another room and send a message in it.
  187. room2 = self.helper.create_room_as(self.user_id, tok=self.user_token)
  188. res = self.helper.send(room2, body="Hi!", tok=self.user_token)
  189. parent_id = res["event_id"]
  190. # Attempt to send an annotation to that event.
  191. self._send_relation(
  192. RelationTypes.ANNOTATION,
  193. "m.reaction",
  194. parent_id=parent_id,
  195. key="A",
  196. expected_response_code=400,
  197. )
  198. def test_deny_double_react(self) -> None:
  199. """Test that we deny relations on membership events"""
  200. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
  201. self._send_relation(
  202. RelationTypes.ANNOTATION, "m.reaction", "a", expected_response_code=400
  203. )
  204. def test_deny_forked_thread(self) -> None:
  205. """It is invalid to start a thread off a thread."""
  206. channel = self._send_relation(
  207. RelationTypes.THREAD,
  208. "m.room.message",
  209. content={"msgtype": "m.text", "body": "foo"},
  210. parent_id=self.parent_id,
  211. )
  212. parent_id = channel.json_body["event_id"]
  213. self._send_relation(
  214. RelationTypes.THREAD,
  215. "m.room.message",
  216. content={"msgtype": "m.text", "body": "foo"},
  217. parent_id=parent_id,
  218. expected_response_code=400,
  219. )
  220. def test_ignore_invalid_room(self) -> None:
  221. """Test that we ignore invalid relations over federation."""
  222. # Create another room and send a message in it.
  223. room2 = self.helper.create_room_as(self.user_id, tok=self.user_token)
  224. res = self.helper.send(room2, body="Hi!", tok=self.user_token)
  225. parent_id = res["event_id"]
  226. # Disable the validation to pretend this came over federation.
  227. with patch(
  228. "synapse.handlers.message.EventCreationHandler._validate_event_relation",
  229. new=lambda self, event: make_awaitable(None),
  230. ):
  231. # Generate a various relations from a different room.
  232. self.get_success(
  233. inject_event(
  234. self.hs,
  235. room_id=self.room,
  236. type="m.reaction",
  237. sender=self.user_id,
  238. content={
  239. "m.relates_to": {
  240. "rel_type": RelationTypes.ANNOTATION,
  241. "event_id": parent_id,
  242. "key": "A",
  243. }
  244. },
  245. )
  246. )
  247. self.get_success(
  248. inject_event(
  249. self.hs,
  250. room_id=self.room,
  251. type="m.room.message",
  252. sender=self.user_id,
  253. content={
  254. "body": "foo",
  255. "msgtype": "m.text",
  256. "m.relates_to": {
  257. "rel_type": RelationTypes.REFERENCE,
  258. "event_id": parent_id,
  259. },
  260. },
  261. )
  262. )
  263. self.get_success(
  264. inject_event(
  265. self.hs,
  266. room_id=self.room,
  267. type="m.room.message",
  268. sender=self.user_id,
  269. content={
  270. "body": "foo",
  271. "msgtype": "m.text",
  272. "m.relates_to": {
  273. "rel_type": RelationTypes.THREAD,
  274. "event_id": parent_id,
  275. },
  276. },
  277. )
  278. )
  279. self.get_success(
  280. inject_event(
  281. self.hs,
  282. room_id=self.room,
  283. type="m.room.message",
  284. sender=self.user_id,
  285. content={
  286. "body": "foo",
  287. "msgtype": "m.text",
  288. "new_content": {
  289. "body": "new content",
  290. "msgtype": "m.text",
  291. },
  292. "m.relates_to": {
  293. "rel_type": RelationTypes.REPLACE,
  294. "event_id": parent_id,
  295. },
  296. },
  297. )
  298. )
  299. # They should be ignored when fetching relations.
  300. channel = self.make_request(
  301. "GET",
  302. f"/_matrix/client/v1/rooms/{room2}/relations/{parent_id}",
  303. access_token=self.user_token,
  304. )
  305. self.assertEqual(200, channel.code, channel.json_body)
  306. self.assertEqual(channel.json_body["chunk"], [])
  307. # And for bundled aggregations.
  308. channel = self.make_request(
  309. "GET",
  310. f"/rooms/{room2}/event/{parent_id}",
  311. access_token=self.user_token,
  312. )
  313. self.assertEqual(200, channel.code, channel.json_body)
  314. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  315. def test_edit(self) -> None:
  316. """Test that a simple edit works."""
  317. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  318. channel = self._send_relation(
  319. RelationTypes.REPLACE,
  320. "m.room.message",
  321. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  322. )
  323. edit_event_id = channel.json_body["event_id"]
  324. def assert_bundle(event_json: JsonDict) -> None:
  325. """Assert the expected values of the bundled aggregations."""
  326. relations_dict = event_json["unsigned"].get("m.relations")
  327. self.assertIn(RelationTypes.REPLACE, relations_dict)
  328. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  329. for key in ["event_id", "sender", "origin_server_ts"]:
  330. self.assertIn(key, m_replace_dict)
  331. self.assert_dict(
  332. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  333. )
  334. # /event should return the *original* event
  335. channel = self.make_request(
  336. "GET",
  337. f"/rooms/{self.room}/event/{self.parent_id}",
  338. access_token=self.user_token,
  339. )
  340. self.assertEqual(200, channel.code, channel.json_body)
  341. self.assertEqual(
  342. channel.json_body["content"], {"body": "Hi!", "msgtype": "m.text"}
  343. )
  344. assert_bundle(channel.json_body)
  345. # Request the room messages.
  346. channel = self.make_request(
  347. "GET",
  348. f"/rooms/{self.room}/messages?dir=b",
  349. access_token=self.user_token,
  350. )
  351. self.assertEqual(200, channel.code, channel.json_body)
  352. assert_bundle(self._find_event_in_chunk(channel.json_body["chunk"]))
  353. # Request the room context.
  354. # /context should return the edited event.
  355. channel = self.make_request(
  356. "GET",
  357. f"/rooms/{self.room}/context/{self.parent_id}",
  358. access_token=self.user_token,
  359. )
  360. self.assertEqual(200, channel.code, channel.json_body)
  361. assert_bundle(channel.json_body["event"])
  362. self.assertEqual(channel.json_body["event"]["content"], new_body)
  363. # Request sync, but limit the timeline so it becomes limited (and includes
  364. # bundled aggregations).
  365. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 2}}}')
  366. channel = self.make_request(
  367. "GET", f"/sync?filter={filter}", access_token=self.user_token
  368. )
  369. self.assertEqual(200, channel.code, channel.json_body)
  370. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  371. self.assertTrue(room_timeline["limited"])
  372. assert_bundle(self._find_event_in_chunk(room_timeline["events"]))
  373. # Request search.
  374. channel = self.make_request(
  375. "POST",
  376. "/search",
  377. # Search term matches the parent message.
  378. content={"search_categories": {"room_events": {"search_term": "Hi"}}},
  379. access_token=self.user_token,
  380. )
  381. self.assertEqual(200, channel.code, channel.json_body)
  382. chunk = [
  383. result["result"]
  384. for result in channel.json_body["search_categories"]["room_events"][
  385. "results"
  386. ]
  387. ]
  388. assert_bundle(self._find_event_in_chunk(chunk))
  389. def test_multi_edit(self) -> None:
  390. """Test that multiple edits, including attempts by people who
  391. shouldn't be allowed, are correctly handled.
  392. """
  393. self._send_relation(
  394. RelationTypes.REPLACE,
  395. "m.room.message",
  396. content={
  397. "msgtype": "m.text",
  398. "body": "Wibble",
  399. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  400. },
  401. )
  402. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  403. channel = self._send_relation(
  404. RelationTypes.REPLACE,
  405. "m.room.message",
  406. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  407. )
  408. edit_event_id = channel.json_body["event_id"]
  409. self._send_relation(
  410. RelationTypes.REPLACE,
  411. "m.room.message.WRONG_TYPE",
  412. content={
  413. "msgtype": "m.text",
  414. "body": "Wibble",
  415. "m.new_content": {"msgtype": "m.text", "body": "Edit, but wrong type"},
  416. },
  417. )
  418. channel = self.make_request(
  419. "GET",
  420. f"/rooms/{self.room}/context/{self.parent_id}",
  421. access_token=self.user_token,
  422. )
  423. self.assertEqual(200, channel.code, channel.json_body)
  424. self.assertEqual(channel.json_body["event"]["content"], new_body)
  425. relations_dict = channel.json_body["event"]["unsigned"].get("m.relations")
  426. self.assertIn(RelationTypes.REPLACE, relations_dict)
  427. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  428. for key in ["event_id", "sender", "origin_server_ts"]:
  429. self.assertIn(key, m_replace_dict)
  430. self.assert_dict(
  431. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  432. )
  433. def test_edit_reply(self) -> None:
  434. """Test that editing a reply works."""
  435. # Create a reply to edit.
  436. original_body = {"msgtype": "m.text", "body": "A reply!"}
  437. channel = self._send_relation(
  438. RelationTypes.REFERENCE, "m.room.message", content=original_body
  439. )
  440. reply = channel.json_body["event_id"]
  441. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  442. channel = self._send_relation(
  443. RelationTypes.REPLACE,
  444. "m.room.message",
  445. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  446. parent_id=reply,
  447. )
  448. edit_event_id = channel.json_body["event_id"]
  449. # /event returns the original event
  450. channel = self.make_request(
  451. "GET",
  452. f"/rooms/{self.room}/event/{reply}",
  453. access_token=self.user_token,
  454. )
  455. self.assertEqual(200, channel.code, channel.json_body)
  456. event_result = channel.json_body
  457. self.assertDictContainsSubset(original_body, event_result["content"])
  458. # also check /context, which returns the *edited* event
  459. channel = self.make_request(
  460. "GET",
  461. f"/rooms/{self.room}/context/{reply}",
  462. access_token=self.user_token,
  463. )
  464. self.assertEqual(200, channel.code, channel.json_body)
  465. context_result = channel.json_body["event"]
  466. # check that the relations are correct for both APIs
  467. for result_event_dict, desc in (
  468. (event_result, "/event"),
  469. (context_result, "/context"),
  470. ):
  471. # The reference metadata should still be intact.
  472. self.assertDictContainsSubset(
  473. {
  474. "m.relates_to": {
  475. "event_id": self.parent_id,
  476. "rel_type": "m.reference",
  477. }
  478. },
  479. result_event_dict["content"],
  480. desc,
  481. )
  482. # We expect that the edit relation appears in the unsigned relations
  483. # section.
  484. relations_dict = result_event_dict["unsigned"].get("m.relations")
  485. self.assertIn(RelationTypes.REPLACE, relations_dict, desc)
  486. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  487. for key in ["event_id", "sender", "origin_server_ts"]:
  488. self.assertIn(key, m_replace_dict, desc)
  489. self.assert_dict(
  490. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  491. )
  492. def test_edit_edit(self) -> None:
  493. """Test that an edit cannot be edited."""
  494. new_body = {"msgtype": "m.text", "body": "Initial edit"}
  495. channel = self._send_relation(
  496. RelationTypes.REPLACE,
  497. "m.room.message",
  498. content={
  499. "msgtype": "m.text",
  500. "body": "Wibble",
  501. "m.new_content": new_body,
  502. },
  503. )
  504. edit_event_id = channel.json_body["event_id"]
  505. # Edit the edit event.
  506. self._send_relation(
  507. RelationTypes.REPLACE,
  508. "m.room.message",
  509. content={
  510. "msgtype": "m.text",
  511. "body": "foo",
  512. "m.new_content": {"msgtype": "m.text", "body": "Ignored edit"},
  513. },
  514. parent_id=edit_event_id,
  515. )
  516. # Request the original event.
  517. # /event should return the original event.
  518. channel = self.make_request(
  519. "GET",
  520. f"/rooms/{self.room}/event/{self.parent_id}",
  521. access_token=self.user_token,
  522. )
  523. self.assertEqual(200, channel.code, channel.json_body)
  524. self.assertEqual(
  525. channel.json_body["content"], {"body": "Hi!", "msgtype": "m.text"}
  526. )
  527. # The relations information should not include the edit to the edit.
  528. relations_dict = channel.json_body["unsigned"].get("m.relations")
  529. self.assertIn(RelationTypes.REPLACE, relations_dict)
  530. # /context should return the event updated for the *first* edit
  531. # (The edit to the edit should be ignored.)
  532. channel = self.make_request(
  533. "GET",
  534. f"/rooms/{self.room}/context/{self.parent_id}",
  535. access_token=self.user_token,
  536. )
  537. self.assertEqual(200, channel.code, channel.json_body)
  538. self.assertEqual(channel.json_body["event"]["content"], new_body)
  539. m_replace_dict = relations_dict[RelationTypes.REPLACE]
  540. for key in ["event_id", "sender", "origin_server_ts"]:
  541. self.assertIn(key, m_replace_dict)
  542. self.assert_dict(
  543. {"event_id": edit_event_id, "sender": self.user_id}, m_replace_dict
  544. )
  545. # Directly requesting the edit should not have the edit to the edit applied.
  546. channel = self.make_request(
  547. "GET",
  548. f"/rooms/{self.room}/event/{edit_event_id}",
  549. access_token=self.user_token,
  550. )
  551. self.assertEqual(200, channel.code, channel.json_body)
  552. self.assertEqual("Wibble", channel.json_body["content"]["body"])
  553. self.assertIn("m.new_content", channel.json_body["content"])
  554. # The relations information should not include the edit to the edit.
  555. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  556. def test_unknown_relations(self) -> None:
  557. """Unknown relations should be accepted."""
  558. channel = self._send_relation("m.relation.test", "m.room.test")
  559. event_id = channel.json_body["event_id"]
  560. channel = self.make_request(
  561. "GET",
  562. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  563. access_token=self.user_token,
  564. )
  565. self.assertEqual(200, channel.code, channel.json_body)
  566. # We expect to get back a single pagination result, which is the full
  567. # relation event we sent above.
  568. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  569. self.assert_dict(
  570. {"event_id": event_id, "sender": self.user_id, "type": "m.room.test"},
  571. channel.json_body["chunk"][0],
  572. )
  573. # We also expect to get the original event (the id of which is self.parent_id)
  574. # when requesting the unstable endpoint.
  575. self.assertNotIn("original_event", channel.json_body)
  576. channel = self.make_request(
  577. "GET",
  578. f"/_matrix/client/unstable/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  579. access_token=self.user_token,
  580. )
  581. self.assertEqual(200, channel.code, channel.json_body)
  582. self.assertEqual(
  583. channel.json_body["original_event"]["event_id"], self.parent_id
  584. )
  585. # When bundling the unknown relation is not included.
  586. channel = self.make_request(
  587. "GET",
  588. f"/rooms/{self.room}/event/{self.parent_id}",
  589. access_token=self.user_token,
  590. )
  591. self.assertEqual(200, channel.code, channel.json_body)
  592. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  593. def test_background_update(self) -> None:
  594. """Test the event_arbitrary_relations background update."""
  595. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  596. annotation_event_id_good = channel.json_body["event_id"]
  597. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="A")
  598. annotation_event_id_bad = channel.json_body["event_id"]
  599. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  600. thread_event_id = channel.json_body["event_id"]
  601. # Clean-up the table as if the inserts did not happen during event creation.
  602. self.get_success(
  603. self.store.db_pool.simple_delete_many(
  604. table="event_relations",
  605. column="event_id",
  606. iterable=(annotation_event_id_bad, thread_event_id),
  607. keyvalues={},
  608. desc="RelationsTestCase.test_background_update",
  609. )
  610. )
  611. # Only the "good" annotation should be found.
  612. channel = self.make_request(
  613. "GET",
  614. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=10",
  615. access_token=self.user_token,
  616. )
  617. self.assertEqual(200, channel.code, channel.json_body)
  618. self.assertEqual(
  619. [ev["event_id"] for ev in channel.json_body["chunk"]],
  620. [annotation_event_id_good],
  621. )
  622. # Insert and run the background update.
  623. self.get_success(
  624. self.store.db_pool.simple_insert(
  625. "background_updates",
  626. {"update_name": "event_arbitrary_relations", "progress_json": "{}"},
  627. )
  628. )
  629. # Ugh, have to reset this flag
  630. self.store.db_pool.updates._all_done = False
  631. self.wait_for_background_updates()
  632. # The "good" annotation and the thread should be found, but not the "bad"
  633. # annotation.
  634. channel = self.make_request(
  635. "GET",
  636. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=10",
  637. access_token=self.user_token,
  638. )
  639. self.assertEqual(200, channel.code, channel.json_body)
  640. self.assertCountEqual(
  641. [ev["event_id"] for ev in channel.json_body["chunk"]],
  642. [annotation_event_id_good, thread_event_id],
  643. )
  644. class RelationPaginationTestCase(BaseRelationsTestCase):
  645. def test_basic_paginate_relations(self) -> None:
  646. """Tests that calling pagination API correctly the latest relations."""
  647. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  648. first_annotation_id = channel.json_body["event_id"]
  649. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  650. second_annotation_id = channel.json_body["event_id"]
  651. channel = self.make_request(
  652. "GET",
  653. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  654. access_token=self.user_token,
  655. )
  656. self.assertEqual(200, channel.code, channel.json_body)
  657. # We expect to get back a single pagination result, which is the latest
  658. # full relation event we sent above.
  659. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  660. self.assert_dict(
  661. {
  662. "event_id": second_annotation_id,
  663. "sender": self.user_id,
  664. "type": "m.reaction",
  665. },
  666. channel.json_body["chunk"][0],
  667. )
  668. # Make sure next_batch has something in it that looks like it could be a
  669. # valid token.
  670. self.assertIsInstance(
  671. channel.json_body.get("next_batch"), str, channel.json_body
  672. )
  673. # Request the relations again, but with a different direction.
  674. channel = self.make_request(
  675. "GET",
  676. f"/_matrix/client/v1/rooms/{self.room}/relations"
  677. f"/{self.parent_id}?limit=1&dir=f",
  678. access_token=self.user_token,
  679. )
  680. self.assertEqual(200, channel.code, channel.json_body)
  681. # We expect to get back a single pagination result, which is the earliest
  682. # full relation event we sent above.
  683. self.assertEqual(len(channel.json_body["chunk"]), 1, channel.json_body)
  684. self.assert_dict(
  685. {
  686. "event_id": first_annotation_id,
  687. "sender": self.user_id,
  688. "type": "m.reaction",
  689. },
  690. channel.json_body["chunk"][0],
  691. )
  692. def test_repeated_paginate_relations(self) -> None:
  693. """Test that if we paginate using a limit and tokens then we get the
  694. expected events.
  695. """
  696. expected_event_ids = []
  697. for idx in range(10):
  698. channel = self._send_relation(
  699. RelationTypes.ANNOTATION, "m.reaction", chr(ord("a") + idx)
  700. )
  701. expected_event_ids.append(channel.json_body["event_id"])
  702. prev_token: Optional[str] = ""
  703. found_event_ids: List[str] = []
  704. for _ in range(20):
  705. from_token = ""
  706. if prev_token:
  707. from_token = "&from=" + prev_token
  708. channel = self.make_request(
  709. "GET",
  710. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=3{from_token}",
  711. access_token=self.user_token,
  712. )
  713. self.assertEqual(200, channel.code, channel.json_body)
  714. found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
  715. next_batch = channel.json_body.get("next_batch")
  716. self.assertNotEqual(prev_token, next_batch)
  717. prev_token = next_batch
  718. if not prev_token:
  719. break
  720. # We paginated backwards, so reverse
  721. found_event_ids.reverse()
  722. self.assertEqual(found_event_ids, expected_event_ids)
  723. # Test forward pagination.
  724. prev_token = ""
  725. found_event_ids = []
  726. for _ in range(20):
  727. from_token = ""
  728. if prev_token:
  729. from_token = "&from=" + prev_token
  730. channel = self.make_request(
  731. "GET",
  732. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?dir=f&limit=3{from_token}",
  733. access_token=self.user_token,
  734. )
  735. self.assertEqual(200, channel.code, channel.json_body)
  736. found_event_ids.extend(e["event_id"] for e in channel.json_body["chunk"])
  737. next_batch = channel.json_body.get("next_batch")
  738. self.assertNotEqual(prev_token, next_batch)
  739. prev_token = next_batch
  740. if not prev_token:
  741. break
  742. self.assertEqual(found_event_ids, expected_event_ids)
  743. def test_pagination_from_sync_and_messages(self) -> None:
  744. """Pagination tokens from /sync and /messages can be used to paginate /relations."""
  745. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "A")
  746. annotation_id = channel.json_body["event_id"]
  747. # Send an event after the relation events.
  748. self.helper.send(self.room, body="Latest event", tok=self.user_token)
  749. # Request /sync, limiting it such that only the latest event is returned
  750. # (and not the relation).
  751. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 1}}}')
  752. channel = self.make_request(
  753. "GET", f"/sync?filter={filter}", access_token=self.user_token
  754. )
  755. self.assertEqual(200, channel.code, channel.json_body)
  756. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  757. sync_prev_batch = room_timeline["prev_batch"]
  758. self.assertIsNotNone(sync_prev_batch)
  759. # Ensure the relation event is not in the batch returned from /sync.
  760. self.assertNotIn(
  761. annotation_id, [ev["event_id"] for ev in room_timeline["events"]]
  762. )
  763. # Request /messages, limiting it such that only the latest event is
  764. # returned (and not the relation).
  765. channel = self.make_request(
  766. "GET",
  767. f"/rooms/{self.room}/messages?dir=b&limit=1",
  768. access_token=self.user_token,
  769. )
  770. self.assertEqual(200, channel.code, channel.json_body)
  771. messages_end = channel.json_body["end"]
  772. self.assertIsNotNone(messages_end)
  773. # Ensure the relation event is not in the chunk returned from /messages.
  774. self.assertNotIn(
  775. annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
  776. )
  777. # Request /relations with the pagination tokens received from both the
  778. # /sync and /messages responses above, in turn.
  779. #
  780. # This is a tiny bit silly since the client wouldn't know the parent ID
  781. # from the requests above; consider the parent ID to be known from a
  782. # previous /sync.
  783. for from_token in (sync_prev_batch, messages_end):
  784. channel = self.make_request(
  785. "GET",
  786. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?from={from_token}",
  787. access_token=self.user_token,
  788. )
  789. self.assertEqual(200, channel.code, channel.json_body)
  790. # The relation should be in the returned chunk.
  791. self.assertIn(
  792. annotation_id, [ev["event_id"] for ev in channel.json_body["chunk"]]
  793. )
  794. class BundledAggregationsTestCase(BaseRelationsTestCase):
  795. """
  796. See RelationsTestCase.test_edit for a similar test for edits.
  797. Note that this doesn't test against /relations since only thread relations
  798. get bundled via that API. See test_aggregation_get_event_for_thread.
  799. """
  800. def _test_bundled_aggregations(
  801. self,
  802. relation_type: str,
  803. assertion_callable: Callable[[JsonDict], None],
  804. expected_db_txn_for_event: int,
  805. access_token: Optional[str] = None,
  806. ) -> None:
  807. """
  808. Makes requests to various endpoints which should include bundled aggregations
  809. and then calls an assertion function on the bundled aggregations.
  810. Args:
  811. relation_type: The field to search for in the `m.relations` field in unsigned.
  812. assertion_callable: Called with the contents of unsigned["m.relations"][relation_type]
  813. for relation-specific assertions.
  814. expected_db_txn_for_event: The number of database transactions which
  815. are expected for a call to /event/.
  816. access_token: The access token to user, defaults to self.user_token.
  817. """
  818. access_token = access_token or self.user_token
  819. def assert_bundle(event_json: JsonDict) -> None:
  820. """Assert the expected values of the bundled aggregations."""
  821. relations_dict = event_json["unsigned"].get("m.relations")
  822. # Ensure the fields are as expected.
  823. self.assertCountEqual(relations_dict.keys(), (relation_type,))
  824. assertion_callable(relations_dict[relation_type])
  825. # Request the event directly.
  826. channel = self.make_request(
  827. "GET",
  828. f"/rooms/{self.room}/event/{self.parent_id}",
  829. access_token=access_token,
  830. )
  831. self.assertEqual(200, channel.code, channel.json_body)
  832. assert_bundle(channel.json_body)
  833. assert channel.resource_usage is not None
  834. self.assertEqual(channel.resource_usage.db_txn_count, expected_db_txn_for_event)
  835. # Request the room messages.
  836. channel = self.make_request(
  837. "GET",
  838. f"/rooms/{self.room}/messages?dir=b",
  839. access_token=access_token,
  840. )
  841. self.assertEqual(200, channel.code, channel.json_body)
  842. assert_bundle(self._find_event_in_chunk(channel.json_body["chunk"]))
  843. # Request the room context.
  844. channel = self.make_request(
  845. "GET",
  846. f"/rooms/{self.room}/context/{self.parent_id}",
  847. access_token=access_token,
  848. )
  849. self.assertEqual(200, channel.code, channel.json_body)
  850. assert_bundle(channel.json_body["event"])
  851. # Request sync.
  852. filter = urllib.parse.quote_plus(b'{"room": {"timeline": {"limit": 4}}}')
  853. channel = self.make_request(
  854. "GET", f"/sync?filter={filter}", access_token=access_token
  855. )
  856. self.assertEqual(200, channel.code, channel.json_body)
  857. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  858. self.assertTrue(room_timeline["limited"])
  859. assert_bundle(self._find_event_in_chunk(room_timeline["events"]))
  860. # Request search.
  861. channel = self.make_request(
  862. "POST",
  863. "/search",
  864. # Search term matches the parent message.
  865. content={"search_categories": {"room_events": {"search_term": "Hi"}}},
  866. access_token=access_token,
  867. )
  868. self.assertEqual(200, channel.code, channel.json_body)
  869. chunk = [
  870. result["result"]
  871. for result in channel.json_body["search_categories"]["room_events"][
  872. "results"
  873. ]
  874. ]
  875. assert_bundle(self._find_event_in_chunk(chunk))
  876. def test_annotation(self) -> None:
  877. """
  878. Test that annotations get correctly bundled.
  879. """
  880. # Setup by sending a variety of relations.
  881. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  882. self._send_relation(
  883. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  884. )
  885. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "b")
  886. def assert_annotations(bundled_aggregations: JsonDict) -> None:
  887. self.assertEqual(
  888. {
  889. "chunk": [
  890. {"type": "m.reaction", "key": "a", "count": 2},
  891. {"type": "m.reaction", "key": "b", "count": 1},
  892. ]
  893. },
  894. bundled_aggregations,
  895. )
  896. self._test_bundled_aggregations(RelationTypes.ANNOTATION, assert_annotations, 7)
  897. def test_annotation_to_annotation(self) -> None:
  898. """Any relation to an annotation should be ignored."""
  899. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  900. event_id = channel.json_body["event_id"]
  901. self._send_relation(
  902. RelationTypes.ANNOTATION, "m.reaction", "b", parent_id=event_id
  903. )
  904. # Fetch the initial annotation event to see if it has bundled aggregations.
  905. channel = self.make_request(
  906. "GET",
  907. f"/_matrix/client/v3/rooms/{self.room}/event/{event_id}",
  908. access_token=self.user_token,
  909. )
  910. self.assertEquals(200, channel.code, channel.json_body)
  911. # The first annotationt should not have any bundled aggregations.
  912. self.assertNotIn("m.relations", channel.json_body["unsigned"])
  913. def test_reference(self) -> None:
  914. """
  915. Test that references get correctly bundled.
  916. """
  917. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  918. reply_1 = channel.json_body["event_id"]
  919. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  920. reply_2 = channel.json_body["event_id"]
  921. def assert_annotations(bundled_aggregations: JsonDict) -> None:
  922. self.assertEqual(
  923. {"chunk": [{"event_id": reply_1}, {"event_id": reply_2}]},
  924. bundled_aggregations,
  925. )
  926. self._test_bundled_aggregations(RelationTypes.REFERENCE, assert_annotations, 7)
  927. def test_thread(self) -> None:
  928. """
  929. Test that threads get correctly bundled.
  930. """
  931. # The root message is from "user", send replies as "user2".
  932. self._send_relation(
  933. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  934. )
  935. channel = self._send_relation(
  936. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  937. )
  938. thread_2 = channel.json_body["event_id"]
  939. # This needs two assertion functions which are identical except for whether
  940. # the current_user_participated flag is True, create a factory for the
  941. # two versions.
  942. def _gen_assert(participated: bool) -> Callable[[JsonDict], None]:
  943. def assert_thread(bundled_aggregations: JsonDict) -> None:
  944. self.assertEqual(2, bundled_aggregations.get("count"))
  945. self.assertEqual(
  946. participated, bundled_aggregations.get("current_user_participated")
  947. )
  948. # The latest thread event has some fields that don't matter.
  949. self.assertIn("latest_event", bundled_aggregations)
  950. self.assert_dict(
  951. {
  952. "content": {
  953. "m.relates_to": {
  954. "event_id": self.parent_id,
  955. "rel_type": RelationTypes.THREAD,
  956. }
  957. },
  958. "event_id": thread_2,
  959. "sender": self.user2_id,
  960. "type": "m.room.test",
  961. },
  962. bundled_aggregations["latest_event"],
  963. )
  964. return assert_thread
  965. # The "user" sent the root event and is making queries for the bundled
  966. # aggregations: they have participated.
  967. self._test_bundled_aggregations(RelationTypes.THREAD, _gen_assert(True), 9)
  968. # The "user2" sent replies in the thread and is making queries for the
  969. # bundled aggregations: they have participated.
  970. #
  971. # Note that this re-uses some cached values, so the total number of
  972. # queries is much smaller.
  973. self._test_bundled_aggregations(
  974. RelationTypes.THREAD, _gen_assert(True), 3, access_token=self.user2_token
  975. )
  976. # A user with no interactions with the thread: they have not participated.
  977. user3_id, user3_token = self._create_user("charlie")
  978. self.helper.join(self.room, user=user3_id, tok=user3_token)
  979. self._test_bundled_aggregations(
  980. RelationTypes.THREAD, _gen_assert(False), 3, access_token=user3_token
  981. )
  982. def test_thread_with_bundled_aggregations_for_latest(self) -> None:
  983. """
  984. Bundled aggregations should get applied to the latest thread event.
  985. """
  986. self._send_relation(RelationTypes.THREAD, "m.room.test")
  987. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  988. thread_2 = channel.json_body["event_id"]
  989. self._send_relation(
  990. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=thread_2
  991. )
  992. def assert_thread(bundled_aggregations: JsonDict) -> None:
  993. self.assertEqual(2, bundled_aggregations.get("count"))
  994. self.assertTrue(bundled_aggregations.get("current_user_participated"))
  995. # The latest thread event has some fields that don't matter.
  996. self.assertIn("latest_event", bundled_aggregations)
  997. self.assert_dict(
  998. {
  999. "content": {
  1000. "m.relates_to": {
  1001. "event_id": self.parent_id,
  1002. "rel_type": RelationTypes.THREAD,
  1003. }
  1004. },
  1005. "event_id": thread_2,
  1006. "sender": self.user_id,
  1007. "type": "m.room.test",
  1008. },
  1009. bundled_aggregations["latest_event"],
  1010. )
  1011. # Check the unsigned field on the latest event.
  1012. self.assert_dict(
  1013. {
  1014. "m.relations": {
  1015. RelationTypes.ANNOTATION: {
  1016. "chunk": [
  1017. {"type": "m.reaction", "key": "a", "count": 1},
  1018. ]
  1019. },
  1020. }
  1021. },
  1022. bundled_aggregations["latest_event"].get("unsigned"),
  1023. )
  1024. self._test_bundled_aggregations(RelationTypes.THREAD, assert_thread, 9)
  1025. def test_nested_thread(self) -> None:
  1026. """
  1027. Ensure that a nested thread gets ignored by bundled aggregations, as
  1028. those are forbidden.
  1029. """
  1030. # Start a thread.
  1031. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1032. reply_event_id = channel.json_body["event_id"]
  1033. # Disable the validation to pretend this came over federation, since it is
  1034. # not an event the Client-Server API will allow..
  1035. with patch(
  1036. "synapse.handlers.message.EventCreationHandler._validate_event_relation",
  1037. new=lambda self, event: make_awaitable(None),
  1038. ):
  1039. # Create a sub-thread off the thread, which is not allowed.
  1040. self._send_relation(
  1041. RelationTypes.THREAD, "m.room.test", parent_id=reply_event_id
  1042. )
  1043. # Fetch the thread root, to get the bundled aggregation for the thread.
  1044. relations_from_event = self._get_bundled_aggregations()
  1045. # Ensure that requesting the room messages also does not return the sub-thread.
  1046. channel = self.make_request(
  1047. "GET",
  1048. f"/rooms/{self.room}/messages?dir=b",
  1049. access_token=self.user_token,
  1050. )
  1051. self.assertEqual(200, channel.code, channel.json_body)
  1052. event = self._find_event_in_chunk(channel.json_body["chunk"])
  1053. relations_from_messages = event["unsigned"]["m.relations"]
  1054. # Check the bundled aggregations from each point.
  1055. for aggregations, desc in (
  1056. (relations_from_event, "/event"),
  1057. (relations_from_messages, "/messages"),
  1058. ):
  1059. # The latest event should have bundled aggregations.
  1060. self.assertIn(RelationTypes.THREAD, aggregations, desc)
  1061. thread_summary = aggregations[RelationTypes.THREAD]
  1062. self.assertIn("latest_event", thread_summary, desc)
  1063. self.assertEqual(
  1064. thread_summary["latest_event"]["event_id"], reply_event_id, desc
  1065. )
  1066. # The latest event should not have any bundled aggregations (since the
  1067. # only relation to it is another thread, which is invalid).
  1068. self.assertNotIn(
  1069. "m.relations", thread_summary["latest_event"]["unsigned"], desc
  1070. )
  1071. def test_thread_edit_latest_event(self) -> None:
  1072. """Test that editing the latest event in a thread works."""
  1073. # Create a thread and edit the last event.
  1074. channel = self._send_relation(
  1075. RelationTypes.THREAD,
  1076. "m.room.message",
  1077. content={"msgtype": "m.text", "body": "A threaded reply!"},
  1078. )
  1079. threaded_event_id = channel.json_body["event_id"]
  1080. new_body = {"msgtype": "m.text", "body": "I've been edited!"}
  1081. channel = self._send_relation(
  1082. RelationTypes.REPLACE,
  1083. "m.room.message",
  1084. content={"msgtype": "m.text", "body": "foo", "m.new_content": new_body},
  1085. parent_id=threaded_event_id,
  1086. )
  1087. edit_event_id = channel.json_body["event_id"]
  1088. # Fetch the thread root, to get the bundled aggregation for the thread.
  1089. relations_dict = self._get_bundled_aggregations()
  1090. # We expect that the edit message appears in the thread summary in the
  1091. # unsigned relations section.
  1092. self.assertIn(RelationTypes.THREAD, relations_dict)
  1093. thread_summary = relations_dict[RelationTypes.THREAD]
  1094. self.assertIn("latest_event", thread_summary)
  1095. latest_event_in_thread = thread_summary["latest_event"]
  1096. self.assertEqual(latest_event_in_thread["content"]["body"], "I've been edited!")
  1097. # The latest event in the thread should have the edit appear under the
  1098. # bundled aggregations.
  1099. self.assertDictContainsSubset(
  1100. {"event_id": edit_event_id, "sender": "@alice:test"},
  1101. latest_event_in_thread["unsigned"]["m.relations"][RelationTypes.REPLACE],
  1102. )
  1103. def test_aggregation_get_event_for_annotation(self) -> None:
  1104. """Test that annotations do not get bundled aggregations included
  1105. when directly requested.
  1106. """
  1107. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1108. annotation_id = channel.json_body["event_id"]
  1109. # Annotate the annotation.
  1110. self._send_relation(
  1111. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=annotation_id
  1112. )
  1113. channel = self.make_request(
  1114. "GET",
  1115. f"/rooms/{self.room}/event/{annotation_id}",
  1116. access_token=self.user_token,
  1117. )
  1118. self.assertEqual(200, channel.code, channel.json_body)
  1119. self.assertIsNone(channel.json_body["unsigned"].get("m.relations"))
  1120. def test_aggregation_get_event_for_thread(self) -> None:
  1121. """Test that threads get bundled aggregations included when directly requested."""
  1122. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1123. thread_id = channel.json_body["event_id"]
  1124. # Annotate the thread.
  1125. self._send_relation(
  1126. RelationTypes.ANNOTATION, "m.reaction", "a", parent_id=thread_id
  1127. )
  1128. channel = self.make_request(
  1129. "GET",
  1130. f"/rooms/{self.room}/event/{thread_id}",
  1131. access_token=self.user_token,
  1132. )
  1133. self.assertEqual(200, channel.code, channel.json_body)
  1134. self.assertEqual(
  1135. channel.json_body["unsigned"].get("m.relations"),
  1136. {
  1137. RelationTypes.ANNOTATION: {
  1138. "chunk": [{"count": 1, "key": "a", "type": "m.reaction"}]
  1139. },
  1140. },
  1141. )
  1142. # It should also be included when the entire thread is requested.
  1143. channel = self.make_request(
  1144. "GET",
  1145. f"/_matrix/client/v1/rooms/{self.room}/relations/{self.parent_id}?limit=1",
  1146. access_token=self.user_token,
  1147. )
  1148. self.assertEqual(200, channel.code, channel.json_body)
  1149. self.assertEqual(len(channel.json_body["chunk"]), 1)
  1150. thread_message = channel.json_body["chunk"][0]
  1151. self.assertEqual(
  1152. thread_message["unsigned"].get("m.relations"),
  1153. {
  1154. RelationTypes.ANNOTATION: {
  1155. "chunk": [{"count": 1, "key": "a", "type": "m.reaction"}]
  1156. },
  1157. },
  1158. )
  1159. def test_bundled_aggregations_with_filter(self) -> None:
  1160. """
  1161. If "unsigned" is an omitted field (due to filtering), adding the bundled
  1162. aggregations should not break.
  1163. Note that the spec allows for a server to return additional fields beyond
  1164. what is specified.
  1165. """
  1166. self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1167. # Note that the sync filter does not include "unsigned" as a field.
  1168. filter = urllib.parse.quote_plus(
  1169. b'{"event_fields": ["content", "event_id"], "room": {"timeline": {"limit": 3}}}'
  1170. )
  1171. channel = self.make_request(
  1172. "GET", f"/sync?filter={filter}", access_token=self.user_token
  1173. )
  1174. self.assertEqual(200, channel.code, channel.json_body)
  1175. # Ensure the timeline is limited, find the parent event.
  1176. room_timeline = channel.json_body["rooms"]["join"][self.room]["timeline"]
  1177. self.assertTrue(room_timeline["limited"])
  1178. parent_event = self._find_event_in_chunk(room_timeline["events"])
  1179. # Ensure there's bundled aggregations on it.
  1180. self.assertIn("unsigned", parent_event)
  1181. self.assertIn("m.relations", parent_event["unsigned"])
  1182. class RelationIgnoredUserTestCase(BaseRelationsTestCase):
  1183. """Relations sent from an ignored user should be ignored."""
  1184. def _test_ignored_user(
  1185. self,
  1186. relation_type: str,
  1187. allowed_event_ids: List[str],
  1188. ignored_event_ids: List[str],
  1189. ) -> Tuple[JsonDict, JsonDict]:
  1190. """
  1191. Fetch the relations and ensure they're all there, then ignore user2, and
  1192. repeat.
  1193. Returns:
  1194. A tuple of two JSON dictionaries, each are bundled aggregations, the
  1195. first is from before the user is ignored, and the second is after.
  1196. """
  1197. # Get the relations.
  1198. event_ids = self._get_related_events()
  1199. self.assertCountEqual(event_ids, allowed_event_ids + ignored_event_ids)
  1200. # And the bundled aggregations.
  1201. before_aggregations = self._get_bundled_aggregations()
  1202. self.assertIn(relation_type, before_aggregations)
  1203. # Ignore user2 and re-do the requests.
  1204. self.get_success(
  1205. self.store.add_account_data_for_user(
  1206. self.user_id,
  1207. AccountDataTypes.IGNORED_USER_LIST,
  1208. {"ignored_users": {self.user2_id: {}}},
  1209. )
  1210. )
  1211. # Get the relations.
  1212. event_ids = self._get_related_events()
  1213. self.assertCountEqual(event_ids, allowed_event_ids)
  1214. # And the bundled aggregations.
  1215. after_aggregations = self._get_bundled_aggregations()
  1216. self.assertIn(relation_type, after_aggregations)
  1217. return before_aggregations[relation_type], after_aggregations[relation_type]
  1218. def test_annotation(self) -> None:
  1219. """Annotations should ignore"""
  1220. # Send 2 from us, 2 from the to be ignored user.
  1221. allowed_event_ids = []
  1222. ignored_event_ids = []
  1223. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="a")
  1224. allowed_event_ids.append(channel.json_body["event_id"])
  1225. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="b")
  1226. allowed_event_ids.append(channel.json_body["event_id"])
  1227. channel = self._send_relation(
  1228. RelationTypes.ANNOTATION,
  1229. "m.reaction",
  1230. key="a",
  1231. access_token=self.user2_token,
  1232. )
  1233. ignored_event_ids.append(channel.json_body["event_id"])
  1234. channel = self._send_relation(
  1235. RelationTypes.ANNOTATION,
  1236. "m.reaction",
  1237. key="c",
  1238. access_token=self.user2_token,
  1239. )
  1240. ignored_event_ids.append(channel.json_body["event_id"])
  1241. before_aggregations, after_aggregations = self._test_ignored_user(
  1242. RelationTypes.ANNOTATION, allowed_event_ids, ignored_event_ids
  1243. )
  1244. self.assertCountEqual(
  1245. before_aggregations["chunk"],
  1246. [
  1247. {"type": "m.reaction", "key": "a", "count": 2},
  1248. {"type": "m.reaction", "key": "b", "count": 1},
  1249. {"type": "m.reaction", "key": "c", "count": 1},
  1250. ],
  1251. )
  1252. self.assertCountEqual(
  1253. after_aggregations["chunk"],
  1254. [
  1255. {"type": "m.reaction", "key": "a", "count": 1},
  1256. {"type": "m.reaction", "key": "b", "count": 1},
  1257. ],
  1258. )
  1259. def test_reference(self) -> None:
  1260. """Annotations should ignore"""
  1261. channel = self._send_relation(RelationTypes.REFERENCE, "m.room.test")
  1262. allowed_event_ids = [channel.json_body["event_id"]]
  1263. channel = self._send_relation(
  1264. RelationTypes.REFERENCE, "m.room.test", access_token=self.user2_token
  1265. )
  1266. ignored_event_ids = [channel.json_body["event_id"]]
  1267. before_aggregations, after_aggregations = self._test_ignored_user(
  1268. RelationTypes.REFERENCE, allowed_event_ids, ignored_event_ids
  1269. )
  1270. self.assertCountEqual(
  1271. [e["event_id"] for e in before_aggregations["chunk"]],
  1272. allowed_event_ids + ignored_event_ids,
  1273. )
  1274. self.assertCountEqual(
  1275. [e["event_id"] for e in after_aggregations["chunk"]], allowed_event_ids
  1276. )
  1277. def test_thread(self) -> None:
  1278. """Annotations should ignore"""
  1279. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1280. allowed_event_ids = [channel.json_body["event_id"]]
  1281. channel = self._send_relation(
  1282. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  1283. )
  1284. ignored_event_ids = [channel.json_body["event_id"]]
  1285. before_aggregations, after_aggregations = self._test_ignored_user(
  1286. RelationTypes.THREAD, allowed_event_ids, ignored_event_ids
  1287. )
  1288. self.assertEqual(before_aggregations["count"], 2)
  1289. self.assertTrue(before_aggregations["current_user_participated"])
  1290. # The latest thread event has some fields that don't matter.
  1291. self.assertEqual(
  1292. before_aggregations["latest_event"]["event_id"], ignored_event_ids[0]
  1293. )
  1294. self.assertEqual(after_aggregations["count"], 1)
  1295. self.assertTrue(after_aggregations["current_user_participated"])
  1296. # The latest thread event has some fields that don't matter.
  1297. self.assertEqual(
  1298. after_aggregations["latest_event"]["event_id"], allowed_event_ids[0]
  1299. )
  1300. class RelationRedactionTestCase(BaseRelationsTestCase):
  1301. """
  1302. Test the behaviour of relations when the parent or child event is redacted.
  1303. The behaviour of each relation type is subtly different which causes the tests
  1304. to be a bit repetitive, they follow a naming scheme of:
  1305. test_redact_(relation|parent)_{relation_type}
  1306. The first bit of "relation" means that the event with the relation defined
  1307. on it (the child event) is to be redacted. A "parent" means that the target
  1308. of the relation (the parent event) is to be redacted.
  1309. The relation_type describes which type of relation is under test (i.e. it is
  1310. related to the value of rel_type in the event content).
  1311. """
  1312. def _redact(self, event_id: str) -> None:
  1313. channel = self.make_request(
  1314. "POST",
  1315. f"/_matrix/client/r0/rooms/{self.room}/redact/{event_id}",
  1316. access_token=self.user_token,
  1317. content={},
  1318. )
  1319. self.assertEqual(200, channel.code, channel.json_body)
  1320. def _get_threads(self) -> List[Tuple[str, str]]:
  1321. """Request the threads in the room and returns a list of thread ID and latest event ID."""
  1322. # Request the threads in the room.
  1323. channel = self.make_request(
  1324. "GET",
  1325. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1326. access_token=self.user_token,
  1327. )
  1328. self.assertEquals(200, channel.code, channel.json_body)
  1329. threads = channel.json_body["chunk"]
  1330. return [
  1331. (
  1332. t["event_id"],
  1333. t["unsigned"]["m.relations"][RelationTypes.THREAD]["latest_event"][
  1334. "event_id"
  1335. ],
  1336. )
  1337. for t in threads
  1338. ]
  1339. def test_redact_relation_annotation(self) -> None:
  1340. """
  1341. Test that annotations of an event are properly handled after the
  1342. annotation is redacted.
  1343. The redacted relation should not be included in bundled aggregations or
  1344. the response to relations.
  1345. """
  1346. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", "a")
  1347. to_redact_event_id = channel.json_body["event_id"]
  1348. channel = self._send_relation(
  1349. RelationTypes.ANNOTATION, "m.reaction", "a", access_token=self.user2_token
  1350. )
  1351. unredacted_event_id = channel.json_body["event_id"]
  1352. # Both relations should exist.
  1353. event_ids = self._get_related_events()
  1354. relations = self._get_bundled_aggregations()
  1355. self.assertCountEqual(event_ids, [to_redact_event_id, unredacted_event_id])
  1356. self.assertEquals(
  1357. relations["m.annotation"],
  1358. {"chunk": [{"type": "m.reaction", "key": "a", "count": 2}]},
  1359. )
  1360. # Redact one of the reactions.
  1361. self._redact(to_redact_event_id)
  1362. # The unredacted relation should still exist.
  1363. event_ids = self._get_related_events()
  1364. relations = self._get_bundled_aggregations()
  1365. self.assertEquals(event_ids, [unredacted_event_id])
  1366. self.assertEquals(
  1367. relations["m.annotation"],
  1368. {"chunk": [{"type": "m.reaction", "key": "a", "count": 1}]},
  1369. )
  1370. def test_redact_relation_thread(self) -> None:
  1371. """
  1372. Test that thread replies are properly handled after the thread reply redacted.
  1373. The redacted event should not be included in bundled aggregations or
  1374. the response to relations.
  1375. """
  1376. # Create a thread with a few events in it.
  1377. thread_replies = []
  1378. for i in range(3):
  1379. channel = self._send_relation(
  1380. RelationTypes.THREAD,
  1381. EventTypes.Message,
  1382. content={"body": f"reply {i}", "msgtype": "m.text"},
  1383. )
  1384. thread_replies.append(channel.json_body["event_id"])
  1385. ##################################################
  1386. # Check the test data is configured as expected. #
  1387. ##################################################
  1388. self.assertEquals(self._get_related_events(), list(reversed(thread_replies)))
  1389. relations = self._get_bundled_aggregations()
  1390. self.assertDictContainsSubset(
  1391. {"count": 3, "current_user_participated": True},
  1392. relations[RelationTypes.THREAD],
  1393. )
  1394. # The latest event is the last sent event.
  1395. self.assertEqual(
  1396. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1397. thread_replies[-1],
  1398. )
  1399. # There should be one thread, the latest event is the event that will be redacted.
  1400. self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])
  1401. ##########################
  1402. # Redact the last event. #
  1403. ##########################
  1404. self._redact(thread_replies.pop())
  1405. # The thread should still exist, but the latest event should be updated.
  1406. self.assertEquals(self._get_related_events(), list(reversed(thread_replies)))
  1407. relations = self._get_bundled_aggregations()
  1408. self.assertDictContainsSubset(
  1409. {"count": 2, "current_user_participated": True},
  1410. relations[RelationTypes.THREAD],
  1411. )
  1412. # And the latest event is the last unredacted event.
  1413. self.assertEqual(
  1414. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1415. thread_replies[-1],
  1416. )
  1417. self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])
  1418. ###########################################
  1419. # Redact the *first* event in the thread. #
  1420. ###########################################
  1421. self._redact(thread_replies.pop(0))
  1422. # Nothing should have changed (except the thread count).
  1423. self.assertEquals(self._get_related_events(), thread_replies)
  1424. relations = self._get_bundled_aggregations()
  1425. self.assertDictContainsSubset(
  1426. {"count": 1, "current_user_participated": True},
  1427. relations[RelationTypes.THREAD],
  1428. )
  1429. # And the latest event is the last unredacted event.
  1430. self.assertEqual(
  1431. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1432. thread_replies[-1],
  1433. )
  1434. self.assertEqual(self._get_threads(), [(self.parent_id, thread_replies[-1])])
  1435. ####################################
  1436. # Redact the last remaining event. #
  1437. ####################################
  1438. self._redact(thread_replies.pop(0))
  1439. self.assertEquals(thread_replies, [])
  1440. # The event should no longer be considered a thread.
  1441. self.assertEquals(self._get_related_events(), [])
  1442. self.assertEquals(self._get_bundled_aggregations(), {})
  1443. self.assertEqual(self._get_threads(), [])
  1444. def test_redact_parent_edit(self) -> None:
  1445. """Test that edits of an event are redacted when the original event
  1446. is redacted.
  1447. """
  1448. # Add a relation
  1449. self._send_relation(
  1450. RelationTypes.REPLACE,
  1451. "m.room.message",
  1452. parent_id=self.parent_id,
  1453. content={
  1454. "msgtype": "m.text",
  1455. "body": "Wibble",
  1456. "m.new_content": {"msgtype": "m.text", "body": "First edit"},
  1457. },
  1458. )
  1459. # Check the relation is returned
  1460. event_ids = self._get_related_events()
  1461. relations = self._get_bundled_aggregations()
  1462. self.assertEqual(len(event_ids), 1)
  1463. self.assertIn(RelationTypes.REPLACE, relations)
  1464. # Redact the original event
  1465. self._redact(self.parent_id)
  1466. # The relations are not returned.
  1467. event_ids = self._get_related_events()
  1468. relations = self._get_bundled_aggregations()
  1469. self.assertEqual(len(event_ids), 0)
  1470. self.assertEqual(relations, {})
  1471. def test_redact_parent_annotation(self) -> None:
  1472. """Test that annotations of an event are viewable when the original event
  1473. is redacted.
  1474. """
  1475. # Add a relation
  1476. channel = self._send_relation(RelationTypes.ANNOTATION, "m.reaction", key="👍")
  1477. related_event_id = channel.json_body["event_id"]
  1478. # The relations should exist.
  1479. event_ids = self._get_related_events()
  1480. relations = self._get_bundled_aggregations()
  1481. self.assertEqual(len(event_ids), 1)
  1482. self.assertIn(RelationTypes.ANNOTATION, relations)
  1483. # Redact the original event.
  1484. self._redact(self.parent_id)
  1485. # The relations are returned.
  1486. event_ids = self._get_related_events()
  1487. relations = self._get_bundled_aggregations()
  1488. self.assertEquals(event_ids, [related_event_id])
  1489. self.assertEquals(
  1490. relations["m.annotation"],
  1491. {"chunk": [{"type": "m.reaction", "key": "👍", "count": 1}]},
  1492. )
  1493. def test_redact_parent_thread(self) -> None:
  1494. """
  1495. Test that thread replies are still available when the root event is redacted.
  1496. """
  1497. channel = self._send_relation(
  1498. RelationTypes.THREAD,
  1499. EventTypes.Message,
  1500. content={"body": "reply 1", "msgtype": "m.text"},
  1501. )
  1502. related_event_id = channel.json_body["event_id"]
  1503. # Redact one of the reactions.
  1504. self._redact(self.parent_id)
  1505. # The unredacted relation should still exist.
  1506. event_ids = self._get_related_events()
  1507. relations = self._get_bundled_aggregations()
  1508. self.assertEquals(len(event_ids), 1)
  1509. self.assertDictContainsSubset(
  1510. {
  1511. "count": 1,
  1512. "current_user_participated": True,
  1513. },
  1514. relations[RelationTypes.THREAD],
  1515. )
  1516. self.assertEqual(
  1517. relations[RelationTypes.THREAD]["latest_event"]["event_id"],
  1518. related_event_id,
  1519. )
  1520. class ThreadsTestCase(BaseRelationsTestCase):
  1521. def _get_threads(self, body: JsonDict) -> List[Tuple[str, str]]:
  1522. return [
  1523. (
  1524. ev["event_id"],
  1525. ev["unsigned"]["m.relations"]["m.thread"]["latest_event"]["event_id"],
  1526. )
  1527. for ev in body["chunk"]
  1528. ]
  1529. def test_threads(self) -> None:
  1530. """Create threads and ensure the ordering is due to their latest event."""
  1531. # Create 2 threads.
  1532. thread_1 = self.parent_id
  1533. res = self.helper.send(self.room, body="Thread Root!", tok=self.user_token)
  1534. thread_2 = res["event_id"]
  1535. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1536. reply_1 = channel.json_body["event_id"]
  1537. channel = self._send_relation(
  1538. RelationTypes.THREAD, "m.room.test", parent_id=thread_2
  1539. )
  1540. reply_2 = channel.json_body["event_id"]
  1541. # Request the threads in the room.
  1542. channel = self.make_request(
  1543. "GET",
  1544. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1545. access_token=self.user_token,
  1546. )
  1547. self.assertEquals(200, channel.code, channel.json_body)
  1548. threads = self._get_threads(channel.json_body)
  1549. self.assertEqual(threads, [(thread_2, reply_2), (thread_1, reply_1)])
  1550. # Update the first thread, the ordering should swap.
  1551. channel = self._send_relation(RelationTypes.THREAD, "m.room.test")
  1552. reply_3 = channel.json_body["event_id"]
  1553. channel = self.make_request(
  1554. "GET",
  1555. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1556. access_token=self.user_token,
  1557. )
  1558. self.assertEquals(200, channel.code, channel.json_body)
  1559. # Tuple of (thread ID, latest event ID) for each thread.
  1560. threads = self._get_threads(channel.json_body)
  1561. self.assertEqual(threads, [(thread_1, reply_3), (thread_2, reply_2)])
  1562. def test_pagination(self) -> None:
  1563. """Create threads and paginate through them."""
  1564. # Create 2 threads.
  1565. thread_1 = self.parent_id
  1566. res = self.helper.send(self.room, body="Thread Root!", tok=self.user_token)
  1567. thread_2 = res["event_id"]
  1568. self._send_relation(RelationTypes.THREAD, "m.room.test")
  1569. self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)
  1570. # Request the threads in the room.
  1571. channel = self.make_request(
  1572. "GET",
  1573. f"/_matrix/client/v1/rooms/{self.room}/threads?limit=1",
  1574. access_token=self.user_token,
  1575. )
  1576. self.assertEquals(200, channel.code, channel.json_body)
  1577. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1578. self.assertEqual(thread_roots, [thread_2])
  1579. # Make sure next_batch has something in it that looks like it could be a
  1580. # valid token.
  1581. next_batch = channel.json_body.get("next_batch")
  1582. self.assertIsInstance(next_batch, str, channel.json_body)
  1583. channel = self.make_request(
  1584. "GET",
  1585. f"/_matrix/client/v1/rooms/{self.room}/threads?limit=1&from={next_batch}",
  1586. access_token=self.user_token,
  1587. )
  1588. self.assertEquals(200, channel.code, channel.json_body)
  1589. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1590. self.assertEqual(thread_roots, [thread_1], channel.json_body)
  1591. self.assertNotIn("next_batch", channel.json_body, channel.json_body)
  1592. def test_include(self) -> None:
  1593. """Filtering threads to all or participated in should work."""
  1594. # Thread 1 has the user as the root event.
  1595. thread_1 = self.parent_id
  1596. self._send_relation(
  1597. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  1598. )
  1599. # Thread 2 has the user replying.
  1600. res = self.helper.send(self.room, body="Thread Root!", tok=self.user2_token)
  1601. thread_2 = res["event_id"]
  1602. self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)
  1603. # Thread 3 has the user not participating in.
  1604. res = self.helper.send(self.room, body="Another thread!", tok=self.user2_token)
  1605. thread_3 = res["event_id"]
  1606. self._send_relation(
  1607. RelationTypes.THREAD,
  1608. "m.room.test",
  1609. access_token=self.user2_token,
  1610. parent_id=thread_3,
  1611. )
  1612. # All threads in the room.
  1613. channel = self.make_request(
  1614. "GET",
  1615. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1616. access_token=self.user_token,
  1617. )
  1618. self.assertEquals(200, channel.code, channel.json_body)
  1619. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1620. self.assertEqual(
  1621. thread_roots, [thread_3, thread_2, thread_1], channel.json_body
  1622. )
  1623. # Only participated threads.
  1624. channel = self.make_request(
  1625. "GET",
  1626. f"/_matrix/client/v1/rooms/{self.room}/threads?include=participated",
  1627. access_token=self.user_token,
  1628. )
  1629. self.assertEquals(200, channel.code, channel.json_body)
  1630. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1631. self.assertEqual(thread_roots, [thread_2, thread_1], channel.json_body)
  1632. def test_ignored_user(self) -> None:
  1633. """Events from ignored users should be ignored."""
  1634. # Thread 1 has a reply from an ignored user.
  1635. thread_1 = self.parent_id
  1636. self._send_relation(
  1637. RelationTypes.THREAD, "m.room.test", access_token=self.user2_token
  1638. )
  1639. # Thread 2 is created by an ignored user.
  1640. res = self.helper.send(self.room, body="Thread Root!", tok=self.user2_token)
  1641. thread_2 = res["event_id"]
  1642. self._send_relation(RelationTypes.THREAD, "m.room.test", parent_id=thread_2)
  1643. # Ignore user2.
  1644. self.get_success(
  1645. self.store.add_account_data_for_user(
  1646. self.user_id,
  1647. AccountDataTypes.IGNORED_USER_LIST,
  1648. {"ignored_users": {self.user2_id: {}}},
  1649. )
  1650. )
  1651. # Only thread 1 is returned.
  1652. channel = self.make_request(
  1653. "GET",
  1654. f"/_matrix/client/v1/rooms/{self.room}/threads",
  1655. access_token=self.user_token,
  1656. )
  1657. self.assertEquals(200, channel.code, channel.json_body)
  1658. thread_roots = [ev["event_id"] for ev in channel.json_body["chunk"]]
  1659. self.assertEqual(thread_roots, [thread_1], channel.json_body)