@unwanted/matrix-sdk-mini 34.12.0-1 → 34.12.0-3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (636) hide show
  1. package/git-revision.txt +1 -1
  2. package/lib/@types/event.d.ts +0 -19
  3. package/lib/@types/event.d.ts.map +1 -1
  4. package/lib/@types/event.js.map +1 -1
  5. package/lib/@types/global.d.js +0 -2
  6. package/lib/@types/global.d.js.map +1 -1
  7. package/lib/browser-index.d.ts.map +1 -1
  8. package/lib/browser-index.js +0 -11
  9. package/lib/browser-index.js.map +1 -1
  10. package/lib/client.d.ts +2 -1224
  11. package/lib/client.d.ts.map +1 -1
  12. package/lib/client.js +345 -2826
  13. package/lib/client.js.map +1 -1
  14. package/lib/embedded.d.ts +0 -22
  15. package/lib/embedded.d.ts.map +1 -1
  16. package/lib/embedded.js +24 -167
  17. package/lib/embedded.js.map +1 -1
  18. package/lib/event-mapper.d.ts.map +1 -1
  19. package/lib/event-mapper.js +0 -4
  20. package/lib/event-mapper.js.map +1 -1
  21. package/lib/matrix.d.ts +0 -25
  22. package/lib/matrix.d.ts.map +1 -1
  23. package/lib/matrix.js +1 -30
  24. package/lib/matrix.js.map +1 -1
  25. package/lib/models/MSC3089Branch.d.ts.map +1 -1
  26. package/lib/models/MSC3089Branch.js +0 -3
  27. package/lib/models/MSC3089Branch.js.map +1 -1
  28. package/lib/models/event.d.ts +0 -94
  29. package/lib/models/event.d.ts.map +1 -1
  30. package/lib/models/event.js +0 -274
  31. package/lib/models/event.js.map +1 -1
  32. package/lib/models/poll.d.ts.map +1 -1
  33. package/lib/models/poll.js +1 -5
  34. package/lib/models/poll.js.map +1 -1
  35. package/lib/models/relations-container.d.ts.map +1 -1
  36. package/lib/models/relations-container.js +1 -7
  37. package/lib/models/relations-container.js.map +1 -1
  38. package/lib/models/relations.d.ts +0 -1
  39. package/lib/models/relations.d.ts.map +1 -1
  40. package/lib/models/relations.js +0 -8
  41. package/lib/models/relations.js.map +1 -1
  42. package/lib/models/room-state.d.ts.map +1 -1
  43. package/lib/models/room-state.js +10 -26
  44. package/lib/models/room-state.js.map +1 -1
  45. package/lib/models/room.d.ts +0 -18
  46. package/lib/models/room.d.ts.map +1 -1
  47. package/lib/models/room.js +94 -148
  48. package/lib/models/room.js.map +1 -1
  49. package/lib/models/thread.d.ts.map +1 -1
  50. package/lib/models/thread.js +0 -1
  51. package/lib/models/thread.js.map +1 -1
  52. package/lib/sliding-sync-sdk.d.ts +2 -3
  53. package/lib/sliding-sync-sdk.d.ts.map +1 -1
  54. package/lib/sliding-sync-sdk.js +41 -90
  55. package/lib/sliding-sync-sdk.js.map +1 -1
  56. package/lib/sync.d.ts +0 -12
  57. package/lib/sync.d.ts.map +1 -1
  58. package/lib/sync.js +1 -73
  59. package/lib/sync.js.map +1 -1
  60. package/lib/testing.d.ts +0 -48
  61. package/lib/testing.d.ts.map +1 -1
  62. package/lib/testing.js +0 -105
  63. package/lib/testing.js.map +1 -1
  64. package/package.json +1 -3
  65. package/src/@types/event.ts +2 -36
  66. package/src/@types/global.d.ts +0 -3
  67. package/src/browser-index.ts +0 -11
  68. package/src/client.ts +52 -2876
  69. package/src/embedded.ts +3 -132
  70. package/src/event-mapper.ts +0 -4
  71. package/src/matrix.ts +0 -41
  72. package/src/models/MSC3089Branch.ts +0 -3
  73. package/src/models/event.ts +0 -289
  74. package/src/models/poll.ts +0 -6
  75. package/src/models/relations-container.ts +1 -8
  76. package/src/models/relations.ts +0 -8
  77. package/src/models/room-state.ts +2 -8
  78. package/src/models/room.ts +0 -62
  79. package/src/models/thread.ts +0 -1
  80. package/src/sliding-sync-sdk.ts +2 -72
  81. package/src/sync.ts +1 -98
  82. package/src/testing.ts +0 -108
  83. package/lib/@types/crypto.d.ts +0 -47
  84. package/lib/@types/crypto.d.ts.map +0 -1
  85. package/lib/@types/crypto.js +0 -1
  86. package/lib/@types/crypto.js.map +0 -1
  87. package/lib/@types/matrix-sdk-crypto-wasm.d.js +0 -1
  88. package/lib/@types/matrix-sdk-crypto-wasm.d.js.map +0 -1
  89. package/lib/common-crypto/CryptoBackend.d.ts +0 -240
  90. package/lib/common-crypto/CryptoBackend.d.ts.map +0 -1
  91. package/lib/common-crypto/CryptoBackend.js +0 -73
  92. package/lib/common-crypto/CryptoBackend.js.map +0 -1
  93. package/lib/common-crypto/key-passphrase.d.ts +0 -14
  94. package/lib/common-crypto/key-passphrase.d.ts.map +0 -1
  95. package/lib/common-crypto/key-passphrase.js +0 -33
  96. package/lib/common-crypto/key-passphrase.js.map +0 -1
  97. package/lib/crypto/CrossSigning.d.ts +0 -184
  98. package/lib/crypto/CrossSigning.d.ts.map +0 -1
  99. package/lib/crypto/CrossSigning.js +0 -718
  100. package/lib/crypto/CrossSigning.js.map +0 -1
  101. package/lib/crypto/DeviceList.d.ts +0 -216
  102. package/lib/crypto/DeviceList.d.ts.map +0 -1
  103. package/lib/crypto/DeviceList.js +0 -892
  104. package/lib/crypto/DeviceList.js.map +0 -1
  105. package/lib/crypto/EncryptionSetup.d.ts +0 -152
  106. package/lib/crypto/EncryptionSetup.d.ts.map +0 -1
  107. package/lib/crypto/EncryptionSetup.js +0 -356
  108. package/lib/crypto/EncryptionSetup.js.map +0 -1
  109. package/lib/crypto/OlmDevice.d.ts +0 -457
  110. package/lib/crypto/OlmDevice.d.ts.map +0 -1
  111. package/lib/crypto/OlmDevice.js +0 -1241
  112. package/lib/crypto/OlmDevice.js.map +0 -1
  113. package/lib/crypto/OutgoingRoomKeyRequestManager.d.ts +0 -109
  114. package/lib/crypto/OutgoingRoomKeyRequestManager.d.ts.map +0 -1
  115. package/lib/crypto/OutgoingRoomKeyRequestManager.js +0 -415
  116. package/lib/crypto/OutgoingRoomKeyRequestManager.js.map +0 -1
  117. package/lib/crypto/RoomList.d.ts +0 -26
  118. package/lib/crypto/RoomList.d.ts.map +0 -1
  119. package/lib/crypto/RoomList.js +0 -71
  120. package/lib/crypto/RoomList.js.map +0 -1
  121. package/lib/crypto/SecretSharing.d.ts +0 -24
  122. package/lib/crypto/SecretSharing.d.ts.map +0 -1
  123. package/lib/crypto/SecretSharing.js +0 -194
  124. package/lib/crypto/SecretSharing.js.map +0 -1
  125. package/lib/crypto/SecretStorage.d.ts +0 -55
  126. package/lib/crypto/SecretStorage.d.ts.map +0 -1
  127. package/lib/crypto/SecretStorage.js +0 -118
  128. package/lib/crypto/SecretStorage.js.map +0 -1
  129. package/lib/crypto/aes.d.ts +0 -6
  130. package/lib/crypto/aes.d.ts.map +0 -1
  131. package/lib/crypto/aes.js +0 -24
  132. package/lib/crypto/aes.js.map +0 -1
  133. package/lib/crypto/algorithms/base.d.ts +0 -156
  134. package/lib/crypto/algorithms/base.d.ts.map +0 -1
  135. package/lib/crypto/algorithms/base.js +0 -187
  136. package/lib/crypto/algorithms/base.js.map +0 -1
  137. package/lib/crypto/algorithms/index.d.ts +0 -4
  138. package/lib/crypto/algorithms/index.d.ts.map +0 -1
  139. package/lib/crypto/algorithms/index.js +0 -20
  140. package/lib/crypto/algorithms/index.js.map +0 -1
  141. package/lib/crypto/algorithms/megolm.d.ts +0 -385
  142. package/lib/crypto/algorithms/megolm.d.ts.map +0 -1
  143. package/lib/crypto/algorithms/megolm.js +0 -1822
  144. package/lib/crypto/algorithms/megolm.js.map +0 -1
  145. package/lib/crypto/algorithms/olm.d.ts +0 -5
  146. package/lib/crypto/algorithms/olm.d.ts.map +0 -1
  147. package/lib/crypto/algorithms/olm.js +0 -299
  148. package/lib/crypto/algorithms/olm.js.map +0 -1
  149. package/lib/crypto/api.d.ts +0 -32
  150. package/lib/crypto/api.d.ts.map +0 -1
  151. package/lib/crypto/api.js +0 -22
  152. package/lib/crypto/api.js.map +0 -1
  153. package/lib/crypto/backup.d.ts +0 -227
  154. package/lib/crypto/backup.d.ts.map +0 -1
  155. package/lib/crypto/backup.js +0 -824
  156. package/lib/crypto/backup.js.map +0 -1
  157. package/lib/crypto/crypto.d.ts +0 -3
  158. package/lib/crypto/crypto.d.ts.map +0 -1
  159. package/lib/crypto/crypto.js +0 -19
  160. package/lib/crypto/crypto.js.map +0 -1
  161. package/lib/crypto/dehydration.d.ts +0 -34
  162. package/lib/crypto/dehydration.d.ts.map +0 -1
  163. package/lib/crypto/dehydration.js +0 -252
  164. package/lib/crypto/dehydration.js.map +0 -1
  165. package/lib/crypto/device-converter.d.ts +0 -9
  166. package/lib/crypto/device-converter.d.ts.map +0 -1
  167. package/lib/crypto/device-converter.js +0 -42
  168. package/lib/crypto/device-converter.js.map +0 -1
  169. package/lib/crypto/deviceinfo.d.ts +0 -99
  170. package/lib/crypto/deviceinfo.d.ts.map +0 -1
  171. package/lib/crypto/deviceinfo.js +0 -148
  172. package/lib/crypto/deviceinfo.js.map +0 -1
  173. package/lib/crypto/index.d.ts +0 -1209
  174. package/lib/crypto/index.d.ts.map +0 -1
  175. package/lib/crypto/index.js +0 -4097
  176. package/lib/crypto/index.js.map +0 -1
  177. package/lib/crypto/key_passphrase.d.ts +0 -14
  178. package/lib/crypto/key_passphrase.d.ts.map +0 -1
  179. package/lib/crypto/key_passphrase.js +0 -44
  180. package/lib/crypto/key_passphrase.js.map +0 -1
  181. package/lib/crypto/keybackup.d.ts +0 -18
  182. package/lib/crypto/keybackup.d.ts.map +0 -1
  183. package/lib/crypto/keybackup.js +0 -1
  184. package/lib/crypto/keybackup.js.map +0 -1
  185. package/lib/crypto/olmlib.d.ts +0 -129
  186. package/lib/crypto/olmlib.d.ts.map +0 -1
  187. package/lib/crypto/olmlib.js +0 -492
  188. package/lib/crypto/olmlib.js.map +0 -1
  189. package/lib/crypto/recoverykey.d.ts +0 -2
  190. package/lib/crypto/recoverykey.d.ts.map +0 -1
  191. package/lib/crypto/recoverykey.js +0 -19
  192. package/lib/crypto/recoverykey.js.map +0 -1
  193. package/lib/crypto/store/base.d.ts +0 -252
  194. package/lib/crypto/store/base.d.ts.map +0 -1
  195. package/lib/crypto/store/base.js +0 -64
  196. package/lib/crypto/store/base.js.map +0 -1
  197. package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts +0 -187
  198. package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts.map +0 -1
  199. package/lib/crypto/store/indexeddb-crypto-store-backend.js +0 -1145
  200. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +0 -1
  201. package/lib/crypto/store/indexeddb-crypto-store.d.ts +0 -432
  202. package/lib/crypto/store/indexeddb-crypto-store.d.ts.map +0 -1
  203. package/lib/crypto/store/indexeddb-crypto-store.js +0 -728
  204. package/lib/crypto/store/indexeddb-crypto-store.js.map +0 -1
  205. package/lib/crypto/store/localStorage-crypto-store.d.ts +0 -119
  206. package/lib/crypto/store/localStorage-crypto-store.d.ts.map +0 -1
  207. package/lib/crypto/store/localStorage-crypto-store.js +0 -531
  208. package/lib/crypto/store/localStorage-crypto-store.js.map +0 -1
  209. package/lib/crypto/store/memory-crypto-store.d.ts +0 -215
  210. package/lib/crypto/store/memory-crypto-store.d.ts.map +0 -1
  211. package/lib/crypto/store/memory-crypto-store.js +0 -622
  212. package/lib/crypto/store/memory-crypto-store.js.map +0 -1
  213. package/lib/crypto/verification/Base.d.ts +0 -105
  214. package/lib/crypto/verification/Base.d.ts.map +0 -1
  215. package/lib/crypto/verification/Base.js +0 -372
  216. package/lib/crypto/verification/Base.js.map +0 -1
  217. package/lib/crypto/verification/Error.d.ts +0 -35
  218. package/lib/crypto/verification/Error.d.ts.map +0 -1
  219. package/lib/crypto/verification/Error.js +0 -86
  220. package/lib/crypto/verification/Error.js.map +0 -1
  221. package/lib/crypto/verification/IllegalMethod.d.ts +0 -15
  222. package/lib/crypto/verification/IllegalMethod.d.ts.map +0 -1
  223. package/lib/crypto/verification/IllegalMethod.js +0 -43
  224. package/lib/crypto/verification/IllegalMethod.js.map +0 -1
  225. package/lib/crypto/verification/QRCode.d.ts +0 -51
  226. package/lib/crypto/verification/QRCode.d.ts.map +0 -1
  227. package/lib/crypto/verification/QRCode.js +0 -277
  228. package/lib/crypto/verification/QRCode.js.map +0 -1
  229. package/lib/crypto/verification/SAS.d.ts +0 -27
  230. package/lib/crypto/verification/SAS.d.ts.map +0 -1
  231. package/lib/crypto/verification/SAS.js +0 -485
  232. package/lib/crypto/verification/SAS.js.map +0 -1
  233. package/lib/crypto/verification/SASDecimal.d.ts +0 -8
  234. package/lib/crypto/verification/SASDecimal.d.ts.map +0 -1
  235. package/lib/crypto/verification/SASDecimal.js +0 -34
  236. package/lib/crypto/verification/SASDecimal.js.map +0 -1
  237. package/lib/crypto/verification/request/Channel.d.ts +0 -18
  238. package/lib/crypto/verification/request/Channel.d.ts.map +0 -1
  239. package/lib/crypto/verification/request/Channel.js +0 -1
  240. package/lib/crypto/verification/request/Channel.js.map +0 -1
  241. package/lib/crypto/verification/request/InRoomChannel.d.ts +0 -113
  242. package/lib/crypto/verification/request/InRoomChannel.d.ts.map +0 -1
  243. package/lib/crypto/verification/request/InRoomChannel.js +0 -351
  244. package/lib/crypto/verification/request/InRoomChannel.js.map +0 -1
  245. package/lib/crypto/verification/request/ToDeviceChannel.d.ts +0 -105
  246. package/lib/crypto/verification/request/ToDeviceChannel.d.ts.map +0 -1
  247. package/lib/crypto/verification/request/ToDeviceChannel.js +0 -328
  248. package/lib/crypto/verification/request/ToDeviceChannel.js.map +0 -1
  249. package/lib/crypto/verification/request/VerificationRequest.d.ts +0 -227
  250. package/lib/crypto/verification/request/VerificationRequest.d.ts.map +0 -1
  251. package/lib/crypto/verification/request/VerificationRequest.js +0 -937
  252. package/lib/crypto/verification/request/VerificationRequest.js.map +0 -1
  253. package/lib/crypto-api/CryptoEvent.d.ts +0 -69
  254. package/lib/crypto-api/CryptoEvent.d.ts.map +0 -1
  255. package/lib/crypto-api/CryptoEvent.js +0 -33
  256. package/lib/crypto-api/CryptoEvent.js.map +0 -1
  257. package/lib/crypto-api/CryptoEventHandlerMap.d.ts +0 -16
  258. package/lib/crypto-api/CryptoEventHandlerMap.d.ts.map +0 -1
  259. package/lib/crypto-api/CryptoEventHandlerMap.js +0 -22
  260. package/lib/crypto-api/CryptoEventHandlerMap.js.map +0 -1
  261. package/lib/crypto-api/index.d.ts +0 -978
  262. package/lib/crypto-api/index.d.ts.map +0 -1
  263. package/lib/crypto-api/index.js +0 -304
  264. package/lib/crypto-api/index.js.map +0 -1
  265. package/lib/crypto-api/key-passphrase.d.ts +0 -11
  266. package/lib/crypto-api/key-passphrase.d.ts.map +0 -1
  267. package/lib/crypto-api/key-passphrase.js +0 -51
  268. package/lib/crypto-api/key-passphrase.js.map +0 -1
  269. package/lib/crypto-api/keybackup.d.ts +0 -88
  270. package/lib/crypto-api/keybackup.d.ts.map +0 -1
  271. package/lib/crypto-api/keybackup.js +0 -1
  272. package/lib/crypto-api/keybackup.js.map +0 -1
  273. package/lib/crypto-api/recovery-key.d.ts +0 -11
  274. package/lib/crypto-api/recovery-key.d.ts.map +0 -1
  275. package/lib/crypto-api/recovery-key.js +0 -65
  276. package/lib/crypto-api/recovery-key.js.map +0 -1
  277. package/lib/crypto-api/verification.d.ts +0 -344
  278. package/lib/crypto-api/verification.d.ts.map +0 -1
  279. package/lib/crypto-api/verification.js +0 -91
  280. package/lib/crypto-api/verification.js.map +0 -1
  281. package/lib/matrixrtc/CallMembership.d.ts +0 -66
  282. package/lib/matrixrtc/CallMembership.d.ts.map +0 -1
  283. package/lib/matrixrtc/CallMembership.js +0 -197
  284. package/lib/matrixrtc/CallMembership.js.map +0 -1
  285. package/lib/matrixrtc/LivekitFocus.d.ts +0 -16
  286. package/lib/matrixrtc/LivekitFocus.d.ts.map +0 -1
  287. package/lib/matrixrtc/LivekitFocus.js +0 -20
  288. package/lib/matrixrtc/LivekitFocus.js.map +0 -1
  289. package/lib/matrixrtc/MatrixRTCSession.d.ts +0 -295
  290. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +0 -1
  291. package/lib/matrixrtc/MatrixRTCSession.js +0 -1043
  292. package/lib/matrixrtc/MatrixRTCSession.js.map +0 -1
  293. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts +0 -40
  294. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts.map +0 -1
  295. package/lib/matrixrtc/MatrixRTCSessionManager.js +0 -146
  296. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +0 -1
  297. package/lib/matrixrtc/focus.d.ts +0 -10
  298. package/lib/matrixrtc/focus.d.ts.map +0 -1
  299. package/lib/matrixrtc/focus.js +0 -1
  300. package/lib/matrixrtc/focus.js.map +0 -1
  301. package/lib/matrixrtc/index.d.ts +0 -7
  302. package/lib/matrixrtc/index.d.ts.map +0 -1
  303. package/lib/matrixrtc/index.js +0 -21
  304. package/lib/matrixrtc/index.js.map +0 -1
  305. package/lib/matrixrtc/types.d.ts +0 -19
  306. package/lib/matrixrtc/types.d.ts.map +0 -1
  307. package/lib/matrixrtc/types.js +0 -1
  308. package/lib/matrixrtc/types.js.map +0 -1
  309. package/lib/rendezvous/MSC4108SignInWithQR.d.ts +0 -112
  310. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +0 -1
  311. package/lib/rendezvous/MSC4108SignInWithQR.js +0 -392
  312. package/lib/rendezvous/MSC4108SignInWithQR.js.map +0 -1
  313. package/lib/rendezvous/RendezvousChannel.d.ts +0 -27
  314. package/lib/rendezvous/RendezvousChannel.d.ts.map +0 -1
  315. package/lib/rendezvous/RendezvousChannel.js +0 -1
  316. package/lib/rendezvous/RendezvousChannel.js.map +0 -1
  317. package/lib/rendezvous/RendezvousCode.d.ts +0 -9
  318. package/lib/rendezvous/RendezvousCode.d.ts.map +0 -1
  319. package/lib/rendezvous/RendezvousCode.js +0 -1
  320. package/lib/rendezvous/RendezvousCode.js.map +0 -1
  321. package/lib/rendezvous/RendezvousError.d.ts +0 -6
  322. package/lib/rendezvous/RendezvousError.d.ts.map +0 -1
  323. package/lib/rendezvous/RendezvousError.js +0 -23
  324. package/lib/rendezvous/RendezvousError.js.map +0 -1
  325. package/lib/rendezvous/RendezvousFailureReason.d.ts +0 -31
  326. package/lib/rendezvous/RendezvousFailureReason.d.ts.map +0 -1
  327. package/lib/rendezvous/RendezvousFailureReason.js +0 -38
  328. package/lib/rendezvous/RendezvousFailureReason.js.map +0 -1
  329. package/lib/rendezvous/RendezvousIntent.d.ts +0 -5
  330. package/lib/rendezvous/RendezvousIntent.d.ts.map +0 -1
  331. package/lib/rendezvous/RendezvousIntent.js +0 -22
  332. package/lib/rendezvous/RendezvousIntent.js.map +0 -1
  333. package/lib/rendezvous/RendezvousTransport.d.ts +0 -36
  334. package/lib/rendezvous/RendezvousTransport.d.ts.map +0 -1
  335. package/lib/rendezvous/RendezvousTransport.js +0 -1
  336. package/lib/rendezvous/RendezvousTransport.js.map +0 -1
  337. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts +0 -58
  338. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts.map +0 -1
  339. package/lib/rendezvous/channels/MSC4108SecureChannel.js +0 -246
  340. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +0 -1
  341. package/lib/rendezvous/channels/index.d.ts +0 -2
  342. package/lib/rendezvous/channels/index.d.ts.map +0 -1
  343. package/lib/rendezvous/channels/index.js +0 -18
  344. package/lib/rendezvous/channels/index.js.map +0 -1
  345. package/lib/rendezvous/index.d.ts +0 -10
  346. package/lib/rendezvous/index.d.ts.map +0 -1
  347. package/lib/rendezvous/index.js +0 -23
  348. package/lib/rendezvous/index.js.map +0 -1
  349. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +0 -61
  350. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +0 -1
  351. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +0 -253
  352. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +0 -1
  353. package/lib/rendezvous/transports/index.d.ts +0 -2
  354. package/lib/rendezvous/transports/index.d.ts.map +0 -1
  355. package/lib/rendezvous/transports/index.js +0 -18
  356. package/lib/rendezvous/transports/index.js.map +0 -1
  357. package/lib/rust-crypto/CrossSigningIdentity.d.ts +0 -33
  358. package/lib/rust-crypto/CrossSigningIdentity.d.ts.map +0 -1
  359. package/lib/rust-crypto/CrossSigningIdentity.js +0 -157
  360. package/lib/rust-crypto/CrossSigningIdentity.js.map +0 -1
  361. package/lib/rust-crypto/DehydratedDeviceManager.d.ts +0 -98
  362. package/lib/rust-crypto/DehydratedDeviceManager.d.ts.map +0 -1
  363. package/lib/rust-crypto/DehydratedDeviceManager.js +0 -285
  364. package/lib/rust-crypto/DehydratedDeviceManager.js.map +0 -1
  365. package/lib/rust-crypto/KeyClaimManager.d.ts +0 -33
  366. package/lib/rust-crypto/KeyClaimManager.d.ts.map +0 -1
  367. package/lib/rust-crypto/KeyClaimManager.js +0 -82
  368. package/lib/rust-crypto/KeyClaimManager.js.map +0 -1
  369. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts +0 -43
  370. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +0 -1
  371. package/lib/rust-crypto/OutgoingRequestProcessor.js +0 -195
  372. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +0 -1
  373. package/lib/rust-crypto/OutgoingRequestsManager.d.ts +0 -47
  374. package/lib/rust-crypto/OutgoingRequestsManager.d.ts.map +0 -1
  375. package/lib/rust-crypto/OutgoingRequestsManager.js +0 -148
  376. package/lib/rust-crypto/OutgoingRequestsManager.js.map +0 -1
  377. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +0 -120
  378. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts.map +0 -1
  379. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +0 -467
  380. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +0 -1
  381. package/lib/rust-crypto/RoomEncryptor.d.ts +0 -98
  382. package/lib/rust-crypto/RoomEncryptor.d.ts.map +0 -1
  383. package/lib/rust-crypto/RoomEncryptor.js +0 -299
  384. package/lib/rust-crypto/RoomEncryptor.js.map +0 -1
  385. package/lib/rust-crypto/backup.d.ts +0 -254
  386. package/lib/rust-crypto/backup.d.ts.map +0 -1
  387. package/lib/rust-crypto/backup.js +0 -837
  388. package/lib/rust-crypto/backup.js.map +0 -1
  389. package/lib/rust-crypto/constants.d.ts +0 -3
  390. package/lib/rust-crypto/constants.d.ts.map +0 -1
  391. package/lib/rust-crypto/constants.js +0 -19
  392. package/lib/rust-crypto/constants.js.map +0 -1
  393. package/lib/rust-crypto/device-converter.d.ts +0 -28
  394. package/lib/rust-crypto/device-converter.d.ts.map +0 -1
  395. package/lib/rust-crypto/device-converter.js +0 -123
  396. package/lib/rust-crypto/device-converter.js.map +0 -1
  397. package/lib/rust-crypto/index.d.ts +0 -61
  398. package/lib/rust-crypto/index.d.ts.map +0 -1
  399. package/lib/rust-crypto/index.js +0 -152
  400. package/lib/rust-crypto/index.js.map +0 -1
  401. package/lib/rust-crypto/libolm_migration.d.ts +0 -81
  402. package/lib/rust-crypto/libolm_migration.d.ts.map +0 -1
  403. package/lib/rust-crypto/libolm_migration.js +0 -459
  404. package/lib/rust-crypto/libolm_migration.js.map +0 -1
  405. package/lib/rust-crypto/rust-crypto.d.ts +0 -556
  406. package/lib/rust-crypto/rust-crypto.d.ts.map +0 -1
  407. package/lib/rust-crypto/rust-crypto.js +0 -2016
  408. package/lib/rust-crypto/rust-crypto.js.map +0 -1
  409. package/lib/rust-crypto/secret-storage.d.ts +0 -22
  410. package/lib/rust-crypto/secret-storage.d.ts.map +0 -1
  411. package/lib/rust-crypto/secret-storage.js +0 -63
  412. package/lib/rust-crypto/secret-storage.js.map +0 -1
  413. package/lib/rust-crypto/verification.d.ts +0 -319
  414. package/lib/rust-crypto/verification.d.ts.map +0 -1
  415. package/lib/rust-crypto/verification.js +0 -816
  416. package/lib/rust-crypto/verification.js.map +0 -1
  417. package/lib/secret-storage.d.ts +0 -370
  418. package/lib/secret-storage.d.ts.map +0 -1
  419. package/lib/secret-storage.js +0 -466
  420. package/lib/secret-storage.js.map +0 -1
  421. package/lib/webrtc/audioContext.d.ts +0 -15
  422. package/lib/webrtc/audioContext.d.ts.map +0 -1
  423. package/lib/webrtc/audioContext.js +0 -46
  424. package/lib/webrtc/audioContext.js.map +0 -1
  425. package/lib/webrtc/call.d.ts +0 -560
  426. package/lib/webrtc/call.d.ts.map +0 -1
  427. package/lib/webrtc/call.js +0 -2541
  428. package/lib/webrtc/call.js.map +0 -1
  429. package/lib/webrtc/callEventHandler.d.ts +0 -37
  430. package/lib/webrtc/callEventHandler.d.ts.map +0 -1
  431. package/lib/webrtc/callEventHandler.js +0 -344
  432. package/lib/webrtc/callEventHandler.js.map +0 -1
  433. package/lib/webrtc/callEventTypes.d.ts +0 -73
  434. package/lib/webrtc/callEventTypes.d.ts.map +0 -1
  435. package/lib/webrtc/callEventTypes.js +0 -13
  436. package/lib/webrtc/callEventTypes.js.map +0 -1
  437. package/lib/webrtc/callFeed.d.ts +0 -128
  438. package/lib/webrtc/callFeed.d.ts.map +0 -1
  439. package/lib/webrtc/callFeed.js +0 -289
  440. package/lib/webrtc/callFeed.js.map +0 -1
  441. package/lib/webrtc/groupCall.d.ts +0 -323
  442. package/lib/webrtc/groupCall.d.ts.map +0 -1
  443. package/lib/webrtc/groupCall.js +0 -1337
  444. package/lib/webrtc/groupCall.js.map +0 -1
  445. package/lib/webrtc/groupCallEventHandler.d.ts +0 -31
  446. package/lib/webrtc/groupCallEventHandler.d.ts.map +0 -1
  447. package/lib/webrtc/groupCallEventHandler.js +0 -178
  448. package/lib/webrtc/groupCallEventHandler.js.map +0 -1
  449. package/lib/webrtc/mediaHandler.d.ts +0 -89
  450. package/lib/webrtc/mediaHandler.d.ts.map +0 -1
  451. package/lib/webrtc/mediaHandler.js +0 -437
  452. package/lib/webrtc/mediaHandler.js.map +0 -1
  453. package/lib/webrtc/stats/callFeedStatsReporter.d.ts +0 -8
  454. package/lib/webrtc/stats/callFeedStatsReporter.d.ts.map +0 -1
  455. package/lib/webrtc/stats/callFeedStatsReporter.js +0 -82
  456. package/lib/webrtc/stats/callFeedStatsReporter.js.map +0 -1
  457. package/lib/webrtc/stats/callStatsReportGatherer.d.ts +0 -25
  458. package/lib/webrtc/stats/callStatsReportGatherer.d.ts.map +0 -1
  459. package/lib/webrtc/stats/callStatsReportGatherer.js +0 -199
  460. package/lib/webrtc/stats/callStatsReportGatherer.js.map +0 -1
  461. package/lib/webrtc/stats/callStatsReportSummary.d.ts +0 -17
  462. package/lib/webrtc/stats/callStatsReportSummary.d.ts.map +0 -1
  463. package/lib/webrtc/stats/callStatsReportSummary.js +0 -1
  464. package/lib/webrtc/stats/callStatsReportSummary.js.map +0 -1
  465. package/lib/webrtc/stats/connectionStats.d.ts +0 -28
  466. package/lib/webrtc/stats/connectionStats.d.ts.map +0 -1
  467. package/lib/webrtc/stats/connectionStats.js +0 -26
  468. package/lib/webrtc/stats/connectionStats.js.map +0 -1
  469. package/lib/webrtc/stats/connectionStatsBuilder.d.ts +0 -5
  470. package/lib/webrtc/stats/connectionStatsBuilder.d.ts.map +0 -1
  471. package/lib/webrtc/stats/connectionStatsBuilder.js +0 -27
  472. package/lib/webrtc/stats/connectionStatsBuilder.js.map +0 -1
  473. package/lib/webrtc/stats/connectionStatsReportBuilder.d.ts +0 -7
  474. package/lib/webrtc/stats/connectionStatsReportBuilder.d.ts.map +0 -1
  475. package/lib/webrtc/stats/connectionStatsReportBuilder.js +0 -121
  476. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +0 -1
  477. package/lib/webrtc/stats/groupCallStats.d.ts +0 -22
  478. package/lib/webrtc/stats/groupCallStats.d.ts.map +0 -1
  479. package/lib/webrtc/stats/groupCallStats.js +0 -78
  480. package/lib/webrtc/stats/groupCallStats.js.map +0 -1
  481. package/lib/webrtc/stats/media/mediaSsrcHandler.d.ts +0 -10
  482. package/lib/webrtc/stats/media/mediaSsrcHandler.d.ts.map +0 -1
  483. package/lib/webrtc/stats/media/mediaSsrcHandler.js +0 -57
  484. package/lib/webrtc/stats/media/mediaSsrcHandler.js.map +0 -1
  485. package/lib/webrtc/stats/media/mediaTrackHandler.d.ts +0 -12
  486. package/lib/webrtc/stats/media/mediaTrackHandler.d.ts.map +0 -1
  487. package/lib/webrtc/stats/media/mediaTrackHandler.js +0 -62
  488. package/lib/webrtc/stats/media/mediaTrackHandler.js.map +0 -1
  489. package/lib/webrtc/stats/media/mediaTrackStats.d.ts +0 -86
  490. package/lib/webrtc/stats/media/mediaTrackStats.d.ts.map +0 -1
  491. package/lib/webrtc/stats/media/mediaTrackStats.js +0 -142
  492. package/lib/webrtc/stats/media/mediaTrackStats.js.map +0 -1
  493. package/lib/webrtc/stats/media/mediaTrackStatsHandler.d.ts +0 -22
  494. package/lib/webrtc/stats/media/mediaTrackStatsHandler.d.ts.map +0 -1
  495. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +0 -76
  496. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +0 -1
  497. package/lib/webrtc/stats/statsReport.d.ts +0 -99
  498. package/lib/webrtc/stats/statsReport.d.ts.map +0 -1
  499. package/lib/webrtc/stats/statsReport.js +0 -32
  500. package/lib/webrtc/stats/statsReport.js.map +0 -1
  501. package/lib/webrtc/stats/statsReportEmitter.d.ts +0 -15
  502. package/lib/webrtc/stats/statsReportEmitter.d.ts.map +0 -1
  503. package/lib/webrtc/stats/statsReportEmitter.js +0 -33
  504. package/lib/webrtc/stats/statsReportEmitter.js.map +0 -1
  505. package/lib/webrtc/stats/summaryStatsReportGatherer.d.ts +0 -16
  506. package/lib/webrtc/stats/summaryStatsReportGatherer.d.ts.map +0 -1
  507. package/lib/webrtc/stats/summaryStatsReportGatherer.js +0 -116
  508. package/lib/webrtc/stats/summaryStatsReportGatherer.js.map +0 -1
  509. package/lib/webrtc/stats/trackStatsBuilder.d.ts +0 -19
  510. package/lib/webrtc/stats/trackStatsBuilder.d.ts.map +0 -1
  511. package/lib/webrtc/stats/trackStatsBuilder.js +0 -168
  512. package/lib/webrtc/stats/trackStatsBuilder.js.map +0 -1
  513. package/lib/webrtc/stats/transportStats.d.ts +0 -11
  514. package/lib/webrtc/stats/transportStats.d.ts.map +0 -1
  515. package/lib/webrtc/stats/transportStats.js +0 -1
  516. package/lib/webrtc/stats/transportStats.js.map +0 -1
  517. package/lib/webrtc/stats/transportStatsBuilder.d.ts +0 -5
  518. package/lib/webrtc/stats/transportStatsBuilder.d.ts.map +0 -1
  519. package/lib/webrtc/stats/transportStatsBuilder.js +0 -34
  520. package/lib/webrtc/stats/transportStatsBuilder.js.map +0 -1
  521. package/lib/webrtc/stats/valueFormatter.d.ts +0 -4
  522. package/lib/webrtc/stats/valueFormatter.d.ts.map +0 -1
  523. package/lib/webrtc/stats/valueFormatter.js +0 -25
  524. package/lib/webrtc/stats/valueFormatter.js.map +0 -1
  525. package/src/@types/crypto.ts +0 -73
  526. package/src/@types/matrix-sdk-crypto-wasm.d.ts +0 -44
  527. package/src/common-crypto/CryptoBackend.ts +0 -302
  528. package/src/common-crypto/README.md +0 -4
  529. package/src/common-crypto/key-passphrase.ts +0 -43
  530. package/src/crypto/CrossSigning.ts +0 -773
  531. package/src/crypto/DeviceList.ts +0 -989
  532. package/src/crypto/EncryptionSetup.ts +0 -351
  533. package/src/crypto/OlmDevice.ts +0 -1500
  534. package/src/crypto/OutgoingRoomKeyRequestManager.ts +0 -485
  535. package/src/crypto/RoomList.ts +0 -70
  536. package/src/crypto/SecretSharing.ts +0 -240
  537. package/src/crypto/SecretStorage.ts +0 -136
  538. package/src/crypto/aes.ts +0 -23
  539. package/src/crypto/algorithms/base.ts +0 -236
  540. package/src/crypto/algorithms/index.ts +0 -20
  541. package/src/crypto/algorithms/megolm.ts +0 -2216
  542. package/src/crypto/algorithms/olm.ts +0 -381
  543. package/src/crypto/api.ts +0 -70
  544. package/src/crypto/backup.ts +0 -922
  545. package/src/crypto/crypto.ts +0 -18
  546. package/src/crypto/dehydration.ts +0 -272
  547. package/src/crypto/device-converter.ts +0 -45
  548. package/src/crypto/deviceinfo.ts +0 -158
  549. package/src/crypto/index.ts +0 -4414
  550. package/src/crypto/key_passphrase.ts +0 -42
  551. package/src/crypto/keybackup.ts +0 -47
  552. package/src/crypto/olmlib.ts +0 -539
  553. package/src/crypto/recoverykey.ts +0 -18
  554. package/src/crypto/store/base.ts +0 -348
  555. package/src/crypto/store/indexeddb-crypto-store-backend.ts +0 -1250
  556. package/src/crypto/store/indexeddb-crypto-store.ts +0 -845
  557. package/src/crypto/store/localStorage-crypto-store.ts +0 -579
  558. package/src/crypto/store/memory-crypto-store.ts +0 -680
  559. package/src/crypto/verification/Base.ts +0 -409
  560. package/src/crypto/verification/Error.ts +0 -76
  561. package/src/crypto/verification/IllegalMethod.ts +0 -50
  562. package/src/crypto/verification/QRCode.ts +0 -310
  563. package/src/crypto/verification/SAS.ts +0 -494
  564. package/src/crypto/verification/SASDecimal.ts +0 -37
  565. package/src/crypto/verification/request/Channel.ts +0 -34
  566. package/src/crypto/verification/request/InRoomChannel.ts +0 -371
  567. package/src/crypto/verification/request/ToDeviceChannel.ts +0 -354
  568. package/src/crypto/verification/request/VerificationRequest.ts +0 -976
  569. package/src/crypto-api/CryptoEvent.ts +0 -93
  570. package/src/crypto-api/CryptoEventHandlerMap.ts +0 -32
  571. package/src/crypto-api/index.ts +0 -1175
  572. package/src/crypto-api/key-passphrase.ts +0 -58
  573. package/src/crypto-api/keybackup.ts +0 -115
  574. package/src/crypto-api/recovery-key.ts +0 -69
  575. package/src/crypto-api/verification.ts +0 -408
  576. package/src/matrixrtc/CallMembership.ts +0 -247
  577. package/src/matrixrtc/LivekitFocus.ts +0 -39
  578. package/src/matrixrtc/MatrixRTCSession.ts +0 -1319
  579. package/src/matrixrtc/MatrixRTCSessionManager.ts +0 -166
  580. package/src/matrixrtc/focus.ts +0 -25
  581. package/src/matrixrtc/index.ts +0 -22
  582. package/src/matrixrtc/types.ts +0 -36
  583. package/src/rendezvous/MSC4108SignInWithQR.ts +0 -444
  584. package/src/rendezvous/RendezvousChannel.ts +0 -48
  585. package/src/rendezvous/RendezvousCode.ts +0 -25
  586. package/src/rendezvous/RendezvousError.ts +0 -26
  587. package/src/rendezvous/RendezvousFailureReason.ts +0 -49
  588. package/src/rendezvous/RendezvousIntent.ts +0 -20
  589. package/src/rendezvous/RendezvousTransport.ts +0 -58
  590. package/src/rendezvous/channels/MSC4108SecureChannel.ts +0 -270
  591. package/src/rendezvous/channels/index.ts +0 -17
  592. package/src/rendezvous/index.ts +0 -25
  593. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +0 -270
  594. package/src/rendezvous/transports/index.ts +0 -17
  595. package/src/rust-crypto/CrossSigningIdentity.ts +0 -183
  596. package/src/rust-crypto/DehydratedDeviceManager.ts +0 -306
  597. package/src/rust-crypto/KeyClaimManager.ts +0 -86
  598. package/src/rust-crypto/OutgoingRequestProcessor.ts +0 -236
  599. package/src/rust-crypto/OutgoingRequestsManager.ts +0 -143
  600. package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +0 -501
  601. package/src/rust-crypto/RoomEncryptor.ts +0 -352
  602. package/src/rust-crypto/backup.ts +0 -881
  603. package/src/rust-crypto/constants.ts +0 -18
  604. package/src/rust-crypto/device-converter.ts +0 -128
  605. package/src/rust-crypto/index.ts +0 -237
  606. package/src/rust-crypto/libolm_migration.ts +0 -530
  607. package/src/rust-crypto/rust-crypto.ts +0 -2205
  608. package/src/rust-crypto/secret-storage.ts +0 -60
  609. package/src/rust-crypto/verification.ts +0 -830
  610. package/src/secret-storage.ts +0 -693
  611. package/src/webrtc/audioContext.ts +0 -44
  612. package/src/webrtc/call.ts +0 -3074
  613. package/src/webrtc/callEventHandler.ts +0 -425
  614. package/src/webrtc/callEventTypes.ts +0 -93
  615. package/src/webrtc/callFeed.ts +0 -364
  616. package/src/webrtc/groupCall.ts +0 -1735
  617. package/src/webrtc/groupCallEventHandler.ts +0 -234
  618. package/src/webrtc/mediaHandler.ts +0 -484
  619. package/src/webrtc/stats/callFeedStatsReporter.ts +0 -94
  620. package/src/webrtc/stats/callStatsReportGatherer.ts +0 -219
  621. package/src/webrtc/stats/callStatsReportSummary.ts +0 -30
  622. package/src/webrtc/stats/connectionStats.ts +0 -47
  623. package/src/webrtc/stats/connectionStatsBuilder.ts +0 -28
  624. package/src/webrtc/stats/connectionStatsReportBuilder.ts +0 -140
  625. package/src/webrtc/stats/groupCallStats.ts +0 -93
  626. package/src/webrtc/stats/media/mediaSsrcHandler.ts +0 -57
  627. package/src/webrtc/stats/media/mediaTrackHandler.ts +0 -76
  628. package/src/webrtc/stats/media/mediaTrackStats.ts +0 -176
  629. package/src/webrtc/stats/media/mediaTrackStatsHandler.ts +0 -90
  630. package/src/webrtc/stats/statsReport.ts +0 -133
  631. package/src/webrtc/stats/statsReportEmitter.ts +0 -49
  632. package/src/webrtc/stats/summaryStatsReportGatherer.ts +0 -148
  633. package/src/webrtc/stats/trackStatsBuilder.ts +0 -207
  634. package/src/webrtc/stats/transportStats.ts +0 -26
  635. package/src/webrtc/stats/transportStatsBuilder.ts +0 -48
  636. package/src/webrtc/stats/valueFormatter.ts +0 -27
@@ -1 +1 @@
1
- {"version":3,"file":"room.js","names":["M_POLL_START","EventTimelineSet","DuplicateStrategy","Direction","EventTimeline","getHttpUriForMxc","removeElement","normalize","noUnsafeEventProps","MatrixEvent","MatrixEventEvent","EventStatus","RoomMember","RoomSummary","logger","TypedReEmitter","EventType","RoomCreateTypeField","RoomType","UNSTABLE_ELEMENT_FUNCTIONAL_USERS","EVENT_VISIBILITY_CHANGE_TYPE","RelationType","UNSIGNED_THREAD_ID_FIELD","PendingEventOrdering","Filter","RoomStateEvent","BeaconEvent","Thread","ThreadEvent","FILTER_RELATED_BY_REL_TYPES","THREAD_RELATION_TYPE","FILTER_RELATED_BY_SENDERS","ThreadFilterType","MAIN_ROOM_TIMELINE","ReceiptType","RelationsContainer","ReadReceipt","synthesizeReceipt","isPollEvent","Poll","PollEvent","RoomReceipts","compareEventOrdering","utils","KnownMembership","RoomVersionStability","KNOWN_SAFE_ROOM_VERSION","SAFE_ROOM_VERSIONS","MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH","NotificationCountType","RoomEvent","Room","constructor","roomId","client","myUserId","_this","opts","arguments","length","undefined","this","_defineProperty","Map","Infinity","thread","toStartOfTimeline","recreateEvent","_this$threadsTimeline","updateThreadRootEvent","threadsTimelineSets","hasCurrentUserParticipated","_this$threadsTimeline2","timelineSet","rootEvent","removeEvent","id","hasServerSideSupport","addLiveEvent","duplicateStrategy","Replace","fromCache","roomState","currentState","addEventToTimeline","getLiveTimeline","event","isRedaction","redactId","redacts","redactedEvent","findEventById","threadRootId","makeRedacted","isState","currentStateEvent","getStateEvents","getType","getStateKey","getId","setStateEvents","emit","Redaction","visibilityEvents","delete","isVisibilityEvent","redactVisibilityChangeEvent","setMaxListeners","reEmitter","pendingEventOrdering","Chronological","name","normalizedName","relations","on","Receipt","onReceipt","timelineSets","reEmit","getUnfilteredTimelineSet","Timeline","TimelineReset","fixUpLegacyTimelineFields","Detached","pendingEventList","store","getPendingEvents","then","events","mapper","getEventMapper","toDevice","decrypt","forEach","_ref","_asyncToGenerator","serializedEvent","decryptEventIfNeeded","setStatus","NOT_SENT","addPendingEvent","getTxnId","_x","apply","lazyLoadMembers","membersPromise","Promise","resolve","createThreadsTimelineSets","_this2","_this2$client","threadTimelineSetsPromise","supportsThreads","all","createThreadTimelineSet","My","_unused","decryptCriticalEvents","_this3","isCryptoEnabled","readReceiptEventId","getEventReadUpTo","getUserId","getEvents","readReceiptTimelineIndex","findIndex","matrixEvent","event_id","decryptionPromises","slice","reverse","map","allSettled","decryptAllEvents","_this4","getCreator","_createEvent$getSende","createEvent","RoomCreate","getSender","getVersion","_createEvent$getConte","getVersionWarning","warn","getContent","getRecommendedVersion","_this5","capabilities","getCapabilities","_unused2","versionCap","default","available","safeVer","Stable","result","checkVersionAgainstCapability","urgent","needsUpgrade","fetchCapabilities","e","currentVersion","log","concat","version","stableVersions","Object","keys","filter","v","includes","match","userMayUpgradeRoom","userId","maySendStateEvent","RoomTombstone","Error","removePendingEvent","eventId","removed","ev","savePendingEvents","hasPendingEvent","_this$pendingEventLis","_this$pendingEventLis2","some","getPendingEvent","_this$pendingEventLis3","_this$pendingEventLis4","find","timeline","getLastActiveTimestamp","lastEvent","getTs","Number","MIN_SAFE_INTEGER","getLastLiveEvent","_lastRoomEvent$getTs","_lastThreadEvent$getT","roomEvents","lastRoomEvent","lastThread","getLastThread","lastThreadEvent","getThreads","reduce","_threadEvent$getTs","_lastThreadEvent$getT2","threadEvent","getMyMembership","_this$selfMembership","selfMembership","Leave","getDMInviter","me","getMember","Invite","memberCount","getInvitedAndJoinedMemberCount","_this$summaryHeroes","summaryHeroes","guessDMUserId","inviterId","Array","isArray","members","getMembers","anyMember","m","getFunctionalMembers","mFunctionalMembers","service_members","getAvatarFallbackMember","_this$summaryHeroes2","functionalMembers","nonFunctionalMemberCount","membership","nonFunctionalHeroes","h","hasHeroes","availableMember","member","nonFunctionalMembers","availableUser","getUser","user","updateMyMembership","prevMembership","cleanupAfterLeaving","MyMembership","loadMembersFromServer","_this6","lastSyncToken","getSyncToken","response","chunk","loadMembers","_this7","fromServer","rawMembersEvents","getOutOfBandMembers","hasEncryptionStateEvent","memberEvents","membersLoaded","outOfBandMembersReady","loadMembersIfNeeded","markOutOfBandMembersStarted","inMemoryUpdate","setOutOfBandMembers","catch","err","markOutOfBandMembersFailed","oobMembers","isOutOfBand","_m$events$member","error","clearLoadedMembersIfNeeded","_this8","clearOutOfBandMembers","refreshLiveTimeline","_this9","liveTimelineBefore","forwardPaginationToken","getPaginationToken","FORWARDS","backwardPaginationToken","BACKWARDS","eventsBefore","mostRecentEventInTimeline","toString","newTimeline","getLatestTimeline","resetLiveTimeline","TimelineRefresh","getEventTimeline","liveTimeline","Forward","Backward","setPaginationToken","setLiveTimeline","setTimelineNeedsRefresh","backPaginationToken","threads","values","previousOldState","oldState","previousCurrentState","getState","OldStateUpdated","CurrentStateUpdated","stopReEmitting","Events","Members","NewMember","Update","Marker","New","Destroy","LivenessChange","clearNotificationsOnReceipt","threadIds","hasUnthreadedReceipt","content","receiptGroup","receiptType","userReceipt","entries","isSupportedReceiptType","singleReceipt","typedSingleReceipt","thread_id","push","getThreadUnreadNotificationCount","Total","Highlight","threadId","_this$getThread","maxHistory","getThread","highlightCount","i","_pushActions$tweaks","hasUserReadEvent","pushActions","getPushActionsForEvent","tweaks","highlight","setUnreadNotificationCount","setThreadUnreadNotificationCount","getTimelineSets","getTimelineForEvent","findThreadForEvent","addTimeline","value","timelineNeedsRefresh","getTimelineNeedsRefresh","getUnreadNotificationCount","type","count","getRoomUnreadNotificationCount","threadNotification","threadNotifications","_threadNotification$t","getUnreadCountForEventContext","_ref2","isThreadEvent","isThreadRoot","_this$notificationCou","notificationCounts","_this$threadNotificat","_this$threadNotificat2","get","hasThreadUnreadNotification","notification","_notification$highlig","_notification$total","total","_this$threadNotificat3","_this$threadNotificat4","_objectSpread","set","UnreadNotifications","threadsAggregateNotificationType","_threadNotification$h","_threadNotification$t2","resetThreadUnreadNotificationCountFromSync","exceptThreadIds","isEncrypted","notifs","setUnread","setSummary","summary","heroes","joinedCount","invitedCount","isInteger","setJoinedMemberCount","setInvitedMemberCount","Summary","setBlacklistUnverifiedDevices","blacklistUnverifiedDevices","getBlacklistUnverifiedDevices","getAvatarUrl","baseUrl","width","height","resizeMethod","allowDefault","roomAvatarEvent","RoomAvatar","mainUrl","url","getMxcAvatarUrl","_this$currentState$ge","getCanonicalAlias","canonicalAlias","RoomCanonicalAlias","alias","getAltAliases","alt_aliases","addEventsToTimeline","paginationToken","getTimelineSet","_this$threads$get","from","getJoinedMembers","getMembersWithMembership","Join","getJoinedMemberCount","getInvitedMemberCount","getEncryptionTargetMembers","_this10","shouldEncryptForInvitedMembers","_ev$getContent","RoomHistoryVisibility","history_visibility","getDefaultRoomName","calculateRoomName","hasMembershipState","getOrCreateFilteredTimelineSet","prepopulateTimeline","useSyncEvents","pendingEvents","filteredTimelineSets","filterId","assign","unfilteredLiveTimeline","getNeighbouringTimeline","livePaginationToken","getThreadListFilter","_arguments","_this11","filterType","All","definition","room","setDefinition","getOrCreateFilter","_this12","hasServerSideListSupport","_ref3","currentUserParticipated","addEvent","processThreadRoots","setEventMetadata","createThread","fetchRoomThreads","_this13","threadsReady","fetchRoomThreadList","allThreadsFilter","createMessagesRequest","MAX_SAFE_INTEGER","threadRoots","sort","eventA","eventB","threadAMetadata","getServerAggregatedRelation","threadBMetadata","latest_event","origin_server_ts","latestMyThreadsRootEvent","_this13$threadsTimeli","Ignore","threadRelationship","current_user_participated","_this13$threadsTimeli2","NewReply","onThreadReply","onThreadUpdate","Delete","onThreadDelete","processPollEvents","_this14","processPollEvent","_this15","isDecryptionFailure","once","Decrypted","maybeDecryptedEvent","matches","poll","polls","BeforeRedaction","_unused3","relationEventId","has","onNewRelation","_this16","end","createThreadListMessagesRequest","threadListType","getFilter","matrixEvents","updateThreadRootEvents","_timeline$getEvents","roomEvent","it","clearEventMetadata","debug","removeFilteredTimelineSet","indexOf","splice","eventShouldLiveIn","roots","_this$client","shouldLiveInRoom","shouldLiveInThread","isThreadRelation","isRelation","parentEventId","getAssociatedId","parentEvent","_this$findEventById","replyEventId","addThreadedEvents","addEvents","_this$findEventById2","processThreadedEvents","applyRedaction","eventsByThread","_eventsByThread","_ref4","threadEvents","_this$cachedThreadRea","relatedEvents","getAllChildEventsForEvent","receipts","cachedThreadReadReceipts","initialEventsFetched","processLiveEvent","applyNewVisibilityEvent","applyPendingVisibilityEvents","txnId","getUnsigned","transaction_id","tid","localEvent","txnToEvent","unsigned","setUnsigned","addLiveEventOptions","timelineWasEmpty","sender","RoomRedaction","addReceipt","Read","status","SENDING","aggregateNonLiveRelation","markLocallyRedacted","filterRoomTimeline","LocalEchoUpdated","txn_id","isEventEncrypted","RoomMessageEncrypted","isRoomEncrypted","setPendingEvents","aggregateChildEvent","getEventForTxnId","handleRemoteEcho","remoteEvent","oldEventId","newEventId","oldStatus","updatePendingEvent","newStatus","getRoomId","SENT","remoteTxnId","allowed","ALLOWED_TRANSITIONS","replaceLocalEventId","replaceEventId","CANCELLED","removedEvent","revertRedactionLocalEcho","redactionEvent","unmarkLocallyRedacted","RedactionCancelled","assertTimelineSetsAreLive","addLiveEvents","_this17","findThreadRoots","options","neighbouringEvents","_eventsByThread$threa","existingEvent","fetchRoomEvent","add","_ref5","partitionThreadedEvents","ROOM","THREAD","UNKNOWN_RELATION","memo","setThreadId","Set","synthetic","roomReceipts","_receipt$thread_id","_this$unthreadedRecei","_this$unthreadedRecei2","receipt","receiptForMainTimeline","receiptDestination","addReceiptToStructure","isInitialSyncComplete","_this$cachedThreadRea2","ts","oldestThreadedReceiptTs","unthreadedReceipts","addEphemeralEvents","Typing","setTypingEvent","removeEvents","eventIds","removedAny","recalculate","membershipEvent","strippedStateEvents","invite_room_state","strippedEvent","state_key","Date","now","room_id","oldName","title","Name","addTags","tags","Tags","addAccountData","eventType","accountData","AccountData","getAccountData","maySendMessage","maySendEvent","RoomMessage","canInvite","powerLevelsEvent","RoomPowerLevels","powerLevels","invite","powerLevel","getJoinRule","getHistoryVisibility","getGuestAccess","getTypeWarning","isSpaceRoom","Space","isCallRoom","UnstableCall","isElementVideoRoom","ElementVideo","findPredecessor","msc3946ProcessDynamicPredecessor","roomNameGenerator","state","RoomNameType","Actual","Generated","subtype","memberNamesToRoomName","names","EmptyRoom","ignoreRoomNameEvent","mRoomName","RoomName","joinedMemberCount","invitedMemberCount","inviteJoinCount","excludedUserIds","otherNames","otherMembers","_ref6","collator","Intl","Collator","a","b","compare","myMembership","thirdPartyInvites","RoomThirdPartyInvite","thirdPartyNames","display_name","leftNames","visibilityChange","asVisibilityChange","isPowerSufficient","altName","visibilityEventsOnOriginalEvent","index","min","Math","max","target","unshift","originalEvent","applyVisibilityEvent","relation","getRelation","originalEventId","change","newEvent","newVisibility","visibilityEvent","visible","getOldestThreadedReceiptTs","getLastUnthreadedReceiptFor","fixupNotifications","unreadThreads","leftEventId","rightEventId","_this$getLiveTimeline","Boolean","RoomEncryption","ENCRYPTING","QUEUED","countWithoutMe","plural"],"sources":["../../src/models/room.ts"],"sourcesContent":["/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { M_POLL_START, Optional } from \"matrix-events-sdk\";\n\nimport {\n EventTimelineSet,\n DuplicateStrategy,\n IAddLiveEventOptions,\n EventTimelineSetHandlerMap,\n} from \"./event-timeline-set.ts\";\nimport { Direction, EventTimeline } from \"./event-timeline.ts\";\nimport { getHttpUriForMxc } from \"../content-repo.ts\";\nimport { removeElement } from \"../utils.ts\";\nimport { normalize, noUnsafeEventProps } from \"../utils.ts\";\nimport { IEvent, IThreadBundledRelationship, MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from \"./event.ts\";\nimport { EventStatus } from \"./event-status.ts\";\nimport { RoomMember } from \"./room-member.ts\";\nimport { IRoomSummary, RoomSummary } from \"./room-summary.ts\";\nimport { logger } from \"../logger.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport {\n EventType,\n RoomCreateTypeField,\n RoomType,\n UNSTABLE_ELEMENT_FUNCTIONAL_USERS,\n EVENT_VISIBILITY_CHANGE_TYPE,\n RelationType,\n UNSIGNED_THREAD_ID_FIELD,\n} from \"../@types/event.ts\";\nimport { MatrixClient, PendingEventOrdering } from \"../client.ts\";\nimport { GuestAccess, HistoryVisibility, JoinRule, ResizeMethod } from \"../@types/partials.ts\";\nimport { Filter, IFilterDefinition } from \"../filter.ts\";\nimport { RoomState, RoomStateEvent, RoomStateEventHandlerMap } from \"./room-state.ts\";\nimport { BeaconEvent, BeaconEventHandlerMap } from \"./beacon.ts\";\nimport {\n Thread,\n ThreadEvent,\n ThreadEventHandlerMap as ThreadHandlerMap,\n FILTER_RELATED_BY_REL_TYPES,\n THREAD_RELATION_TYPE,\n FILTER_RELATED_BY_SENDERS,\n ThreadFilterType,\n} from \"./thread.ts\";\nimport {\n CachedReceiptStructure,\n MAIN_ROOM_TIMELINE,\n Receipt,\n ReceiptContent,\n ReceiptType,\n} from \"../@types/read_receipts.ts\";\nimport { IStateEventWithRoomId } from \"../@types/search.ts\";\nimport { RelationsContainer } from \"./relations-container.ts\";\nimport { ReadReceipt, synthesizeReceipt } from \"./read-receipt.ts\";\nimport { isPollEvent, Poll, PollEvent } from \"./poll.ts\";\nimport { RoomReceipts } from \"./room-receipts.ts\";\nimport { compareEventOrdering } from \"./compare-event-ordering.ts\";\nimport * as utils from \"../utils.ts\";\nimport { KnownMembership, Membership } from \"../@types/membership.ts\";\nimport { Capabilities, IRoomVersionsCapability, RoomVersionStability } from \"../serverCapabilities.ts\";\n\n// These constants are used as sane defaults when the homeserver doesn't support\n// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be\n// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the\n// room versions which are considered okay for people to run without being asked\n// to upgrade (ie: \"stable\"). Eventually, we should remove these when all homeservers\n// return an m.room_versions capability.\nexport const KNOWN_SAFE_ROOM_VERSION = \"10\";\nconst SAFE_ROOM_VERSIONS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"];\n\ninterface IOpts {\n /**\n * Controls where pending messages appear in a room's timeline.\n * If \"<b>chronological</b>\", messages will appear in the timeline when the call to `sendEvent` was made.\n * If \"<b>detached</b>\", pending messages will appear in a separate list,\n * accessible via {@link Room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n /**\n * Set to true to enable improved timeline support.\n */\n timelineSupport?: boolean;\n lazyLoadMembers?: boolean;\n}\n\nexport interface IRecommendedVersion {\n version: string;\n needsUpgrade: boolean;\n urgent: boolean;\n}\n\n// When inserting a visibility event affecting event `eventId`, we\n// need to scan through existing visibility events for `eventId`.\n// In theory, this could take an unlimited amount of time if:\n//\n// - the visibility event was sent by a moderator; and\n// - `eventId` already has many visibility changes (usually, it should\n// be 2 or less); and\n// - for some reason, the visibility changes are received out of order\n// (usually, this shouldn't happen at all).\n//\n// For this reason, we limit the number of events to scan through,\n// expecting that a broken visibility change for a single event in\n// an extremely uncommon case (possibly a DoS) is a small\n// price to pay to keep matrix-js-sdk responsive.\nconst MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30;\n\nexport type NotificationCount = Partial<Record<NotificationCountType, number>>;\n\nexport enum NotificationCountType {\n Highlight = \"highlight\",\n Total = \"total\",\n}\n\nexport interface ICreateFilterOpts {\n // Populate the filtered timeline with already loaded events in the room\n // timeline. Useful to disable for some filters that can't be achieved by the\n // client in an efficient manner\n prepopulateTimeline?: boolean;\n useSyncEvents?: boolean;\n pendingEvents?: boolean;\n}\n\nexport enum RoomEvent {\n MyMembership = \"Room.myMembership\",\n Tags = \"Room.tags\",\n AccountData = \"Room.accountData\",\n Receipt = \"Room.receipt\",\n Name = \"Room.name\",\n Redaction = \"Room.redaction\",\n RedactionCancelled = \"Room.redactionCancelled\",\n LocalEchoUpdated = \"Room.localEchoUpdated\",\n Timeline = \"Room.timeline\",\n TimelineReset = \"Room.timelineReset\",\n TimelineRefresh = \"Room.TimelineRefresh\",\n OldStateUpdated = \"Room.OldStateUpdated\",\n CurrentStateUpdated = \"Room.CurrentStateUpdated\",\n HistoryImportedWithinTimeline = \"Room.historyImportedWithinTimeline\",\n UnreadNotifications = \"Room.UnreadNotifications\",\n Summary = \"Room.Summary\",\n}\n\nexport type RoomEmittedEvents =\n | RoomEvent\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker\n | ThreadEvent.New\n | ThreadEvent.Update\n | ThreadEvent.NewReply\n | ThreadEvent.Delete\n | MatrixEventEvent.BeforeRedaction\n | BeaconEvent.New\n | BeaconEvent.Update\n | BeaconEvent.Destroy\n | BeaconEvent.LivenessChange\n | PollEvent.New;\n\nexport type RoomEventHandlerMap = {\n /**\n * Fires when the logged in user's membership in the room is updated.\n *\n * @param room - The room in which the membership has been updated\n * @param membership - The new membership value\n * @param prevMembership - The previous membership value\n */\n [RoomEvent.MyMembership]: (room: Room, membership: Membership, prevMembership?: Membership) => void;\n /**\n * Fires whenever a room's tags are updated.\n * @param event - The tags event\n * @param room - The room whose Room.tags was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.tags\", function(event, room){\n * var newTags = event.getContent().tags;\n * if (newTags[\"favourite\"]) showStar(room);\n * });\n * ```\n */\n [RoomEvent.Tags]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires whenever a room's account_data is updated.\n * @param event - The account_data event\n * @param room - The room whose account_data was updated.\n * @param prevEvent - The event being replaced by\n * the new account data, if known.\n * @example\n * ```\n * matrixClient.on(\"Room.accountData\", function(event, room, oldEvent){\n * if (event.getType() === \"m.room.colorscheme\") {\n * applyColorScheme(event.getContents());\n * }\n * });\n * ```\n */\n [RoomEvent.AccountData]: (event: MatrixEvent, room: Room, prevEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a receipt is received for a room\n * @param event - The receipt event\n * @param room - The room whose receipts was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.receipt\", function(event, room){\n * var receiptContent = event.getContent();\n * });\n * ```\n */\n [RoomEvent.Receipt]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires whenever the name of a room is updated.\n * @param room - The room whose Room.name was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.name\", function(room){\n * var newName = room.name;\n * });\n * ```\n */\n [RoomEvent.Name]: (room: Room) => void;\n /**\n * Fires when an event we had previously received is redacted.\n *\n * (Note this is *not* fired when the redaction happens before we receive the\n * event).\n *\n * @param event - The matrix redaction event\n * @param room - The room containing the redacted event\n * @param threadId - The thread containing the redacted event (before it was redacted)\n */\n [RoomEvent.Redaction]: (event: MatrixEvent, room: Room, threadId?: string) => void;\n /**\n * Fires when an event that was previously redacted isn't anymore.\n * This happens when the redaction couldn't be sent and\n * was subsequently cancelled by the user. Redactions have a local echo\n * which is undone in this scenario.\n *\n * @param event - The matrix redaction event that was cancelled.\n * @param room - The room containing the unredacted event\n */\n [RoomEvent.RedactionCancelled]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires when the status of a transmitted event is updated.\n *\n * <p>When an event is first transmitted, a temporary copy of the event is\n * inserted into the timeline, with a temporary event id, and a status of\n * 'SENDING'.\n *\n * <p>Once the echo comes back from the server, the content of the event\n * (MatrixEvent.event) is replaced by the complete event from the homeserver,\n * thus updating its event id, as well as server-generated fields such as the\n * timestamp. Its status is set to null.\n *\n * <p>Once the /send request completes, if the remote echo has not already\n * arrived, the event is updated with a new event id and the status is set to\n * 'SENT'. The server-generated fields are of course not updated yet.\n *\n * <p>If the /send fails, In this case, the event's status is set to\n * 'NOT_SENT'. If it is later resent, the process starts again, setting the\n * status to 'SENDING'. Alternatively, the message may be cancelled, which\n * removes the event from the room, and sets the status to 'CANCELLED'.\n *\n * <p>This event is raised to reflect each of the transitions above.\n *\n * @param event - The matrix event which has been updated\n *\n * @param room - The room containing the redacted event\n *\n * @param oldEventId - The previous event id (the temporary event id,\n * except when updating a successfully-sent event when its echo arrives)\n *\n * @param oldStatus - The previous event status.\n */\n [RoomEvent.LocalEchoUpdated]: (\n event: MatrixEvent,\n room: Room,\n oldEventId?: string,\n oldStatus?: EventStatus | null,\n ) => void;\n [RoomEvent.OldStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;\n [RoomEvent.CurrentStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;\n [RoomEvent.HistoryImportedWithinTimeline]: (markerEvent: MatrixEvent, room: Room) => void;\n [RoomEvent.UnreadNotifications]: (unreadNotifications?: NotificationCount, threadId?: string) => void;\n [RoomEvent.TimelineRefresh]: (room: Room, eventTimelineSet: EventTimelineSet) => void;\n /**\n * Fires when a new room summary is returned by `/sync`.\n *\n * See https://spec.matrix.org/v1.8/client-server-api/#_matrixclientv3sync_roomsummary\n * for full details\n * @param summary - the room summary object\n */\n [RoomEvent.Summary]: (summary: IRoomSummary) => void;\n [ThreadEvent.New]: (thread: Thread, toStartOfTimeline: boolean) => void;\n /**\n * Fires when a new poll instance is added to the room state\n * @param poll - the new poll\n */\n [PollEvent.New]: (poll: Poll) => void;\n} & Pick<ThreadHandlerMap, ThreadEvent.Update | ThreadEvent.NewReply | ThreadEvent.Delete> &\n EventTimelineSetHandlerMap &\n Pick<MatrixEventHandlerMap, MatrixEventEvent.BeforeRedaction> &\n Pick<\n RoomStateEventHandlerMap,\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker\n | BeaconEvent.New\n > &\n Pick<BeaconEventHandlerMap, BeaconEvent.Update | BeaconEvent.Destroy | BeaconEvent.LivenessChange>;\n\nexport class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {\n public readonly reEmitter: TypedReEmitter<RoomEmittedEvents, RoomEventHandlerMap>;\n private txnToEvent: Map<string, MatrixEvent> = new Map(); // Pending in-flight requests { string: MatrixEvent }\n private notificationCounts: NotificationCount = {};\n private readonly threadNotifications = new Map<string, NotificationCount>();\n public readonly cachedThreadReadReceipts = new Map<string, CachedReceiptStructure[]>();\n // Useful to know at what point the current user has started using threads in this room\n private oldestThreadedReceiptTs = Infinity;\n /**\n * A record of the latest unthread receipts per user\n * This is useful in determining whether a user has read a thread or not\n */\n private unthreadedReceipts = new Map<string, Receipt>();\n private readonly timelineSets: EventTimelineSet[];\n public readonly polls: Map<string, Poll> = new Map<string, Poll>();\n\n /**\n * Empty array if the timeline sets have not been initialised. After initialisation:\n * 0: All threads\n * 1: Threads the current user has participated in\n */\n public readonly threadsTimelineSets: [] | [EventTimelineSet, EventTimelineSet] = [];\n\n // any filtered timeline sets we're maintaining for this room\n private readonly filteredTimelineSets: Record<string, EventTimelineSet> = {}; // filter_id: timelineSet\n private timelineNeedsRefresh = false;\n private readonly pendingEventList?: MatrixEvent[];\n // read by megolm via getter; boolean value - null indicates \"use global value\"\n private blacklistUnverifiedDevices?: boolean;\n private selfMembership?: Membership;\n private summaryHeroes: string[] | null = null;\n // flags to stop logspam about missing m.room.create events\n private getTypeWarning = false;\n private getVersionWarning = false;\n private membersPromise?: Promise<boolean>;\n\n // XXX: These should be read-only\n /**\n * The human-readable display name for this room.\n */\n public name: string;\n /**\n * The un-homoglyphed name for this room.\n */\n public normalizedName: string;\n /**\n * Dict of room tags; the keys are the tag name and the values\n * are any metadata associated with the tag - e.g. `{ \"fav\" : { order: 1 } }`\n */\n public tags: Record<string, Record<string, any>> = {}; // $tagName: { $metadata: $value }\n /**\n * accountData Dict of per-room account_data events; the keys are the\n * event type and the values are the events.\n */\n public accountData: Map<string, MatrixEvent> = new Map(); // $eventType: $event\n /**\n * The room summary.\n */\n public summary: RoomSummary | null = null;\n /**\n * oldState The state of the room at the time of the oldest event in the live timeline.\n *\n * @deprecated Present for backwards compatibility.\n * Use getLiveTimeline().getState(EventTimeline.BACKWARDS) instead\n */\n public oldState!: RoomState;\n /**\n * currentState The state of the room at the time of the newest event in the timeline.\n *\n * @deprecated Present for backwards compatibility.\n * Use getLiveTimeline().getState(EventTimeline.FORWARDS) instead.\n */\n public currentState!: RoomState;\n\n public readonly relations;\n\n /**\n * A collection of events known by the client\n * This is not a comprehensive list of the threads that exist in this room\n */\n private threads = new Map<string, Thread>();\n\n /**\n * A mapping of eventId to all visibility changes to apply\n * to the event, by chronological order, as per\n * https://github.com/matrix-org/matrix-doc/pull/3531\n *\n * # Invariants\n *\n * - within each list, all events are classed by\n * chronological order;\n * - all events are events such that\n * `asVisibilityEvent()` returns a non-null `IVisibilityChange`;\n * - within each list with key `eventId`, all events\n * are in relation to `eventId`.\n *\n * @experimental\n */\n private visibilityEvents = new Map<string, MatrixEvent[]>();\n\n /**\n * The latest receipts (synthetic and real) for each user in each thread\n * (and unthreaded).\n */\n private roomReceipts = new RoomReceipts(this);\n\n /**\n * Construct a new Room.\n *\n * <p>For a room, we store an ordered sequence of timelines, which may or may not\n * be continuous. Each timeline lists a series of events, as well as tracking\n * the room state at the start and the end of the timeline. It also tracks\n * forward and backward pagination tokens, as well as containing links to the\n * next timeline in the sequence.\n *\n * <p>There is one special timeline - the 'live' timeline, which represents the\n * timeline to which events are being added in real-time as they are received\n * from the /sync API. Note that you should not retain references to this\n * timeline - even if it is the current timeline right now, it may not remain\n * so if the server gives us a timeline gap in /sync.\n *\n * <p>In order that we can find events from their ids later, we also maintain a\n * map from event_id to timeline and index.\n *\n * @param roomId - Required. The ID of this room.\n * @param client - Required. The client, used to lazy load members.\n * @param myUserId - Required. The ID of the syncing user.\n * @param opts - Configuration options\n */\n public constructor(\n public readonly roomId: string,\n public readonly client: MatrixClient,\n public readonly myUserId: string,\n private readonly opts: IOpts = {},\n ) {\n super();\n\n // In some cases, we add listeners for every displayed Matrix event, so it's\n // common to have quite a few more than the default limit.\n this.setMaxListeners(100);\n this.reEmitter = new TypedReEmitter(this);\n\n opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological;\n\n this.name = roomId;\n this.normalizedName = roomId;\n\n this.relations = new RelationsContainer(this.client, this);\n\n // Listen to our own receipt event as a more modular way of processing our own\n // receipts. No need to remove the listener: it's on ourself anyway.\n this.on(RoomEvent.Receipt, this.onReceipt);\n\n // all our per-room timeline sets. the first one is the unfiltered ones;\n // the subsequent ones are the filtered ones in no particular order.\n this.timelineSets = [new EventTimelineSet(this, opts)];\n this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n\n this.fixUpLegacyTimelineFields();\n\n if (this.opts.pendingEventOrdering === PendingEventOrdering.Detached) {\n this.pendingEventList = [];\n this.client.store.getPendingEvents(this.roomId).then((events) => {\n const mapper = this.client.getEventMapper({\n toDevice: false,\n decrypt: false,\n });\n events.forEach(async (serializedEvent: Partial<IEvent>) => {\n const event = mapper(serializedEvent);\n await client.decryptEventIfNeeded(event);\n event.setStatus(EventStatus.NOT_SENT);\n this.addPendingEvent(event, event.getTxnId()!);\n });\n });\n }\n\n // awaited by getEncryptionTargetMembers while room members are loading\n if (!this.opts.lazyLoadMembers) {\n this.membersPromise = Promise.resolve(false);\n } else {\n this.membersPromise = undefined;\n }\n }\n\n private threadTimelineSetsPromise: Promise<[EventTimelineSet, EventTimelineSet]> | null = null;\n public async createThreadsTimelineSets(): Promise<[EventTimelineSet, EventTimelineSet] | null> {\n if (this.threadTimelineSetsPromise) {\n return this.threadTimelineSetsPromise;\n }\n\n if (this.client?.supportsThreads()) {\n try {\n this.threadTimelineSetsPromise = Promise.all([\n this.createThreadTimelineSet(),\n this.createThreadTimelineSet(ThreadFilterType.My),\n ]);\n const timelineSets = await this.threadTimelineSetsPromise;\n this.threadsTimelineSets[0] = timelineSets[0];\n this.threadsTimelineSets[1] = timelineSets[1];\n return timelineSets;\n } catch {\n this.threadTimelineSetsPromise = null;\n return null;\n }\n }\n return null;\n }\n\n /**\n * Bulk decrypt critical events in a room\n *\n * Critical events represents the minimal set of events to decrypt\n * for a typical UI to function properly\n *\n * - Last event of every room (to generate likely message preview)\n * - All events up to the read receipt (to calculate an accurate notification count)\n *\n * @returns Signals when all events have been decrypted\n */\n public async decryptCriticalEvents(): Promise<void> {\n if (!this.client.isCryptoEnabled()) return;\n\n const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId()!, true);\n const events = this.getLiveTimeline().getEvents();\n const readReceiptTimelineIndex = events.findIndex((matrixEvent) => {\n return matrixEvent.event.event_id === readReceiptEventId;\n });\n\n const decryptionPromises = events\n .slice(readReceiptTimelineIndex)\n .reverse()\n .map((event) => this.client.decryptEventIfNeeded(event));\n\n await Promise.allSettled(decryptionPromises);\n }\n\n /**\n * Bulk decrypt events in a room\n *\n * @returns Signals when all events have been decrypted\n */\n public async decryptAllEvents(): Promise<void> {\n if (!this.client.isCryptoEnabled()) return;\n\n const decryptionPromises = this.getUnfilteredTimelineSet()\n .getLiveTimeline()\n .getEvents()\n .slice(0) // copy before reversing\n .reverse()\n .map((event) => this.client.decryptEventIfNeeded(event));\n\n await Promise.allSettled(decryptionPromises);\n }\n\n /**\n * Gets the creator of the room\n * @returns The creator of the room, or null if it could not be determined\n */\n public getCreator(): string | null {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n return createEvent?.getSender() ?? null;\n }\n\n /**\n * Gets the version of the room\n * @returns The version of the room, or null if it could not be determined\n */\n public getVersion(): string {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getVersionWarning) {\n logger.warn(\"[getVersion] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getVersionWarning = true;\n }\n return \"1\";\n }\n return createEvent.getContent()[\"room_version\"] ?? \"1\";\n }\n\n /**\n * Determines the recommended room version for the room. This returns an\n * object with 3 properties: `version` as the new version the\n * room should be upgraded to (may be the same as the current version);\n * `needsUpgrade` to indicate if the room actually can be\n * upgraded (ie: does the current version not match?); and `urgent`\n * to indicate if the new version patches a vulnerability in a previous\n * version.\n * @returns\n * Resolves to the version the room should be upgraded to.\n */\n public async getRecommendedVersion(): Promise<IRecommendedVersion> {\n let capabilities: Capabilities = {};\n try {\n capabilities = await this.client.getCapabilities();\n } catch {}\n let versionCap = capabilities[\"m.room_versions\"];\n if (!versionCap) {\n versionCap = {\n default: KNOWN_SAFE_ROOM_VERSION,\n available: {},\n };\n for (const safeVer of SAFE_ROOM_VERSIONS) {\n versionCap.available[safeVer] = RoomVersionStability.Stable;\n }\n }\n\n let result = this.checkVersionAgainstCapability(versionCap);\n if (result.urgent && result.needsUpgrade) {\n // Something doesn't feel right: we shouldn't need to update\n // because the version we're on should be in the protocol's\n // namespace. This usually means that the server was updated\n // before the client was, making us think the newest possible\n // room version is not stable. As a solution, we'll refresh\n // the capability we're using to determine this.\n logger.warn(\n \"Refreshing room version capability because the server looks \" +\n \"to be supporting a newer room version we don't know about.\",\n );\n\n try {\n capabilities = await this.client.fetchCapabilities();\n } catch (e) {\n logger.warn(\"Failed to refresh room version capabilities\", e);\n }\n versionCap = capabilities[\"m.room_versions\"];\n if (!versionCap) {\n logger.warn(\"No room version capability - assuming upgrade required.\");\n return result;\n } else {\n result = this.checkVersionAgainstCapability(versionCap);\n }\n }\n\n return result;\n }\n\n private checkVersionAgainstCapability(versionCap: IRoomVersionsCapability): IRecommendedVersion {\n const currentVersion = this.getVersion();\n logger.log(`[${this.roomId}] Current version: ${currentVersion}`);\n logger.log(`[${this.roomId}] Version capability: `, versionCap);\n\n const result: IRecommendedVersion = {\n version: currentVersion,\n needsUpgrade: false,\n urgent: false,\n };\n\n // If the room is on the default version then nothing needs to change\n if (currentVersion === versionCap.default) return result;\n\n const stableVersions = Object.keys(versionCap.available).filter((v) => versionCap.available[v] === \"stable\");\n\n // Check if the room is on an unstable version. We determine urgency based\n // off the version being in the Matrix spec namespace or not (if the version\n // is in the current namespace and unstable, the room is probably vulnerable).\n if (!stableVersions.includes(currentVersion)) {\n result.version = versionCap.default;\n result.needsUpgrade = true;\n result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);\n if (result.urgent) {\n logger.warn(`URGENT upgrade required on ${this.roomId}`);\n } else {\n logger.warn(`Non-urgent upgrade required on ${this.roomId}`);\n }\n return result;\n }\n\n // The room is on a stable, but non-default, version by this point.\n // No upgrade needed.\n return result;\n }\n\n /**\n * Determines whether the given user is permitted to perform a room upgrade\n * @param userId - The ID of the user to test against\n * @returns True if the given user is permitted to upgrade the room\n */\n public userMayUpgradeRoom(userId: string): boolean {\n return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);\n }\n\n /**\n * Get the list of pending sent events for this room\n *\n * @returns A list of the sent events\n * waiting for remote echo.\n *\n * @throws If `opts.pendingEventOrdering` was not 'detached'\n */\n public getPendingEvents(): MatrixEvent[] {\n if (!this.pendingEventList) {\n throw new Error(\n \"Cannot call getPendingEvents with pendingEventOrdering == \" + this.opts.pendingEventOrdering,\n );\n }\n\n return this.pendingEventList;\n }\n\n /**\n * Removes a pending event for this room\n *\n * @returns True if an element was removed.\n */\n public removePendingEvent(eventId: string): boolean {\n if (!this.pendingEventList) {\n throw new Error(\n \"Cannot call removePendingEvent with pendingEventOrdering == \" + this.opts.pendingEventOrdering,\n );\n }\n\n const removed = removeElement(\n this.pendingEventList,\n function (ev) {\n return ev.getId() == eventId;\n },\n false,\n );\n\n this.savePendingEvents();\n\n return removed;\n }\n\n /**\n * Check whether the pending event list contains a given event by ID.\n * If pending event ordering is not \"detached\" then this returns false.\n *\n * @param eventId - The event ID to check for.\n */\n public hasPendingEvent(eventId: string): boolean {\n return this.pendingEventList?.some((event) => event.getId() === eventId) ?? false;\n }\n\n /**\n * Get a specific event from the pending event list, if configured, null otherwise.\n *\n * @param eventId - The event ID to check for.\n */\n public getPendingEvent(eventId: string): MatrixEvent | null {\n return this.pendingEventList?.find((event) => event.getId() === eventId) ?? null;\n }\n\n /**\n * Get the live unfiltered timeline for this room.\n *\n * @returns live timeline\n */\n public getLiveTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().getLiveTimeline();\n }\n\n /**\n * The live event timeline for this room, with the oldest event at index 0.\n *\n * @deprecated Present for backwards compatibility.\n * Use getLiveTimeline().getEvents() instead\n */\n public get timeline(): MatrixEvent[] {\n return this.getLiveTimeline().getEvents();\n }\n\n /**\n * Get the timestamp of the last message in the room\n *\n * @returns the timestamp of the last message in the room\n */\n public getLastActiveTimestamp(): number {\n const timeline = this.getLiveTimeline();\n const events = timeline.getEvents();\n if (events.length) {\n const lastEvent = events[events.length - 1];\n return lastEvent.getTs();\n } else {\n return Number.MIN_SAFE_INTEGER;\n }\n }\n\n /**\n * Returns the last live event of this room.\n * \"last\" means latest timestamp.\n * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.\n * Unfortunately, this information is currently not available in the client.\n * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.\n * \"live of this room\" means from all live timelines: the room and the threads.\n *\n * @returns MatrixEvent if there is a last event; else undefined.\n */\n public getLastLiveEvent(): MatrixEvent | undefined {\n const roomEvents = this.getLiveTimeline().getEvents();\n const lastRoomEvent = roomEvents[roomEvents.length - 1] as MatrixEvent | undefined;\n const lastThread = this.getLastThread();\n\n if (!lastThread) return lastRoomEvent;\n\n const lastThreadEvent = lastThread.events[lastThread.events.length - 1];\n\n return (lastRoomEvent?.getTs() ?? 0) > (lastThreadEvent?.getTs() ?? 0) ? lastRoomEvent : lastThreadEvent;\n }\n\n /**\n * Returns the last thread of this room.\n * \"last\" means latest timestamp of the last thread event.\n * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.\n * Unfortunately, this information is currently not available in the client.\n * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.\n *\n * @returns the thread with the most recent event in its live time line. undefined if there is no thread.\n */\n public getLastThread(): Thread | undefined {\n return this.getThreads().reduce<Thread | undefined>((lastThread: Thread | undefined, thread: Thread) => {\n if (!lastThread) return thread;\n\n const threadEvent = thread.events[thread.events.length - 1];\n const lastThreadEvent = lastThread.events[lastThread.events.length - 1];\n\n if ((threadEvent?.getTs() ?? 0) >= (lastThreadEvent?.getTs() ?? 0)) {\n // Last message of current thread is newer → new last thread.\n // Equal also means newer, because it was added to the thread map later.\n return thread;\n }\n\n return lastThread;\n }, undefined);\n }\n\n /**\n * @returns the membership type (join | leave | invite | knock) for the logged in user\n */\n public getMyMembership(): Membership {\n return this.selfMembership ?? KnownMembership.Leave;\n }\n\n /**\n * If this room is a DM we're invited to,\n * try to find out who invited us\n * @returns user id of the inviter\n */\n public getDMInviter(): string | undefined {\n const me = this.getMember(this.myUserId);\n if (me) {\n return me.getDMInviter();\n }\n\n if (this.selfMembership === KnownMembership.Invite) {\n // fall back to summary information\n const memberCount = this.getInvitedAndJoinedMemberCount();\n if (memberCount === 2) {\n return this.summaryHeroes?.[0];\n }\n }\n }\n\n /**\n * Assuming this room is a DM room, tries to guess with which user.\n * @returns user id of the other member (could be syncing user)\n */\n public guessDMUserId(): string {\n const me = this.getMember(this.myUserId);\n if (me) {\n const inviterId = me.getDMInviter();\n if (inviterId) {\n return inviterId;\n }\n }\n // Remember, we're assuming this room is a DM, so returning the first member we find should be fine\n if (Array.isArray(this.summaryHeroes) && this.summaryHeroes.length) {\n return this.summaryHeroes[0];\n }\n const members = this.currentState.getMembers();\n const anyMember = members.find((m) => m.userId !== this.myUserId);\n if (anyMember) {\n return anyMember.userId;\n }\n // it really seems like I'm the only user in the room\n // so I probably created a room with just me in it\n // and marked it as a DM. Ok then\n return this.myUserId;\n }\n\n /**\n * Gets the \"functional members\" in this room.\n *\n * Returns the list of userIDs from the `io.element.functional_members` event. Does not consider the\n * current membership states of those users.\n *\n * @see https://github.com/element-hq/element-meta/blob/develop/spec/functional_members.md.\n */\n private getFunctionalMembers(): string[] {\n const mFunctionalMembers = this.currentState.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, \"\");\n if (Array.isArray(mFunctionalMembers?.getContent().service_members)) {\n return mFunctionalMembers!.getContent().service_members;\n }\n return [];\n }\n\n public getAvatarFallbackMember(): RoomMember | undefined {\n const functionalMembers = this.getFunctionalMembers();\n\n // Only generate a fallback avatar if the conversation is with a single specific other user (a \"DM\").\n let nonFunctionalMemberCount = 0;\n this.getMembers()!.forEach((m) => {\n if (m.membership !== \"join\" && m.membership !== \"invite\") return;\n if (functionalMembers.includes(m.userId)) return;\n nonFunctionalMemberCount++;\n });\n if (nonFunctionalMemberCount > 2) return;\n\n // Prefer the list of heroes, if present. It should only include the single other user in the DM.\n const nonFunctionalHeroes = this.summaryHeroes?.filter((h) => !functionalMembers.includes(h));\n const hasHeroes = Array.isArray(nonFunctionalHeroes) && nonFunctionalHeroes.length;\n if (hasHeroes) {\n const availableMember = nonFunctionalHeroes\n .map((userId) => {\n return this.getMember(userId);\n })\n .find((member) => !!member);\n if (availableMember) {\n return availableMember;\n }\n }\n\n // Consider *all*, including previous, members, to generate the avatar for DMs where the other user left.\n // Needed to generate a matching avatar for rooms named \"Empty Room (was Alice)\".\n const members = this.getMembers();\n const nonFunctionalMembers = members?.filter((m) => !functionalMembers.includes(m.userId));\n if (nonFunctionalMembers.length <= 2) {\n const availableMember = nonFunctionalMembers.find((m) => {\n return m.userId !== this.myUserId;\n });\n if (availableMember) {\n return availableMember;\n }\n }\n\n // If all else failed, but the homeserver gave us heroes that previously could not be found in the room members,\n // trust and try falling back to a hero, creating a one-off member for it\n if (hasHeroes) {\n const availableUser = nonFunctionalHeroes\n .map((userId) => {\n return this.client.getUser(userId);\n })\n .find((user) => !!user);\n if (availableUser) {\n const member = new RoomMember(this.roomId, availableUser.userId);\n member.user = availableUser;\n return member;\n }\n }\n }\n\n /**\n * Sets the membership this room was received as during sync\n * @param membership - join | leave | invite\n */\n public updateMyMembership(membership: Membership): void {\n const prevMembership = this.selfMembership;\n this.selfMembership = membership;\n if (prevMembership !== membership) {\n if (membership === KnownMembership.Leave) {\n this.cleanupAfterLeaving();\n }\n this.emit(RoomEvent.MyMembership, this, membership, prevMembership);\n }\n }\n\n private async loadMembersFromServer(): Promise<IStateEventWithRoomId[]> {\n const lastSyncToken = this.client.store.getSyncToken();\n const response = await this.client.members(\n this.roomId,\n undefined,\n KnownMembership.Leave,\n lastSyncToken ?? undefined,\n );\n return response.chunk;\n }\n\n private async loadMembers(): Promise<{ memberEvents: MatrixEvent[]; fromServer: boolean }> {\n // were the members loaded from the server?\n let fromServer = false;\n let rawMembersEvents = await this.client.store.getOutOfBandMembers(this.roomId);\n // If the room is encrypted, we always fetch members from the server at\n // least once, in case the latest state wasn't persisted properly. Note\n // that this function is only called once (unless loading the members\n // fails), since loadMembersIfNeeded always returns this.membersPromise\n // if set, which will be the result of the first (successful) call.\n if (rawMembersEvents === null || this.hasEncryptionStateEvent()) {\n fromServer = true;\n rawMembersEvents = await this.loadMembersFromServer();\n logger.log(`LL: got ${rawMembersEvents.length} ` + `members from server for room ${this.roomId}`);\n }\n const memberEvents = rawMembersEvents.filter(noUnsafeEventProps).map(this.client.getEventMapper());\n return { memberEvents, fromServer };\n }\n\n /**\n * Check if loading of out-of-band-members has completed\n *\n * @returns true if the full membership list of this room has been loaded (including if lazy-loading is disabled).\n * False if the load is not started or is in progress.\n */\n public membersLoaded(): boolean {\n if (!this.opts.lazyLoadMembers) {\n return true;\n }\n\n return this.currentState.outOfBandMembersReady();\n }\n\n /**\n * Preloads the member list in case lazy loading\n * of memberships is in use. Can be called multiple times,\n * it will only preload once.\n * @returns when preloading is done and\n * accessing the members on the room will take\n * all members in the room into account\n */\n public loadMembersIfNeeded(): Promise<boolean> {\n if (this.membersPromise) {\n return this.membersPromise;\n }\n\n // mark the state so that incoming messages while\n // the request is in flight get marked as superseding\n // the OOB members\n this.currentState.markOutOfBandMembersStarted();\n\n const inMemoryUpdate = this.loadMembers()\n .then((result) => {\n this.currentState.setOutOfBandMembers(result.memberEvents);\n return result.fromServer;\n })\n .catch((err) => {\n // allow retries on fail\n this.membersPromise = undefined;\n this.currentState.markOutOfBandMembersFailed();\n throw err;\n });\n // update members in storage, but don't wait for it\n inMemoryUpdate\n .then((fromServer) => {\n if (fromServer) {\n const oobMembers = this.currentState\n .getMembers()\n .filter((m) => m.isOutOfBand())\n .map((m) => m.events.member?.event as IStateEventWithRoomId);\n logger.log(`LL: telling store to write ${oobMembers.length}` + ` members for room ${this.roomId}`);\n const store = this.client.store;\n return (\n store\n .setOutOfBandMembers(this.roomId, oobMembers)\n // swallow any IDB error as we don't want to fail\n // because of this\n .catch((err) => {\n logger.log(\"LL: storing OOB room members failed, oh well\", err);\n })\n );\n }\n })\n .catch((err) => {\n // as this is not awaited anywhere,\n // at least show the error in the console\n logger.error(err);\n });\n\n this.membersPromise = inMemoryUpdate;\n\n return this.membersPromise;\n }\n\n /**\n * Removes the lazily loaded members from storage if needed\n */\n public async clearLoadedMembersIfNeeded(): Promise<void> {\n if (this.opts.lazyLoadMembers && this.membersPromise) {\n await this.loadMembersIfNeeded();\n await this.client.store.clearOutOfBandMembers(this.roomId);\n this.currentState.clearOutOfBandMembers();\n this.membersPromise = undefined;\n }\n }\n\n /**\n * called when sync receives this room in the leave section\n * to do cleanup after leaving a room. Possibly called multiple times.\n */\n private cleanupAfterLeaving(): void {\n this.clearLoadedMembersIfNeeded().catch((err) => {\n logger.error(`error after clearing loaded members from ` + `room ${this.roomId} after leaving`);\n logger.log(err);\n });\n }\n\n /**\n * Empty out the current live timeline and re-request it. This is used when\n * historical messages are imported into the room via MSC2716 `/batch_send`\n * because the client may already have that section of the timeline loaded.\n * We need to force the client to throw away their current timeline so that\n * when they back paginate over the area again with the historical messages\n * in between, it grabs the newly imported messages. We can listen for\n * `UNSTABLE_MSC2716_MARKER`, in order to tell when historical messages are ready\n * to be discovered in the room and the timeline needs a refresh. The SDK\n * emits a `RoomEvent.HistoryImportedWithinTimeline` event when we detect a\n * valid marker and can check the needs refresh status via\n * `room.getTimelineNeedsRefresh()`.\n */\n public async refreshLiveTimeline(): Promise<void> {\n const liveTimelineBefore = this.getLiveTimeline();\n const forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS);\n const backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS);\n const eventsBefore = liveTimelineBefore.getEvents();\n const mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];\n logger.log(\n `[refreshLiveTimeline for ${this.roomId}] at ` +\n `mostRecentEventInTimeline=${mostRecentEventInTimeline && mostRecentEventInTimeline.getId()} ` +\n `liveTimelineBefore=${liveTimelineBefore.toString()} ` +\n `forwardPaginationToken=${forwardPaginationToken} ` +\n `backwardPaginationToken=${backwardPaginationToken}`,\n );\n\n // Get the main TimelineSet\n const timelineSet = this.getUnfilteredTimelineSet();\n\n let newTimeline: Optional<EventTimeline>;\n // If there isn't any event in the timeline, let's go fetch the latest\n // event and construct a timeline from it.\n //\n // This should only really happen if the user ran into an error\n // with refreshing the timeline before which left them in a blank\n // timeline from `resetLiveTimeline`.\n if (!mostRecentEventInTimeline) {\n newTimeline = await this.client.getLatestTimeline(timelineSet);\n } else {\n // Empty out all of `this.timelineSets`. But we also need to keep the\n // same `timelineSet` references around so the React code updates\n // properly and doesn't ignore the room events we emit because it checks\n // that the `timelineSet` references are the same. We need the\n // `timelineSet` empty so that the `client.getEventTimeline(...)` call\n // later, will call `/context` and create a new timeline instead of\n // returning the same one.\n this.resetLiveTimeline(null, null);\n\n // Make the UI timeline show the new blank live timeline we just\n // reset so that if the network fails below it's showing the\n // accurate state of what we're working with instead of the\n // disconnected one in the TimelineWindow which is just hanging\n // around by reference.\n this.emit(RoomEvent.TimelineRefresh, this, timelineSet);\n\n // Use `client.getEventTimeline(...)` to construct a new timeline from a\n // `/context` response state and events for the most recent event before\n // we reset everything. The `timelineSet` we pass in needs to be empty\n // in order for this function to call `/context` and generate a new\n // timeline.\n newTimeline = await this.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId()!);\n }\n\n // If a racing `/sync` beat us to creating a new timeline, use that\n // instead because it's the latest in the room and any new messages in\n // the scrollback will include the history.\n const liveTimeline = timelineSet.getLiveTimeline();\n if (\n !liveTimeline ||\n (liveTimeline.getPaginationToken(Direction.Forward) === null &&\n liveTimeline.getPaginationToken(Direction.Backward) === null &&\n liveTimeline.getEvents().length === 0)\n ) {\n logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`);\n // Set the pagination token back to the live sync token (`null`) instead\n // of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`)\n // so that it matches the next response from `/sync` and we can properly\n // continue the timeline.\n newTimeline!.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);\n\n // Set our new fresh timeline as the live timeline to continue syncing\n // forwards and back paginating from.\n timelineSet.setLiveTimeline(newTimeline!);\n // Fixup `this.oldstate` so that `scrollback` has the pagination tokens\n // available\n this.fixUpLegacyTimelineFields();\n } else {\n logger.log(\n `[refreshLiveTimeline for ${this.roomId}] \\`/sync\\` or some other request beat us to creating a new ` +\n `live timeline after we reset it. We'll use that instead since any events in the scrollback from ` +\n `this timeline will include the history.`,\n );\n }\n\n // The timeline has now been refreshed ✅\n this.setTimelineNeedsRefresh(false);\n\n // Emit an event which clients can react to and re-load the timeline\n // from the SDK\n this.emit(RoomEvent.TimelineRefresh, this, timelineSet);\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n * <p>This is used when /sync returns a 'limited' timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public resetLiveTimeline(backPaginationToken?: string | null, forwardPaginationToken?: string | null): void {\n for (const timelineSet of this.timelineSets) {\n timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n }\n for (const thread of this.threads.values()) {\n thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken);\n }\n\n this.fixUpLegacyTimelineFields();\n }\n\n /**\n * Fix up this.timeline, this.oldState and this.currentState\n *\n * @internal\n */\n private fixUpLegacyTimelineFields(): void {\n const previousOldState = this.oldState;\n const previousCurrentState = this.currentState;\n\n // maintain this.oldState and this.currentState as references to the\n // state at the start and end of that timeline. These are more\n // for backwards-compatibility than anything else.\n this.oldState = this.getLiveTimeline().getState(EventTimeline.BACKWARDS)!;\n this.currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n\n // Let people know to register new listeners for the new state\n // references. The reference won't necessarily change every time so only\n // emit when we see a change.\n if (previousOldState !== this.oldState) {\n this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);\n }\n\n if (previousCurrentState !== this.currentState) {\n this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);\n\n // Re-emit various events on the current room state\n // TODO: If currentState really only exists for backwards\n // compatibility, shouldn't we be doing this some other way?\n this.reEmitter.stopReEmitting(previousCurrentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n RoomStateEvent.Marker,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n this.reEmitter.reEmit(this.currentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n RoomStateEvent.Marker,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n }\n }\n\n private onReceipt(event: MatrixEvent): void {\n if (this.hasEncryptionStateEvent()) {\n this.clearNotificationsOnReceipt(event);\n }\n }\n\n private clearNotificationsOnReceipt(event: MatrixEvent): void {\n // Like above, we have to listen for read receipts from ourselves in order to\n // correctly handle notification counts on encrypted rooms.\n // This fixes https://github.com/vector-im/element-web/issues/9421\n\n // Figure out if we've read something or if it's just informational\n // We need to work out what threads we've just recieved receipts for, so we\n // know which ones to update. If we've received an unthreaded receipt, we'll\n // need to update all threads.\n let threadIds: string[] = [];\n let hasUnthreadedReceipt = false;\n\n const content = event.getContent();\n\n for (const receiptGroup of Object.values(content)) {\n for (const [receiptType, userReceipt] of Object.entries(receiptGroup)) {\n if (!utils.isSupportedReceiptType(receiptType)) continue;\n if (!userReceipt) continue;\n\n for (const [userId, singleReceipt] of Object.entries(userReceipt)) {\n if (!singleReceipt || typeof singleReceipt !== \"object\") continue;\n const typedSingleReceipt = singleReceipt as Record<string, any>;\n if (userId !== this.client.getUserId()) continue;\n if (typedSingleReceipt.thread_id === undefined) {\n hasUnthreadedReceipt = true;\n } else if (typeof typedSingleReceipt.thread_id === \"string\") {\n threadIds.push(typedSingleReceipt.thread_id);\n }\n }\n }\n }\n\n if (hasUnthreadedReceipt) {\n // If we have an unthreaded receipt, we need to update any threads that have a notification\n // in them (because we know the receipt can't go backwards so we don't need to check any with\n // no notifications: the number can only decrease from a receipt).\n threadIds = this.getThreads()\n .filter(\n (thread) =>\n this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0 ||\n this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Highlight) > 0,\n )\n .map((thread) => thread.id);\n threadIds.push(\"main\");\n }\n\n for (const threadId of threadIds) {\n // Work backwards to determine how many events are unread. We also set\n // a limit for how back we'll look to avoid spinning CPU for too long.\n // If we hit the limit, we assume the count is unchanged.\n const maxHistory = 20;\n const timeline = threadId === \"main\" ? this.getLiveTimeline() : this.getThread(threadId)?.liveTimeline;\n\n if (!timeline) {\n logger.warn(`Couldn't find timeline for thread ID ${threadId} in room ${this.roomId}`);\n continue;\n }\n\n const events = timeline.getEvents();\n\n let highlightCount = 0;\n\n for (let i = events.length - 1; i >= 0; i--) {\n if (i === events.length - maxHistory) return; // limit reached\n\n const event = events[i];\n\n if (this.hasUserReadEvent(this.client.getUserId()!, event.getId()!)) {\n // If the user has read the event, then the counting is done.\n break;\n }\n\n const pushActions = this.client.getPushActionsForEvent(event);\n highlightCount += pushActions?.tweaks?.highlight ? 1 : 0;\n }\n\n // Note: we don't need to handle 'total' notifications because the counts\n // will come from the server.\n if (threadId === \"main\") {\n this.setUnreadNotificationCount(NotificationCountType.Highlight, highlightCount);\n } else {\n this.setThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight, highlightCount);\n }\n }\n }\n\n /**\n * Return the timeline sets for this room.\n * @returns array of timeline sets for this room\n */\n public getTimelineSets(): EventTimelineSet[] {\n return this.timelineSets;\n }\n\n /**\n * Helper to return the main unfiltered timeline set for this room\n * @returns room's unfiltered timeline set\n */\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSets[0];\n }\n\n /**\n * Get the timeline which contains the given event from the unfiltered set, if any\n *\n * @param eventId - event ID to look for\n * @returns timeline containing\n * the given event, or null if unknown\n */\n public getTimelineForEvent(eventId: string): EventTimeline | null {\n const event = this.findEventById(eventId);\n const thread = this.findThreadForEvent(event);\n if (thread) {\n return thread.timelineSet.getTimelineForEvent(eventId);\n } else {\n return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);\n }\n }\n\n /**\n * Add a new timeline to this room's unfiltered timeline set\n *\n * @returns newly-created timeline\n */\n public addTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().addTimeline();\n }\n\n /**\n * Whether the timeline needs to be refreshed in order to pull in new\n * historical messages that were imported.\n * @param value - The value to set\n */\n public setTimelineNeedsRefresh(value: boolean): void {\n this.timelineNeedsRefresh = value;\n }\n\n /**\n * Whether the timeline needs to be refreshed in order to pull in new\n * historical messages that were imported.\n * @returns .\n */\n public getTimelineNeedsRefresh(): boolean {\n return this.timelineNeedsRefresh;\n }\n\n /**\n * Get an event which is stored in our unfiltered timeline set, or in a thread\n *\n * @param eventId - event ID to look for\n * @returns the given event, or undefined if unknown\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n let event = this.getUnfilteredTimelineSet().findEventById(eventId);\n\n if (!event) {\n const threads = this.getThreads();\n for (let i = 0; i < threads.length; i++) {\n const thread = threads[i];\n event = thread.findEventById(eventId);\n if (event) {\n return event;\n }\n }\n }\n\n return event;\n }\n\n /**\n * Get one of the notification counts for this room\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getUnreadNotificationCount(type = NotificationCountType.Total): number {\n let count = this.getRoomUnreadNotificationCount(type);\n for (const threadNotification of this.threadNotifications.values()) {\n count += threadNotification[type] ?? 0;\n }\n return count;\n }\n\n /**\n * Get the notification for the event context (room or thread timeline)\n */\n public getUnreadCountForEventContext(type = NotificationCountType.Total, event: MatrixEvent): number {\n const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n\n return (\n (isThreadEvent\n ? this.getThreadUnreadNotificationCount(event.threadRootId, type)\n : this.getRoomUnreadNotificationCount(type)) ?? 0\n );\n }\n\n /**\n * Get one of the notification counts for this room\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getRoomUnreadNotificationCount(type = NotificationCountType.Total): number {\n return this.notificationCounts[type] ?? 0;\n }\n\n /**\n * Get one of the notification counts for a thread\n * @param threadId - the root event ID\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getThreadUnreadNotificationCount(threadId: string, type = NotificationCountType.Total): number {\n return this.threadNotifications.get(threadId)?.[type] ?? 0;\n }\n\n /**\n * Checks if the current room has unread thread notifications\n * @returns\n */\n public hasThreadUnreadNotification(): boolean {\n for (const notification of this.threadNotifications.values()) {\n if ((notification.highlight ?? 0) > 0 || (notification.total ?? 0) > 0) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Swet one of the notification count for a thread\n * @param threadId - the root event ID\n * @param type - The type of notification count to get. default: 'total'\n * @returns\n */\n public setThreadUnreadNotificationCount(threadId: string, type: NotificationCountType, count: number): void {\n const notification: NotificationCount = {\n highlight: this.threadNotifications.get(threadId)?.highlight,\n total: this.threadNotifications.get(threadId)?.total,\n ...{\n [type]: count,\n },\n };\n\n this.threadNotifications.set(threadId, notification);\n\n this.emit(RoomEvent.UnreadNotifications, notification, threadId);\n }\n\n /**\n * @returns the notification count type for all the threads in the room\n */\n public get threadsAggregateNotificationType(): NotificationCountType | null {\n let type: NotificationCountType | null = null;\n for (const threadNotification of this.threadNotifications.values()) {\n if ((threadNotification.highlight ?? 0) > 0) {\n return NotificationCountType.Highlight;\n } else if ((threadNotification.total ?? 0) > 0 && !type) {\n type = NotificationCountType.Total;\n }\n }\n return type;\n }\n\n /**\n * Resets the total thread notifications for all threads in this room to zero,\n * excluding any threads whose IDs are given in `exceptThreadIds`.\n *\n * If the room is not encrypted, also resets the highlight notification count to zero\n * for the same set of threads.\n *\n * This is intended for use from the sync code since we calculate highlight notification\n * counts locally from decrypted messages. We want to partially trust the total from the\n * server such that we clear notifications when read receipts arrive. The weird name is\n * intended to reflect this. You probably do not want to use this.\n *\n * @param exceptThreadIds - The thread IDs to exclude from the reset.\n */\n public resetThreadUnreadNotificationCountFromSync(exceptThreadIds: string[] = []): void {\n const isEncrypted = this.hasEncryptionStateEvent();\n\n for (const [threadId, notifs] of this.threadNotifications) {\n if (!exceptThreadIds.includes(threadId)) {\n notifs.total = 0;\n if (!isEncrypted) {\n notifs.highlight = 0;\n }\n }\n }\n\n this.emit(RoomEvent.UnreadNotifications);\n }\n\n /**\n * Set one of the notification counts for this room\n * @param type - The type of notification count to set.\n * @param count - The new count\n */\n public setUnreadNotificationCount(type: NotificationCountType, count: number): void {\n this.notificationCounts[type] = count;\n this.emit(RoomEvent.UnreadNotifications, this.notificationCounts);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.setUnreadNotificationCount(type, count);\n }\n\n public setSummary(summary: IRoomSummary): void {\n const heroes = summary[\"m.heroes\"];\n const joinedCount = summary[\"m.joined_member_count\"];\n const invitedCount = summary[\"m.invited_member_count\"];\n if (Number.isInteger(joinedCount)) {\n this.currentState.setJoinedMemberCount(joinedCount!);\n }\n if (Number.isInteger(invitedCount)) {\n this.currentState.setInvitedMemberCount(invitedCount!);\n }\n if (Array.isArray(heroes)) {\n // be cautious about trusting server values,\n // and make sure heroes doesn't contain our own id\n // just to be sure\n this.summaryHeroes = heroes.filter((userId) => {\n return userId !== this.myUserId;\n });\n }\n\n this.emit(RoomEvent.Summary, summary);\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @param value - true to blacklist unverified devices, null\n * to use the global value for this room.\n */\n public setBlacklistUnverifiedDevices(value: boolean): void {\n this.blacklistUnverifiedDevices = value;\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @returns true if blacklisting unverified devices, null\n * if the global value should be used for this room.\n */\n public getBlacklistUnverifiedDevices(): boolean | null {\n if (this.blacklistUnverifiedDevices === undefined) return null;\n return this.blacklistUnverifiedDevices;\n }\n\n /**\n * Get the avatar URL for a room if one was set.\n * @param baseUrl - The homeserver base URL. See\n * {@link MatrixClient#getHomeserverUrl}.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDefault - True to allow an identicon for this room if an\n * avatar URL wasn't explicitly set. Default: true. (Deprecated)\n * @returns the avatar URL or null.\n */\n public getAvatarUrl(\n baseUrl: string,\n width: number,\n height: number,\n resizeMethod: ResizeMethod,\n allowDefault = true,\n ): string | null {\n const roomAvatarEvent = this.currentState.getStateEvents(EventType.RoomAvatar, \"\");\n if (!roomAvatarEvent && !allowDefault) {\n return null;\n }\n\n const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;\n if (mainUrl) {\n return getHttpUriForMxc(baseUrl, mainUrl, width, height, resizeMethod);\n }\n\n return null;\n }\n\n /**\n * Get the mxc avatar url for the room, if one was set.\n * @returns the mxc avatar url or falsy\n */\n public getMxcAvatarUrl(): string | null {\n return this.currentState.getStateEvents(EventType.RoomAvatar, \"\")?.getContent()?.url || null;\n }\n\n /**\n * Get this room's canonical alias\n * The alias returned by this function may not necessarily\n * still point to this room.\n * @returns The room's canonical alias, or null if there is none\n */\n public getCanonicalAlias(): string | null {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alias || null;\n }\n return null;\n }\n\n /**\n * Get this room's alternative aliases\n * @returns The room's alternative aliases, or an empty array\n */\n public getAltAliases(): string[] {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alt_aliases || [];\n }\n return [];\n }\n\n /**\n * Add events to a timeline\n *\n * <p>Will fire \"Room.timeline\" for each event added.\n *\n * @param events - A list of events to add.\n *\n * @param toStartOfTimeline - True to add these events to the start\n * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n * event will be the <b>last</b> element of 'events'.\n *\n * @param timeline - timeline to\n * add events to.\n *\n * @param paginationToken - token for the next batch of events\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n public addEventsToTimeline(\n events: MatrixEvent[],\n toStartOfTimeline: boolean,\n timeline: EventTimeline,\n paginationToken?: string,\n ): void {\n timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken);\n }\n\n /**\n * Get the instance of the thread associated with the current event\n * @param eventId - the ID of the current event\n * @returns a thread instance if known\n */\n public getThread(eventId: string): Thread | null {\n return this.threads.get(eventId) ?? null;\n }\n\n /**\n * Get all the known threads in the room\n */\n public getThreads(): Thread[] {\n return Array.from(this.threads.values());\n }\n\n /**\n * Get a member from the current room state.\n * @param userId - The user ID of the member.\n * @returns The member or `null`.\n */\n public getMember(userId: string): RoomMember | null {\n return this.currentState.getMember(userId);\n }\n\n /**\n * Get all currently loaded members from the current\n * room state.\n * @returns Room members\n */\n public getMembers(): RoomMember[] {\n return this.currentState.getMembers();\n }\n\n /**\n * Get a list of members whose membership state is \"join\".\n * @returns A list of currently joined members.\n */\n public getJoinedMembers(): RoomMember[] {\n return this.getMembersWithMembership(KnownMembership.Join);\n }\n\n /**\n * Returns the number of joined members in this room\n * This method caches the result.\n * This is a wrapper around the method of the same name in roomState, returning\n * its result for the room's current state.\n * @returns The number of members in this room whose membership is 'join'\n */\n public getJoinedMemberCount(): number {\n return this.currentState.getJoinedMemberCount();\n }\n\n /**\n * Returns the number of invited members in this room\n * @returns The number of members in this room whose membership is 'invite'\n */\n public getInvitedMemberCount(): number {\n return this.currentState.getInvitedMemberCount();\n }\n\n /**\n * Returns the number of invited + joined members in this room\n * @returns The number of members in this room whose membership is 'invite' or 'join'\n */\n public getInvitedAndJoinedMemberCount(): number {\n return this.getInvitedMemberCount() + this.getJoinedMemberCount();\n }\n\n /**\n * Get a list of members with given membership state.\n * @param membership - The membership state.\n * @returns A list of members with the given membership state.\n */\n public getMembersWithMembership(membership: Membership): RoomMember[] {\n return this.currentState.getMembers().filter(function (m) {\n return m.membership === membership;\n });\n }\n\n /**\n * Get a list of members we should be encrypting for in this room\n * @returns A list of members who\n * we should encrypt messages for in this room.\n */\n public async getEncryptionTargetMembers(): Promise<RoomMember[]> {\n await this.loadMembersIfNeeded();\n let members = this.getMembersWithMembership(KnownMembership.Join);\n if (this.shouldEncryptForInvitedMembers()) {\n members = members.concat(this.getMembersWithMembership(KnownMembership.Invite));\n }\n return members;\n }\n\n /**\n * Determine whether we should encrypt messages for invited users in this room\n * @returns if we should encrypt messages for invited users\n */\n public shouldEncryptForInvitedMembers(): boolean {\n const ev = this.currentState.getStateEvents(EventType.RoomHistoryVisibility, \"\");\n return ev?.getContent()?.history_visibility !== \"joined\";\n }\n\n /**\n * Get the default room name (i.e. what a given user would see if the\n * room had no m.room.name)\n * @param userId - The userId from whose perspective we want\n * to calculate the default name\n * @returns The default room name\n */\n public getDefaultRoomName(userId: string): string {\n return this.calculateRoomName(userId, true);\n }\n\n /**\n * Check if the given user_id has the given membership state.\n * @param userId - The user ID to check.\n * @param membership - The membership e.g. `'join'`\n * @returns True if this user_id has the given membership state.\n */\n public hasMembershipState(userId: string, membership: Membership): boolean {\n const member = this.getMember(userId);\n if (!member) {\n return false;\n }\n return member.membership === membership;\n }\n\n /**\n * Add a timelineSet for this room with the given filter\n * @param filter - The filter to be applied to this timelineSet\n * @param opts - Configuration options\n * @returns The timelineSet\n */\n public getOrCreateFilteredTimelineSet(\n filter: Filter,\n { prepopulateTimeline = true, useSyncEvents = true, pendingEvents = true }: ICreateFilterOpts = {},\n ): EventTimelineSet {\n if (this.filteredTimelineSets[filter.filterId!]) {\n return this.filteredTimelineSets[filter.filterId!];\n }\n const opts = Object.assign({ filter, pendingEvents }, this.opts);\n const timelineSet = new EventTimelineSet(this, opts);\n this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n if (useSyncEvents) {\n this.filteredTimelineSets[filter.filterId!] = timelineSet;\n this.timelineSets.push(timelineSet);\n }\n\n const unfilteredLiveTimeline = this.getLiveTimeline();\n // Not all filter are possible to replicate client-side only\n // When that's the case we do not want to prepopulate from the live timeline\n // as we would get incorrect results compared to what the server would send back\n if (prepopulateTimeline) {\n // populate up the new timelineSet with filtered events from our live\n // unfiltered timeline.\n //\n // XXX: This is risky as our timeline\n // may have grown huge and so take a long time to filter.\n // see https://github.com/vector-im/vector-web/issues/2109\n\n unfilteredLiveTimeline.getEvents().forEach(function (event) {\n timelineSet.addLiveEvent(event);\n });\n\n // find the earliest unfiltered timeline\n let timeline = unfilteredLiveTimeline;\n while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) {\n timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)!;\n }\n\n timelineSet\n .getLiveTimeline()\n .setPaginationToken(timeline.getPaginationToken(EventTimeline.BACKWARDS), EventTimeline.BACKWARDS);\n } else if (useSyncEvents) {\n const livePaginationToken = unfilteredLiveTimeline.getPaginationToken(Direction.Forward);\n timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, Direction.Backward);\n }\n\n // alternatively, we could try to do something like this to try and re-paginate\n // in the filtered events from nothing, but Mark says it's an abuse of the API\n // to do so:\n //\n // timelineSet.resetLiveTimeline(\n // unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)\n // );\n\n return timelineSet;\n }\n\n private async getThreadListFilter(filterType = ThreadFilterType.All): Promise<Filter> {\n const myUserId = this.client.getUserId()!;\n const filter = new Filter(myUserId);\n\n const definition: IFilterDefinition = {\n room: {\n timeline: {\n [FILTER_RELATED_BY_REL_TYPES.name]: [THREAD_RELATION_TYPE.name],\n },\n },\n };\n\n if (filterType === ThreadFilterType.My) {\n definition!.room!.timeline![FILTER_RELATED_BY_SENDERS.name] = [myUserId];\n }\n\n filter.setDefinition(definition);\n const filterId = await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${filterType}`, filter);\n\n filter.filterId = filterId;\n\n return filter;\n }\n\n private async createThreadTimelineSet(filterType?: ThreadFilterType): Promise<EventTimelineSet> {\n let timelineSet: EventTimelineSet;\n if (Thread.hasServerSideListSupport) {\n timelineSet = new EventTimelineSet(\n this,\n {\n ...this.opts,\n pendingEvents: false,\n },\n undefined,\n undefined,\n filterType ?? ThreadFilterType.All,\n );\n this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n } else if (Thread.hasServerSideSupport) {\n const filter = await this.getThreadListFilter(filterType);\n\n timelineSet = this.getOrCreateFilteredTimelineSet(filter, {\n prepopulateTimeline: false,\n useSyncEvents: false,\n pendingEvents: false,\n });\n } else {\n timelineSet = new EventTimelineSet(this, {\n pendingEvents: false,\n });\n\n Array.from(this.threads).forEach(([, thread]) => {\n if (thread.length === 0) return;\n const currentUserParticipated = thread.timeline.some((event) => {\n return event.getSender() === this.client.getUserId();\n });\n if (filterType !== ThreadFilterType.My || currentUserParticipated) {\n timelineSet.getLiveTimeline().addEvent(thread.rootEvent!, {\n toStartOfTimeline: false,\n });\n }\n });\n }\n\n return timelineSet;\n }\n\n private threadsReady = false;\n\n /**\n * Takes the given thread root events and creates threads for them.\n */\n public processThreadRoots(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n if (!this.client.supportsThreads()) return;\n for (const rootEvent of events) {\n EventTimeline.setEventMetadata(rootEvent, this.currentState, toStartOfTimeline);\n if (!this.getThread(rootEvent.getId()!)) {\n this.createThread(rootEvent.getId()!, rootEvent, [], toStartOfTimeline);\n }\n }\n }\n\n /**\n * Fetch the bare minimum of room threads required for the thread list to work reliably.\n * With server support that means fetching one page.\n * Without server support that means fetching as much at once as the server allows us to.\n */\n public async fetchRoomThreads(): Promise<void> {\n if (this.threadsReady || !this.client.supportsThreads()) {\n return;\n }\n\n if (Thread.hasServerSideListSupport) {\n await Promise.all([\n this.fetchRoomThreadList(ThreadFilterType.All),\n this.fetchRoomThreadList(ThreadFilterType.My),\n ]);\n } else {\n const allThreadsFilter = await this.getThreadListFilter();\n\n const { chunk: events } = await this.client.createMessagesRequest(\n this.roomId,\n \"\",\n Number.MAX_SAFE_INTEGER,\n Direction.Backward,\n allThreadsFilter,\n );\n\n if (!events.length) return;\n\n // Sorted by last_reply origin_server_ts\n const threadRoots = events.map(this.client.getEventMapper()).sort((eventA, eventB) => {\n /**\n * `origin_server_ts` in a decentralised world is far from ideal\n * but for lack of any better, we will have to use this\n * Long term the sorting should be handled by homeservers and this\n * is only meant as a short term patch\n */\n const threadAMetadata = eventA.getServerAggregatedRelation<IThreadBundledRelationship>(\n THREAD_RELATION_TYPE.name,\n )!;\n const threadBMetadata = eventB.getServerAggregatedRelation<IThreadBundledRelationship>(\n THREAD_RELATION_TYPE.name,\n )!;\n return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts;\n });\n\n let latestMyThreadsRootEvent: MatrixEvent | undefined;\n const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n for (const rootEvent of threadRoots) {\n const opts = {\n duplicateStrategy: DuplicateStrategy.Ignore,\n fromCache: false,\n roomState,\n };\n this.threadsTimelineSets[0]?.addLiveEvent(rootEvent, opts);\n\n const threadRelationship = rootEvent.getServerAggregatedRelation<IThreadBundledRelationship>(\n THREAD_RELATION_TYPE.name,\n );\n if (threadRelationship?.current_user_participated) {\n this.threadsTimelineSets[1]?.addLiveEvent(rootEvent, opts);\n latestMyThreadsRootEvent = rootEvent;\n }\n }\n\n this.processThreadRoots(threadRoots, true);\n\n this.client.decryptEventIfNeeded(threadRoots[threadRoots.length - 1]);\n if (latestMyThreadsRootEvent) {\n this.client.decryptEventIfNeeded(latestMyThreadsRootEvent);\n }\n }\n\n this.on(ThreadEvent.NewReply, this.onThreadReply);\n this.on(ThreadEvent.Update, this.onThreadUpdate);\n this.on(ThreadEvent.Delete, this.onThreadDelete);\n this.threadsReady = true;\n }\n\n /**\n * Process a list of poll events.\n *\n * @param events - List of events\n */\n public async processPollEvents(events: MatrixEvent[]): Promise<void> {\n for (const event of events) {\n try {\n // Continue if the event is a clear text, non-poll event.\n if (!event.isEncrypted() && !isPollEvent(event)) continue;\n\n /**\n * Try to decrypt the event. Promise resolution does not guarantee a successful decryption.\n * Retry is handled in {@link processPollEvent}.\n */\n await this.client.decryptEventIfNeeded(event);\n this.processPollEvent(event);\n } catch (err) {\n logger.warn(\"Error processing poll event\", event.getId(), err);\n }\n }\n }\n\n /**\n * Processes poll events:\n * If the event has a decryption failure, it will listen for decryption and tries again.\n * If it is a poll start event (`m.poll.start`),\n * it creates and stores a Poll model and emits a PollEvent.New event.\n * If the event is related to a poll, it will add it to the poll.\n * Noop for other cases.\n *\n * @param event - Event that could be a poll event\n */\n private async processPollEvent(event: MatrixEvent): Promise<void> {\n if (event.isDecryptionFailure()) {\n event.once(MatrixEventEvent.Decrypted, (maybeDecryptedEvent: MatrixEvent) => {\n this.processPollEvent(maybeDecryptedEvent);\n });\n return;\n }\n\n if (M_POLL_START.matches(event.getType())) {\n try {\n const poll = new Poll(event, this.client, this);\n this.polls.set(event.getId()!, poll);\n this.emit(PollEvent.New, poll);\n\n // remove the poll when redacted\n event.once(MatrixEventEvent.BeforeRedaction, (redactedEvent: MatrixEvent) => {\n this.polls.delete(redactedEvent.getId()!);\n });\n } catch {}\n // poll creation can fail for malformed poll start events\n return;\n }\n\n const relationEventId = event.relationEventId;\n\n if (relationEventId && this.polls.has(relationEventId)) {\n const poll = this.polls.get(relationEventId);\n poll?.onNewRelation(event);\n }\n }\n\n /**\n * Fetch a single page of threadlist messages for the specific thread filter\n * @internal\n */\n private async fetchRoomThreadList(filter?: ThreadFilterType): Promise<void> {\n if (!this.client.supportsThreads()) return;\n if (this.threadsTimelineSets.length === 0) return;\n\n const timelineSet = filter === ThreadFilterType.My ? this.threadsTimelineSets[1] : this.threadsTimelineSets[0];\n\n const { chunk: events, end } = await this.client.createThreadListMessagesRequest(\n this.roomId,\n null,\n undefined,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n\n timelineSet.getLiveTimeline().setPaginationToken(end ?? null, Direction.Backward);\n\n if (!events.length) return;\n\n const matrixEvents = events.map(this.client.getEventMapper());\n this.processThreadRoots(matrixEvents, true);\n const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n for (const rootEvent of matrixEvents) {\n timelineSet.addLiveEvent(rootEvent, {\n duplicateStrategy: DuplicateStrategy.Replace,\n fromCache: false,\n roomState,\n });\n }\n }\n\n private onThreadUpdate(thread: Thread): void {\n this.updateThreadRootEvents(thread, false, false);\n }\n\n private onThreadReply(thread: Thread): void {\n this.updateThreadRootEvents(thread, false, true);\n }\n\n private onThreadDelete(thread: Thread): void {\n this.threads.delete(thread.id);\n\n const timeline = this.getTimelineForEvent(thread.id);\n const roomEvent = timeline?.getEvents()?.find((it) => it.getId() === thread.id);\n if (roomEvent) {\n thread.clearEventMetadata(roomEvent);\n } else {\n logger.debug(\"onThreadDelete: Could not find root event in room timeline\");\n }\n for (const timelineSet of this.threadsTimelineSets) {\n timelineSet.removeEvent(thread.id);\n }\n }\n\n /**\n * Forget the timelineSet for this room with the given filter\n *\n * @param filter - the filter whose timelineSet is to be forgotten\n */\n public removeFilteredTimelineSet(filter: Filter): void {\n const timelineSet = this.filteredTimelineSets[filter.filterId!];\n delete this.filteredTimelineSets[filter.filterId!];\n const i = this.timelineSets.indexOf(timelineSet);\n if (i > -1) {\n this.timelineSets.splice(i, 1);\n }\n }\n\n /**\n * Determine which timeline(s) a given event should live in\n * Thread roots live in both the main timeline and their corresponding thread timeline\n * Relations, redactions, replies to thread relation events live only in the thread timeline\n * Relations (other than m.thread), redactions, replies to a thread root live only in the main timeline\n * Relations, redactions, replies where the parent cannot be found live in no timelines but should be aggregated regardless.\n * Otherwise, the event lives in the main timeline only.\n *\n * Note: when a redaction is applied, the redacted event, events relating\n * to it, and the redaction event itself, will all move to the main thread.\n * This method classifies them as inside the thread of the redacted event.\n * They are moved later as part of makeRedacted.\n * This will change if MSC3389 is merged.\n */\n public eventShouldLiveIn(\n event: MatrixEvent,\n events?: MatrixEvent[],\n roots?: Set<string>,\n ): {\n shouldLiveInRoom: boolean;\n shouldLiveInThread: boolean;\n threadId?: string;\n } {\n if (!this.client?.supportsThreads()) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n // A thread root is the only event shown in both timelines\n if (event.isThreadRoot || roots?.has(event.getId()!)) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: true,\n threadId: event.getId(),\n };\n }\n\n const isThreadRelation = event.isRelation(THREAD_RELATION_TYPE.name);\n const parentEventId = event.getAssociatedId();\n const threadRootId = event.threadRootId;\n\n // Where the parent is the thread root and this is a non-thread relation this should live only in the main timeline\n if (!!parentEventId && !isThreadRelation && (threadRootId === parentEventId || roots?.has(parentEventId!))) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n let parentEvent: MatrixEvent | undefined;\n if (parentEventId) {\n parentEvent = this.findEventById(parentEventId) ?? events?.find((e) => e.getId() === parentEventId);\n }\n\n // Treat non-thread-relations, redactions, and replies as extensions of their parents so evaluate parentEvent instead\n if (parentEvent && !isThreadRelation) {\n return this.eventShouldLiveIn(parentEvent, events, roots);\n }\n\n // A thread relation (1st and 2nd order) is always only shown in a thread\n if (threadRootId != undefined) {\n return {\n shouldLiveInRoom: false,\n shouldLiveInThread: true,\n threadId: threadRootId,\n };\n }\n\n // Due to replies not being typical relations and being used as fallbacks for threads relations\n // If we bypass the if case above then we know we are not a thread, so if we are still a reply\n // then we know that we must be in the main timeline. Same goes if we have no associated parent event.\n if (!parentEventId || !!event.replyEventId) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n // We've exhausted all scenarios,\n // we cannot assume that it lives in the main timeline as this may be a relation for an unknown thread\n // adding the event in the wrong timeline causes stuck notifications and can break ability to send read receipts\n return {\n shouldLiveInRoom: false,\n shouldLiveInThread: false,\n };\n }\n\n public findThreadForEvent(event?: MatrixEvent): Thread | null {\n if (!event) return null;\n\n const { threadId } = this.eventShouldLiveIn(event);\n return threadId ? this.getThread(threadId) : null;\n }\n\n private addThreadedEvents(threadId: string, events: MatrixEvent[], toStartOfTimeline = false): void {\n const thread = this.getThread(threadId);\n if (thread) {\n thread.addEvents(events, toStartOfTimeline);\n } else {\n const rootEvent = this.findEventById(threadId) ?? events.find((e) => e.getId() === threadId);\n this.createThread(threadId, rootEvent, events, toStartOfTimeline);\n }\n }\n\n /**\n * Adds events to a thread's timeline. Will fire \"Thread.update\"\n */\n public processThreadedEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach(this.applyRedaction);\n\n const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};\n for (const event of events) {\n const { threadId, shouldLiveInThread } = this.eventShouldLiveIn(event);\n if (shouldLiveInThread && !eventsByThread[threadId!]) {\n eventsByThread[threadId!] = [];\n }\n eventsByThread[threadId!]?.push(event);\n }\n\n Object.entries(eventsByThread).map(([threadId, threadEvents]) =>\n this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline),\n );\n }\n\n private updateThreadRootEvents = (thread: Thread, toStartOfTimeline: boolean, recreateEvent: boolean): void => {\n if (thread.length) {\n this.updateThreadRootEvent(this.threadsTimelineSets?.[0], thread, toStartOfTimeline, recreateEvent);\n if (thread.hasCurrentUserParticipated) {\n this.updateThreadRootEvent(this.threadsTimelineSets?.[1], thread, toStartOfTimeline, recreateEvent);\n }\n }\n };\n\n private updateThreadRootEvent = (\n timelineSet: Optional<EventTimelineSet>,\n thread: Thread,\n toStartOfTimeline: boolean,\n recreateEvent: boolean,\n ): void => {\n if (timelineSet && thread.rootEvent) {\n if (recreateEvent) {\n timelineSet.removeEvent(thread.id);\n }\n if (Thread.hasServerSideSupport) {\n timelineSet.addLiveEvent(thread.rootEvent, {\n duplicateStrategy: DuplicateStrategy.Replace,\n fromCache: false,\n roomState: this.currentState,\n });\n } else {\n timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), { toStartOfTimeline });\n }\n }\n };\n\n public createThread(\n threadId: string,\n rootEvent: MatrixEvent | undefined,\n events: MatrixEvent[] = [],\n toStartOfTimeline: boolean,\n ): Thread {\n if (this.threads.has(threadId)) {\n return this.threads.get(threadId)!;\n }\n\n if (rootEvent) {\n const relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId()!);\n if (relatedEvents?.length) {\n // Include all relations of the root event, given it'll be visible in both timelines,\n // except `m.replace` as that will already be applied atop the event using `MatrixEvent::makeReplaced`\n events = events.concat(relatedEvents.filter((e) => !e.isRelation(RelationType.Replace)));\n }\n }\n\n const thread = new Thread(threadId, rootEvent, {\n room: this,\n client: this.client,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n receipts: this.cachedThreadReadReceipts.get(threadId) ?? [],\n });\n\n // Add the re-emitter before we start adding events to the thread so we don't miss events\n this.reEmitter.reEmit(thread, [\n ThreadEvent.Delete,\n ThreadEvent.Update,\n ThreadEvent.NewReply,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n ]);\n\n // All read receipts should now come down from sync, we do not need to keep\n // a reference to the cached receipts anymore.\n this.cachedThreadReadReceipts.delete(threadId);\n\n // If we managed to create a thread and figure out its `id` then we can use it\n // This has to happen before thread.addEvents, because that adds events to the eventtimeline, and the\n // eventtimeline sometimes looks up thread information via the room.\n this.threads.set(thread.id, thread);\n\n // This is necessary to be able to jump to events in threads:\n // If we jump to an event in a thread where neither the event, nor the root,\n // nor any thread event are loaded yet, we'll load the event as well as the thread root, create the thread,\n // and pass the event through this.\n thread.addEvents(events, false);\n\n // We need to update the thread root events, but the thread may not be ready yet.\n // If it isn't, it will fire ThreadEvent.Update when it is and we'll call updateThreadRootEvents then.\n if (this.threadsReady && thread.initialEventsFetched) {\n this.updateThreadRootEvents(thread, toStartOfTimeline, false);\n }\n this.emit(ThreadEvent.New, thread, toStartOfTimeline);\n\n return thread;\n }\n\n private applyRedaction = (event: MatrixEvent): void => {\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n\n // if we know about this event, redact its contents now.\n const redactedEvent = redactId ? this.findEventById(redactId) : undefined;\n if (redactedEvent) {\n const threadRootId = redactedEvent.threadRootId;\n redactedEvent.makeRedacted(event, this);\n\n // If this is in the current state, replace it with the redacted version\n if (redactedEvent.isState()) {\n const currentStateEvent = this.currentState.getStateEvents(\n redactedEvent.getType(),\n redactedEvent.getStateKey()!,\n );\n if (currentStateEvent?.getId() === redactedEvent.getId()) {\n this.currentState.setStateEvents([redactedEvent]);\n }\n }\n\n this.emit(RoomEvent.Redaction, event, this, threadRootId);\n\n // TODO: we stash user displaynames (among other things) in\n // RoomMember objects which are then attached to other events\n // (in the sender and target fields). We should get those\n // RoomMember objects to update themselves when the events that\n // they are based on are changed.\n\n // Remove any visibility change on this event.\n this.visibilityEvents.delete(redactId!);\n\n // If this event is a visibility change event, remove it from the\n // list of visibility changes and update any event affected by it.\n if (redactedEvent.isVisibilityEvent()) {\n this.redactVisibilityChangeEvent(event);\n }\n }\n\n // FIXME: apply redactions to notification list\n\n // NB: We continue to add the redaction event to the timeline so\n // clients can say \"so and so redacted an event\" if they wish to. Also\n // this may be needed to trigger an update.\n }\n };\n\n private processLiveEvent(event: MatrixEvent): void {\n this.applyRedaction(event);\n\n // Implement MSC3531: hiding messages.\n if (event.isVisibilityEvent()) {\n // This event changes the visibility of another event, record\n // the visibility change, inform clients if necessary.\n this.applyNewVisibilityEvent(event);\n }\n // If any pending visibility change is waiting for this (older) event,\n this.applyPendingVisibilityEvents(event);\n\n // Sliding Sync modifications:\n // The proxy cannot guarantee every sent event will have a transaction_id field, so we need\n // to check the event ID against the list of pending events if there is no transaction ID\n // field. Only do this for events sent by us though as it's potentially expensive to loop\n // the pending events map.\n const txnId = event.getUnsigned().transaction_id;\n if (!txnId && event.getSender() === this.myUserId) {\n // check the txn map for a matching event ID\n for (const [tid, localEvent] of this.txnToEvent) {\n if (localEvent.getId() === event.getId()) {\n logger.debug(\"processLiveEvent: found sent event without txn ID: \", tid, event.getId());\n // update the unsigned field so we can re-use the same codepaths\n const unsigned = event.getUnsigned();\n unsigned.transaction_id = tid;\n event.setUnsigned(unsigned);\n break;\n }\n }\n }\n }\n\n /**\n * Add an event to the end of this room's live timelines. Will fire\n * \"Room.timeline\".\n *\n * @param event - Event to be added\n * @param addLiveEventOptions - addLiveEvent options\n * @internal\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n private addLiveEvent(event: MatrixEvent, addLiveEventOptions: IAddLiveEventOptions): void {\n const { duplicateStrategy, timelineWasEmpty, fromCache } = addLiveEventOptions;\n\n // add to our timeline sets\n for (const timelineSet of this.timelineSets) {\n timelineSet.addLiveEvent(event, {\n duplicateStrategy,\n fromCache,\n timelineWasEmpty,\n });\n }\n\n // synthesize and inject implicit read receipts\n // Done after adding the event because otherwise the app would get a read receipt\n // pointing to an event that wasn't yet in the timeline\n // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.\n if (event.sender && event.getType() !== EventType.RoomRedaction) {\n this.addReceipt(synthesizeReceipt(event.sender.userId, event, ReceiptType.Read), true);\n\n // Any live events from a user could be taken as implicit\n // presence information: evidence that they are currently active.\n // ...except in a world where we use 'user.currentlyActive' to reduce\n // presence spam, this isn't very useful - we'll get a transition when\n // they are no longer currently active anyway. So don't bother to\n // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.\n }\n }\n\n /**\n * Add a pending outgoing event to this room.\n *\n * <p>The event is added to either the pendingEventList, or the live timeline,\n * depending on the setting of opts.pendingEventOrdering.\n *\n * <p>This is an internal method, intended for use by MatrixClient.\n *\n * @param event - The event to add.\n *\n * @param txnId - Transaction id for this outgoing event\n *\n * @throws if the event doesn't have status SENDING, or we aren't given a\n * unique transaction id.\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public addPendingEvent(event: MatrixEvent, txnId: string): void {\n if (event.status !== EventStatus.SENDING && event.status !== EventStatus.NOT_SENT) {\n throw new Error(\"addPendingEvent called on an event with status \" + event.status);\n }\n\n if (this.txnToEvent.get(txnId)) {\n throw new Error(\"addPendingEvent called on an event with known txnId \" + txnId);\n }\n\n // call setEventMetadata to set up event.sender etc\n // as event is shared over all timelineSets, we set up its metadata based\n // on the unfiltered timelineSet.\n EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(EventTimeline.FORWARDS)!, false);\n\n this.txnToEvent.set(txnId, event);\n if (this.pendingEventList) {\n if (this.pendingEventList.some((e) => e.status === EventStatus.NOT_SENT)) {\n logger.warn(\"Setting event as NOT_SENT due to messages in the same state\");\n event.setStatus(EventStatus.NOT_SENT);\n }\n this.pendingEventList.push(event);\n this.savePendingEvents();\n if (event.isRelation()) {\n // For pending events, add them to the relations collection immediately.\n // (The alternate case below already covers this as part of adding to\n // the timeline set.)\n this.aggregateNonLiveRelation(event);\n }\n\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n let redactedEvent = this.pendingEventList.find((e) => e.getId() === redactId);\n if (!redactedEvent && redactId) {\n redactedEvent = this.findEventById(redactId);\n }\n if (redactedEvent) {\n redactedEvent.markLocallyRedacted(event);\n this.emit(RoomEvent.Redaction, event, this, redactedEvent.threadRootId);\n }\n }\n } else {\n for (const timelineSet of this.timelineSets) {\n if (timelineSet.getFilter()) {\n if (timelineSet.getFilter()!.filterRoomTimeline([event]).length) {\n timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n toStartOfTimeline: false,\n });\n }\n } else {\n timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n toStartOfTimeline: false,\n });\n }\n }\n }\n\n this.emit(RoomEvent.LocalEchoUpdated, event, this);\n }\n\n /**\n * Persists all pending events to local storage\n *\n * If the current room is encrypted only encrypted events will be persisted\n * all messages that are not yet encrypted will be discarded\n *\n * This is because the flow of EVENT_STATUS transition is\n * `queued => sending => encrypting => sending => sent`\n *\n * Steps 3 and 4 are skipped for unencrypted room.\n * It is better to discard an unencrypted message rather than persisting\n * it locally for everyone to read\n */\n private savePendingEvents(): void {\n if (this.pendingEventList) {\n const pendingEvents = this.pendingEventList\n .map((event) => {\n return {\n ...event.event,\n txn_id: event.getTxnId(),\n };\n })\n .filter((event) => {\n // Filter out the unencrypted messages if the room is encrypted\n const isEventEncrypted = event.type === EventType.RoomMessageEncrypted;\n const isRoomEncrypted = this.hasEncryptionStateEvent();\n return isEventEncrypted || !isRoomEncrypted;\n });\n\n this.client.store.setPendingEvents(this.roomId, pendingEvents);\n }\n }\n\n /**\n * Used to aggregate the local echo for a relation, and also\n * for re-applying a relation after it's redaction has been cancelled,\n * as the local echo for the redaction of the relation would have\n * un-aggregated the relation. Note that this is different from regular messages,\n * which are just kept detached for their local echo.\n *\n * Also note that live events are aggregated in the live EventTimelineSet.\n * @param event - the relation event that needs to be aggregated.\n */\n private aggregateNonLiveRelation(event: MatrixEvent): void {\n this.relations.aggregateChildEvent(event);\n }\n\n public getEventForTxnId(txnId: string): MatrixEvent | undefined {\n return this.txnToEvent.get(txnId);\n }\n\n /**\n * Deal with the echo of a message we sent.\n *\n * <p>We move the event to the live timeline if it isn't there already, and\n * update it.\n *\n * @param remoteEvent - The event received from\n * /sync\n * @param localEvent - The local echo, which\n * should be either in the pendingEventList or the timeline.\n *\n * @internal\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public handleRemoteEcho(remoteEvent: MatrixEvent, localEvent: MatrixEvent): void {\n const oldEventId = localEvent.getId()!;\n const newEventId = remoteEvent.getId()!;\n const oldStatus = localEvent.status;\n\n logger.debug(`Got remote echo for event ${oldEventId} -> ${newEventId} old status ${oldStatus}`);\n\n // no longer pending\n this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id!);\n\n // if it's in the pending list, remove it\n if (this.pendingEventList) {\n this.removePendingEvent(oldEventId);\n }\n\n // replace the event source (this will preserve the plaintext payload if\n // any, which is good, because we don't want to try decoding it again).\n localEvent.handleRemoteEcho(remoteEvent.event);\n\n const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(remoteEvent);\n const thread = threadId ? this.getThread(threadId) : null;\n thread?.setEventMetadata(localEvent);\n thread?.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n\n if (shouldLiveInRoom) {\n for (const timelineSet of this.timelineSets) {\n // if it's already in the timeline, update the timeline map. If it's not, add it.\n timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n }\n }\n\n this.emit(RoomEvent.LocalEchoUpdated, localEvent, this, oldEventId, oldStatus);\n }\n\n /**\n * Update the status / event id on a pending event, to reflect its transmission\n * progress.\n *\n * <p>This is an internal method.\n *\n * @param event - local echo event\n * @param newStatus - status to assign\n * @param newEventId - new event id to assign. Ignored unless newStatus == EventStatus.SENT.\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public updatePendingEvent(event: MatrixEvent, newStatus: EventStatus, newEventId?: string): void {\n logger.log(\n `setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` +\n `event ID ${event.getId()} -> ${newEventId}`,\n );\n\n // if the message was sent, we expect an event id\n if (newStatus == EventStatus.SENT && !newEventId) {\n throw new Error(\"updatePendingEvent called with status=SENT, but no new event id\");\n }\n\n // SENT races against /sync, so we have to special-case it.\n if (newStatus == EventStatus.SENT) {\n const timeline = this.getTimelineForEvent(newEventId!);\n if (timeline) {\n // we've already received the event via the event stream.\n // nothing more to do here, assuming the transaction ID was correctly matched.\n // Let's check that.\n const remoteEvent = this.findEventById(newEventId!);\n const remoteTxnId = remoteEvent?.getUnsigned().transaction_id;\n if (!remoteTxnId && remoteEvent) {\n // This code path is mostly relevant for the Sliding Sync proxy.\n // The remote event did not contain a transaction ID, so we did not handle\n // the remote echo yet. Handle it now.\n const unsigned = remoteEvent.getUnsigned();\n unsigned.transaction_id = event.getTxnId();\n remoteEvent.setUnsigned(unsigned);\n // the remote event is _already_ in the timeline, so we need to remove it so\n // we can convert the local event into the final event.\n this.removeEvent(remoteEvent.getId()!);\n this.handleRemoteEcho(remoteEvent, event);\n }\n return;\n }\n }\n\n const oldStatus = event.status;\n const oldEventId = event.getId()!;\n\n if (!oldStatus) {\n throw new Error(\"updatePendingEventStatus called on an event which is not a local echo.\");\n }\n\n const allowed = ALLOWED_TRANSITIONS[oldStatus];\n if (!allowed?.includes(newStatus)) {\n throw new Error(`Invalid EventStatus transition ${oldStatus}->${newStatus}`);\n }\n\n event.setStatus(newStatus);\n\n if (newStatus == EventStatus.SENT) {\n // update the event id\n event.replaceLocalEventId(newEventId!);\n\n const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(event);\n const thread = threadId ? this.getThread(threadId) : undefined;\n thread?.setEventMetadata(event);\n thread?.timelineSet.replaceEventId(oldEventId, newEventId!);\n\n if (shouldLiveInRoom) {\n // if the event was already in the timeline (which will be the case if\n // opts.pendingEventOrdering==chronological), we need to update the\n // timeline map.\n for (const timelineSet of this.timelineSets) {\n timelineSet.replaceEventId(oldEventId, newEventId!);\n }\n }\n } else if (newStatus == EventStatus.CANCELLED) {\n // remove it from the pending event list, or the timeline.\n if (this.pendingEventList) {\n const removedEvent = this.getPendingEvent(oldEventId);\n this.removePendingEvent(oldEventId);\n if (removedEvent?.isRedaction()) {\n this.revertRedactionLocalEcho(removedEvent);\n }\n }\n this.removeEvent(oldEventId);\n }\n this.savePendingEvents();\n\n this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus);\n }\n\n private revertRedactionLocalEcho(redactionEvent: MatrixEvent): void {\n const redactId = redactionEvent.event.redacts;\n if (!redactId) {\n return;\n }\n const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);\n if (redactedEvent) {\n redactedEvent.unmarkLocallyRedacted();\n // re-render after undoing redaction\n this.emit(RoomEvent.RedactionCancelled, redactionEvent, this);\n // reapply relation now redaction failed\n if (redactedEvent.isRelation()) {\n this.aggregateNonLiveRelation(redactedEvent);\n }\n }\n }\n\n private assertTimelineSetsAreLive(): void {\n for (let i = 0; i < this.timelineSets.length; i++) {\n const liveTimeline = this.timelineSets[i].getLiveTimeline();\n if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {\n throw new Error(\n \"live timeline \" +\n i +\n \" is no longer live - it has a pagination token \" +\n \"(\" +\n liveTimeline.getPaginationToken(EventTimeline.FORWARDS) +\n \")\",\n );\n }\n if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) {\n throw new Error(`live timeline ${i} is no longer live - it has a neighbouring timeline`);\n }\n }\n }\n\n /**\n * Add some events to this room. This can include state events, message\n * events and typing notifications. These events are treated as \"live\" so\n * they will go to the end of the timeline.\n *\n * @param events - A list of events to add.\n * @param addLiveEventOptions - addLiveEvent options\n * @throws If `duplicateStrategy` is not falsey, 'replace' or 'ignore'.\n */\n public async addLiveEvents(events: MatrixEvent[], addLiveEventOptions?: IAddLiveEventOptions): Promise<void> {\n const { duplicateStrategy, fromCache, timelineWasEmpty = false } = addLiveEventOptions ?? {};\n if (duplicateStrategy && [\"replace\", \"ignore\"].indexOf(duplicateStrategy) === -1) {\n throw new Error(\"duplicateStrategy MUST be either 'replace' or 'ignore'\");\n }\n\n // sanity check that the live timeline is still live\n this.assertTimelineSetsAreLive();\n\n const threadRoots = this.findThreadRoots(events);\n const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};\n\n const options: IAddLiveEventOptions = {\n duplicateStrategy,\n fromCache,\n timelineWasEmpty,\n };\n\n // List of extra events to check for being parents of any relations encountered\n const neighbouringEvents = [...events];\n\n for (const event of events) {\n // TODO: We should have a filter to say \"only add state event types X Y Z to the timeline\".\n this.processLiveEvent(event);\n\n if (event.getUnsigned().transaction_id) {\n const existingEvent = this.txnToEvent.get(event.getUnsigned().transaction_id!);\n if (existingEvent) {\n // remote echo of an event we sent earlier\n this.handleRemoteEcho(event, existingEvent);\n continue; // we can skip adding the event to the timeline sets, it is already there\n }\n }\n\n let {\n shouldLiveInRoom,\n shouldLiveInThread,\n threadId = \"\",\n } = this.eventShouldLiveIn(event, neighbouringEvents, threadRoots);\n\n if (!shouldLiveInThread && !shouldLiveInRoom && event.isRelation()) {\n try {\n const parentEvent = new MatrixEvent(\n await this.client.fetchRoomEvent(this.roomId, event.relationEventId!),\n );\n neighbouringEvents.push(parentEvent);\n if (parentEvent.threadRootId) {\n threadRoots.add(parentEvent.threadRootId);\n const unsigned = event.getUnsigned();\n unsigned[UNSIGNED_THREAD_ID_FIELD.name] = parentEvent.threadRootId;\n event.setUnsigned(unsigned);\n }\n\n ({\n shouldLiveInRoom,\n shouldLiveInThread,\n threadId = \"\",\n } = this.eventShouldLiveIn(event, neighbouringEvents, threadRoots));\n } catch (e) {\n logger.error(\"Failed to load parent event of unhandled relation\", e);\n }\n }\n\n if (shouldLiveInThread && !eventsByThread[threadId]) {\n eventsByThread[threadId] = [];\n }\n eventsByThread[threadId]?.push(event);\n\n if (shouldLiveInRoom) {\n this.addLiveEvent(event, options);\n } else if (!shouldLiveInThread && event.isRelation()) {\n this.relations.aggregateChildEvent(event);\n }\n }\n\n Object.entries(eventsByThread).forEach(([threadId, threadEvents]) => {\n this.addThreadedEvents(threadId, threadEvents, false);\n });\n }\n\n public partitionThreadedEvents(\n events: MatrixEvent[],\n ): [timelineEvents: MatrixEvent[], threadedEvents: MatrixEvent[], unknownRelations: MatrixEvent[]] {\n // Indices to the events array, for readability\n const ROOM = 0;\n const THREAD = 1;\n const UNKNOWN_RELATION = 2;\n if (this.client.supportsThreads()) {\n const threadRoots = this.findThreadRoots(events);\n return events.reduce<[MatrixEvent[], MatrixEvent[], MatrixEvent[]]>(\n (memo, event: MatrixEvent) => {\n const { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(\n event,\n events,\n threadRoots,\n );\n\n if (shouldLiveInRoom) {\n memo[ROOM].push(event);\n }\n\n if (shouldLiveInThread) {\n event.setThreadId(threadId ?? \"\");\n memo[THREAD].push(event);\n }\n\n if (!shouldLiveInThread && !shouldLiveInRoom) {\n memo[UNKNOWN_RELATION].push(event);\n }\n\n return memo;\n },\n [[], [], []],\n );\n } else {\n // When `threadSupport` is disabled treat all events as timelineEvents\n return [events as MatrixEvent[], [] as MatrixEvent[], [] as MatrixEvent[]];\n }\n }\n\n /**\n * Given some events, find the IDs of all the thread roots that are referred to by them.\n */\n private findThreadRoots(events: MatrixEvent[]): Set<string> {\n const threadRoots = new Set<string>();\n for (const event of events) {\n const threadRootId = event.threadRootId;\n if (threadRootId != undefined) {\n threadRoots.add(threadRootId);\n }\n }\n return threadRoots;\n }\n\n /**\n * Add a receipt event to the room.\n * @param event - The m.receipt event.\n * @param synthetic - True if this event is implicit.\n */\n public addReceipt(event: MatrixEvent, synthetic = false): void {\n const content = event.getContent<ReceiptContent>();\n\n this.roomReceipts.add(content, synthetic);\n\n // TODO: delete the following code when it has been replaced by RoomReceipts\n Object.keys(content).forEach((eventId: string) => {\n Object.keys(content[eventId]).forEach((receiptType: ReceiptType | string) => {\n Object.keys(content[eventId][receiptType]).forEach((userId: string) => {\n const receipt = content[eventId][receiptType][userId] as Receipt;\n const receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === MAIN_ROOM_TIMELINE;\n const receiptDestination: Thread | this | undefined = receiptForMainTimeline\n ? this\n : this.threads.get(receipt.thread_id ?? \"\");\n\n if (receiptDestination) {\n receiptDestination.addReceiptToStructure(\n eventId,\n receiptType as ReceiptType,\n userId,\n receipt,\n synthetic,\n );\n\n // If the read receipt sent for the logged in user matches\n // the last event of the live timeline, then we know for a fact\n // that the user has read that message, so we can mark the room\n // as read and not wait for the remote echo from synapse.\n //\n // This needs to be done after the initial sync as we do not want this\n // logic to run whilst the room is being initialised\n //\n // We only do this for non-synthetic receipts, because\n // our intention is to do this when the user really did\n // just read a message, not when we are e.g. receiving\n // an event during the sync. More explanation at:\n // https://github.com/matrix-org/matrix-js-sdk/issues/3684\n if (!synthetic && this.client.isInitialSyncComplete() && userId === this.client.getUserId()) {\n const lastEvent = receiptDestination.timeline[receiptDestination.timeline.length - 1];\n if (lastEvent && eventId === lastEvent.getId() && userId === lastEvent.getSender()) {\n receiptDestination.setUnread(NotificationCountType.Total, 0);\n receiptDestination.setUnread(NotificationCountType.Highlight, 0);\n }\n }\n } else {\n // The thread does not exist locally, keep the read receipt\n // in a cache locally, and re-apply the `addReceipt` logic\n // when the thread is created\n this.cachedThreadReadReceipts.set(receipt.thread_id!, [\n ...(this.cachedThreadReadReceipts.get(receipt.thread_id!) ?? []),\n { eventId, receiptType, userId, receipt, synthetic },\n ]);\n }\n\n const me = this.client.getUserId();\n // Track the time of the current user's oldest threaded receipt in the room.\n if (userId === me && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) {\n this.oldestThreadedReceiptTs = receipt.ts;\n }\n\n // Track each user's unthreaded read receipt.\n if (!receipt.thread_id && receipt.ts > (this.unthreadedReceipts.get(userId)?.ts ?? 0)) {\n this.unthreadedReceipts.set(userId, receipt);\n }\n });\n });\n });\n // End of code to delete when replaced by RoomReceipts\n\n // send events after we've regenerated the structure & cache, otherwise things that\n // listened for the event would read stale data.\n this.emit(RoomEvent.Receipt, event, this);\n }\n\n /**\n * Adds/handles ephemeral events such as typing notifications and read receipts.\n * @param events - A list of events to process\n */\n public addEphemeralEvents(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === EventType.Typing) {\n this.currentState.setTypingEvent(event);\n } else if (event.getType() === EventType.Receipt) {\n this.addReceipt(event);\n } // else ignore - life is too short for us to care about these events\n }\n }\n\n /**\n * Removes events from this room.\n * @param eventIds - A list of eventIds to remove.\n */\n public removeEvents(eventIds: string[]): void {\n for (const eventId of eventIds) {\n this.removeEvent(eventId);\n }\n }\n\n /**\n * Removes a single event from this room.\n *\n * @param eventId - The id of the event to remove\n *\n * @returns true if the event was removed from any of the room's timeline sets\n */\n public removeEvent(eventId: string): boolean {\n let removedAny = false;\n for (const timelineSet of this.timelineSets) {\n const removed = timelineSet.removeEvent(eventId);\n if (removed) {\n if (removed.isRedaction()) {\n this.revertRedactionLocalEcho(removed);\n }\n removedAny = true;\n }\n }\n return removedAny;\n }\n\n /**\n * Recalculate various aspects of the room, including the room name and\n * room summary. Call this any time the room's current state is modified.\n * May fire \"Room.name\" if the room name is updated.\n *\n * @remarks\n * Fires {@link RoomEvent.Name}\n */\n public recalculate(): void {\n // set fake stripped state events if this is an invite room so logic remains\n // consistent elsewhere.\n const membershipEvent = this.currentState.getStateEvents(EventType.RoomMember, this.myUserId);\n if (membershipEvent) {\n const membership = membershipEvent.getContent().membership;\n this.updateMyMembership(membership!);\n\n if (membership === KnownMembership.Invite) {\n const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];\n strippedStateEvents.forEach((strippedEvent) => {\n const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);\n if (!existingEvent) {\n // set the fake stripped event instead\n this.currentState.setStateEvents([\n new MatrixEvent({\n type: strippedEvent.type,\n state_key: strippedEvent.state_key,\n content: strippedEvent.content,\n event_id: \"$fake\" + Date.now(),\n room_id: this.roomId,\n sender: this.myUserId, // technically a lie\n }),\n ]);\n }\n });\n }\n }\n\n const oldName = this.name;\n this.name = this.calculateRoomName(this.myUserId);\n this.normalizedName = normalize(this.name);\n this.summary = new RoomSummary(this.roomId, {\n title: this.name,\n });\n\n if (oldName !== this.name) {\n this.emit(RoomEvent.Name, this);\n }\n }\n\n /**\n * Update the room-tag event for the room. The previous one is overwritten.\n * @param event - the m.tag event\n */\n public addTags(event: MatrixEvent): void {\n // event content looks like:\n // content: {\n // tags: {\n // $tagName: { $metadata: $value },\n // $tagName: { $metadata: $value },\n // }\n // }\n\n // XXX: do we need to deep copy here?\n this.tags = event.getContent().tags || {};\n\n // XXX: we could do a deep-comparison to see if the tags have really\n // changed - but do we want to bother?\n this.emit(RoomEvent.Tags, event, this);\n }\n\n /**\n * Update the account_data events for this room, overwriting events of the same type.\n * @param events - an array of account_data events to add\n */\n public addAccountData(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === \"m.tag\") {\n this.addTags(event);\n }\n const eventType = event.getType();\n const lastEvent = this.accountData.get(eventType);\n this.accountData.set(eventType, event);\n this.emit(RoomEvent.AccountData, event, this, lastEvent);\n }\n }\n\n /**\n * Access account_data event of given event type for this room\n * @param type - the type of account_data event to be accessed\n * @returns the account_data event in question\n */\n public getAccountData(type: EventType | string): MatrixEvent | undefined {\n return this.accountData.get(type);\n }\n\n /**\n * Returns whether the syncing user has permission to send a message in the room\n * @returns true if the user should be permitted to send\n * message events into the room.\n */\n public maySendMessage(): boolean {\n return (\n this.getMyMembership() === KnownMembership.Join &&\n (this.hasEncryptionStateEvent()\n ? this.currentState.maySendEvent(EventType.RoomMessageEncrypted, this.myUserId)\n : this.currentState.maySendEvent(EventType.RoomMessage, this.myUserId))\n );\n }\n\n /**\n * Returns whether the given user has permissions to issue an invite for this room.\n * @param userId - the ID of the Matrix user to check permissions for\n * @returns true if the user should be permitted to issue invites for this room.\n */\n public canInvite(userId: string): boolean {\n let canInvite = this.getMyMembership() === KnownMembership.Join;\n const powerLevelsEvent = this.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();\n const me = this.getMember(userId);\n if (powerLevels && me && powerLevels.invite > me.powerLevel) {\n canInvite = false;\n }\n return canInvite;\n }\n\n /**\n * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n * @returns the join_rule applied to this room\n */\n public getJoinRule(): JoinRule {\n return this.currentState.getJoinRule();\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getHistoryVisibility(): HistoryVisibility {\n return this.currentState.getHistoryVisibility();\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getGuestAccess(): GuestAccess {\n return this.currentState.getGuestAccess();\n }\n\n /**\n * Returns the type of the room from the `m.room.create` event content or undefined if none is set\n * @returns the type of the room.\n */\n public getType(): RoomType | string | undefined {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getTypeWarning) {\n logger.warn(\"[getType] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getTypeWarning = true;\n }\n return undefined;\n }\n return createEvent.getContent()[RoomCreateTypeField];\n }\n\n /**\n * Returns whether the room is a space-room as defined by MSC1772.\n * @returns true if the room's type is RoomType.Space\n */\n public isSpaceRoom(): boolean {\n return this.getType() === RoomType.Space;\n }\n\n /**\n * Returns whether the room is a call-room as defined by MSC3417.\n * @returns true if the room's type is RoomType.UnstableCall\n */\n public isCallRoom(): boolean {\n return this.getType() === RoomType.UnstableCall;\n }\n\n /**\n * Returns whether the room is a video room.\n * @returns true if the room's type is RoomType.ElementVideo\n */\n public isElementVideoRoom(): boolean {\n return this.getType() === RoomType.ElementVideo;\n }\n\n /**\n * Find the predecessor of this room.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and use it if found (MSC3946).\n * @returns null if this room has no predecessor. Otherwise, returns\n * the roomId, last eventId and viaServers of the predecessor room.\n *\n * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events\n * as well as m.room.create events to find predecessors.\n *\n * Note: if an m.predecessor event is used, eventId may be undefined\n * since last_known_event_id is optional.\n *\n * Note: viaServers may be undefined, and will definitely be undefined if\n * this predecessor comes from a RoomCreate event (rather than a\n * RoomPredecessor, which has the optional via_servers property).\n */\n public findPredecessor(\n msc3946ProcessDynamicPredecessor = false,\n ): { roomId: string; eventId?: string; viaServers?: string[] } | null {\n const currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n if (!currentState) {\n return null;\n }\n return currentState.findPredecessor(msc3946ProcessDynamicPredecessor);\n }\n\n private roomNameGenerator(state: RoomNameState): string {\n if (this.client.roomNameGenerator) {\n const name = this.client.roomNameGenerator(this.roomId, state);\n if (name !== null) {\n return name;\n }\n }\n\n switch (state.type) {\n case RoomNameType.Actual:\n return state.name;\n case RoomNameType.Generated:\n switch (state.subtype) {\n case \"Inviting\":\n return `Inviting ${memberNamesToRoomName(state.names, state.count)}`;\n default:\n return memberNamesToRoomName(state.names, state.count);\n }\n case RoomNameType.EmptyRoom:\n if (state.oldName) {\n return `Empty room (was ${state.oldName})`;\n } else {\n return \"Empty room\";\n }\n }\n }\n\n /**\n * This is an internal method. Calculates the name of the room from the current\n * room state.\n * @param userId - The client's user ID. Used to filter room members\n * correctly.\n * @param ignoreRoomNameEvent - Return the implicit room name that we'd see if there\n * was no m.room.name event.\n * @returns The calculated room name.\n */\n private calculateRoomName(userId: string, ignoreRoomNameEvent = false): string {\n if (!ignoreRoomNameEvent) {\n // check for an alias, if any. for now, assume first alias is the\n // official one.\n const mRoomName = this.currentState.getStateEvents(EventType.RoomName, \"\");\n if (mRoomName?.getContent().name) {\n return this.roomNameGenerator({\n type: RoomNameType.Actual,\n name: mRoomName.getContent().name,\n });\n }\n }\n\n const alias = this.getCanonicalAlias();\n if (alias) {\n return this.roomNameGenerator({\n type: RoomNameType.Actual,\n name: alias,\n });\n }\n\n const joinedMemberCount = this.currentState.getJoinedMemberCount();\n const invitedMemberCount = this.currentState.getInvitedMemberCount();\n // -1 because these numbers include the syncing user\n let inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;\n\n // get service members (e.g. helper bots) for exclusion\n const excludedUserIds = this.getFunctionalMembers();\n\n // get members that are NOT ourselves and are actually in the room.\n let otherNames: string[] = [];\n if (this.summaryHeroes) {\n // if we have a summary, the member state events should be in the room state\n this.summaryHeroes.forEach((userId) => {\n // filter service members\n if (excludedUserIds.includes(userId)) {\n inviteJoinCount--;\n return;\n }\n const member = this.getMember(userId);\n otherNames.push(member ? member.name : userId);\n });\n } else {\n let otherMembers = this.currentState.getMembers().filter((m) => {\n return (\n m.userId !== userId &&\n (m.membership === KnownMembership.Invite || m.membership === KnownMembership.Join)\n );\n });\n otherMembers = otherMembers.filter(({ userId }) => {\n // filter service members\n if (excludedUserIds.includes(userId)) {\n inviteJoinCount--;\n return false;\n }\n return true;\n });\n // make sure members have stable order\n const collator = new Intl.Collator();\n otherMembers.sort((a, b) => collator.compare(a.userId, b.userId));\n // only 5 first members, immitate summaryHeroes\n otherMembers = otherMembers.slice(0, 5);\n otherNames = otherMembers.map((m) => m.name);\n }\n\n if (inviteJoinCount) {\n return this.roomNameGenerator({\n type: RoomNameType.Generated,\n names: otherNames,\n count: inviteJoinCount,\n });\n }\n\n const myMembership = this.getMyMembership();\n // if I have created a room and invited people through\n // 3rd party invites\n if (myMembership == KnownMembership.Join) {\n const thirdPartyInvites = this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);\n\n if (thirdPartyInvites?.length) {\n const thirdPartyNames = thirdPartyInvites.map((i) => {\n return i.getContent().display_name;\n });\n\n return this.roomNameGenerator({\n type: RoomNameType.Generated,\n subtype: \"Inviting\",\n names: thirdPartyNames,\n count: thirdPartyNames.length + 1,\n });\n }\n }\n\n // let's try to figure out who was here before\n let leftNames = otherNames;\n // if we didn't have heroes, try finding them in the room state\n if (!leftNames.length) {\n leftNames = this.currentState\n .getMembers()\n .filter((m) => {\n return (\n m.userId !== userId &&\n m.membership !== KnownMembership.Invite &&\n m.membership !== KnownMembership.Join\n );\n })\n .map((m) => m.name);\n }\n\n let oldName: string | undefined;\n if (leftNames.length) {\n oldName = this.roomNameGenerator({\n type: RoomNameType.Generated,\n names: leftNames,\n count: leftNames.length + 1,\n });\n }\n\n return this.roomNameGenerator({\n type: RoomNameType.EmptyRoom,\n oldName,\n });\n }\n\n /**\n * When we receive a new visibility change event:\n *\n * - store this visibility change alongside the timeline, in case we\n * later need to apply it to an event that we haven't received yet;\n * - if we have already received the event whose visibility has changed,\n * patch it to reflect the visibility change and inform listeners.\n */\n private applyNewVisibilityEvent(event: MatrixEvent): void {\n const visibilityChange = event.asVisibilityChange();\n if (!visibilityChange) {\n // The event is ill-formed.\n return;\n }\n\n // Ignore visibility change events that are not emitted by moderators.\n const userId = event.getSender();\n if (!userId) {\n return;\n }\n const isPowerSufficient =\n (EVENT_VISIBILITY_CHANGE_TYPE.name &&\n this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.name, userId)) ||\n (EVENT_VISIBILITY_CHANGE_TYPE.altName &&\n this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.altName, userId));\n if (!isPowerSufficient) {\n // Powerlevel is insufficient.\n return;\n }\n\n // Record this change in visibility.\n // If the event is not in our timeline and we only receive it later,\n // we may need to apply the visibility change at a later date.\n\n const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId);\n if (visibilityEventsOnOriginalEvent) {\n // It would be tempting to simply erase the latest visibility change\n // but we need to record all of the changes in case the latest change\n // is ever redacted.\n //\n // In practice, linear scans through `visibilityEvents` should be fast.\n // However, to protect against a potential DoS attack, we limit the\n // number of iterations in this loop.\n let index = visibilityEventsOnOriginalEvent.length - 1;\n const min = Math.max(\n 0,\n visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH,\n );\n for (; index >= min; --index) {\n const target = visibilityEventsOnOriginalEvent[index];\n if (target.getTs() < event.getTs()) {\n break;\n }\n }\n if (index === -1) {\n visibilityEventsOnOriginalEvent.unshift(event);\n } else {\n visibilityEventsOnOriginalEvent.splice(index + 1, 0, event);\n }\n } else {\n this.visibilityEvents.set(visibilityChange.eventId, [event]);\n }\n\n // Finally, let's check if the event is already in our timeline.\n // If so, we need to patch it and inform listeners.\n\n const originalEvent = this.findEventById(visibilityChange.eventId);\n if (!originalEvent) {\n return;\n }\n originalEvent.applyVisibilityEvent(visibilityChange);\n }\n\n private redactVisibilityChangeEvent(event: MatrixEvent): void {\n // Sanity checks.\n if (!event.isVisibilityEvent) {\n throw new Error(\"expected a visibility change event\");\n }\n const relation = event.getRelation();\n const originalEventId = relation?.event_id;\n const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId!);\n if (!visibilityEventsOnOriginalEvent) {\n // No visibility changes on the original event.\n // In particular, this change event was not recorded,\n // most likely because it was ill-formed.\n return;\n }\n const index = visibilityEventsOnOriginalEvent.findIndex((change) => change.getId() === event.getId());\n if (index === -1) {\n // This change event was not recorded, most likely because\n // it was ill-formed.\n return;\n }\n // Remove visibility change.\n visibilityEventsOnOriginalEvent.splice(index, 1);\n\n // If we removed the latest visibility change event, propagate changes.\n if (index === visibilityEventsOnOriginalEvent.length) {\n const originalEvent = this.findEventById(originalEventId!);\n if (!originalEvent) {\n return;\n }\n if (index === 0) {\n // We have just removed the only visibility change event.\n this.visibilityEvents.delete(originalEventId!);\n originalEvent.applyVisibilityEvent();\n } else {\n const newEvent = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1];\n const newVisibility = newEvent.asVisibilityChange();\n if (!newVisibility) {\n // Event is ill-formed.\n // This breaks our invariant.\n throw new Error(\"at this stage, visibility changes should be well-formed\");\n }\n originalEvent.applyVisibilityEvent(newVisibility);\n }\n }\n }\n\n /**\n * When we receive an event whose visibility has been altered by\n * a (more recent) visibility change event, patch the event in\n * place so that clients now not to display it.\n *\n * @param event - Any matrix event. If this event has at least one a\n * pending visibility change event, apply the latest visibility\n * change event.\n */\n private applyPendingVisibilityEvents(event: MatrixEvent): void {\n const visibilityEvents = this.visibilityEvents.get(event.getId()!);\n if (!visibilityEvents || visibilityEvents.length == 0) {\n // No pending visibility change in store.\n return;\n }\n const visibilityEvent = visibilityEvents[visibilityEvents.length - 1];\n const visibilityChange = visibilityEvent.asVisibilityChange();\n if (!visibilityChange) {\n return;\n }\n if (visibilityChange.visible) {\n // Events are visible by default, no need to apply a visibility change.\n // Note that we need to keep the visibility changes in `visibilityEvents`,\n // in case we later fetch an older visibility change event that is superseded\n // by `visibilityChange`.\n }\n if (visibilityEvent.getTs() < event.getTs()) {\n // Something is wrong, the visibility change cannot happen before the\n // event. Presumably an ill-formed event.\n return;\n }\n event.applyVisibilityEvent(visibilityChange);\n }\n\n /**\n * Find when a client has gained thread capabilities by inspecting the oldest\n * threaded receipt\n * @returns the timestamp of the oldest threaded receipt\n */\n public getOldestThreadedReceiptTs(): number {\n return this.oldestThreadedReceiptTs;\n }\n\n /**\n * Determines if the given user has read a particular event ID with the known\n * history of the room. This is not a definitive check as it relies only on\n * what is available to the room at the time of execution.\n *\n * @param userId - The user ID to check the read state of.\n * @param eventId - The event ID to check if the user read.\n * @returns true if the user has read the event, false otherwise.\n */\n public hasUserReadEvent(userId: string, eventId: string): boolean {\n return this.roomReceipts.hasUserReadEvent(userId, eventId);\n }\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n */\n public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {\n return this.unthreadedReceipts.get(userId);\n }\n\n /**\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n *\n * We consider a room fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n * This also detects all unread threads and applies the same logic to those\n * contexts\n */\n public fixupNotifications(userId: string): void {\n super.fixupNotifications(userId);\n\n const unreadThreads = this.getThreads().filter(\n (thread) => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0,\n );\n\n for (const thread of unreadThreads) {\n thread.fixupNotifications(userId);\n }\n }\n\n /**\n * Determine the order of two events in this room.\n *\n * In principle this should use the same order as the server, but in practice\n * this is difficult for events that were not received over the Sync API. See\n * MSC4033 for details.\n *\n * This implementation leans on the order of events within their timelines, and\n * falls back to comparing event timestamps when they are in different\n * timelines.\n *\n * See https://github.com/matrix-org/matrix-js-sdk/issues/3325 for where we are\n * tracking the work to fix this.\n *\n * @param leftEventId - the id of the first event\n * @param rightEventId - the id of the second event\n\n * @returns -1 if left \\< right, 1 if left \\> right, 0 if left == right, null if\n * we can't tell (because we can't find the events).\n */\n public compareEventOrdering(leftEventId: string, rightEventId: string): number | null {\n return compareEventOrdering(this, leftEventId, rightEventId);\n }\n\n /**\n * Return true if this room has an `m.room.encryption` state event.\n *\n * If this returns `true`, events sent to this room should be encrypted (and `MatrixClient.sendEvent` and friends\n * will encrypt outgoing events).\n */\n public hasEncryptionStateEvent(): boolean {\n return Boolean(\n this.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(EventType.RoomEncryption, \"\"),\n );\n }\n}\n\n// a map from current event status to a list of allowed next statuses\nconst ALLOWED_TRANSITIONS: Record<EventStatus, EventStatus[]> = {\n [EventStatus.ENCRYPTING]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n [EventStatus.SENDING]: [EventStatus.ENCRYPTING, EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.SENT],\n [EventStatus.QUEUED]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n [EventStatus.SENT]: [],\n [EventStatus.NOT_SENT]: [EventStatus.SENDING, EventStatus.QUEUED, EventStatus.CANCELLED],\n [EventStatus.CANCELLED]: [],\n};\n\nexport enum RoomNameType {\n EmptyRoom,\n Generated,\n Actual,\n}\n\nexport interface EmptyRoomNameState {\n type: RoomNameType.EmptyRoom;\n oldName?: string;\n}\n\nexport interface GeneratedRoomNameState {\n type: RoomNameType.Generated;\n subtype?: \"Inviting\";\n names: string[];\n count: number;\n}\n\nexport interface ActualRoomNameState {\n type: RoomNameType.Actual;\n name: string;\n}\n\nexport type RoomNameState = EmptyRoomNameState | GeneratedRoomNameState | ActualRoomNameState;\n\n// Can be overriden by IMatrixClientCreateOpts::memberNamesToRoomNameFn\nfunction memberNamesToRoomName(names: string[], count: number): string {\n const countWithoutMe = count - 1;\n if (!names.length) {\n return \"Empty room\";\n } else if (names.length === 1 && countWithoutMe <= 1) {\n return names[0];\n } else if (names.length === 2 && countWithoutMe <= 2) {\n return `${names[0]} and ${names[1]}`;\n } else {\n const plural = countWithoutMe > 1;\n if (plural) {\n return `${names[0]} and ${countWithoutMe} others`;\n } else {\n return `${names[0]} and 1 other`;\n }\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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room.js","names":["M_POLL_START","EventTimelineSet","DuplicateStrategy","Direction","EventTimeline","getHttpUriForMxc","removeElement","normalize","noUnsafeEventProps","MatrixEvent","MatrixEventEvent","EventStatus","RoomMember","RoomSummary","logger","TypedReEmitter","EventType","RoomCreateTypeField","RoomType","UNSTABLE_ELEMENT_FUNCTIONAL_USERS","EVENT_VISIBILITY_CHANGE_TYPE","RelationType","UNSIGNED_THREAD_ID_FIELD","PendingEventOrdering","Filter","RoomStateEvent","BeaconEvent","Thread","ThreadEvent","FILTER_RELATED_BY_REL_TYPES","THREAD_RELATION_TYPE","FILTER_RELATED_BY_SENDERS","ThreadFilterType","MAIN_ROOM_TIMELINE","ReceiptType","RelationsContainer","ReadReceipt","synthesizeReceipt","isPollEvent","Poll","PollEvent","RoomReceipts","compareEventOrdering","utils","KnownMembership","RoomVersionStability","KNOWN_SAFE_ROOM_VERSION","SAFE_ROOM_VERSIONS","MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH","NotificationCountType","RoomEvent","Room","constructor","roomId","client","myUserId","_this","opts","arguments","length","undefined","this","_defineProperty","Map","Infinity","thread","toStartOfTimeline","recreateEvent","_this$threadsTimeline","updateThreadRootEvent","threadsTimelineSets","hasCurrentUserParticipated","_this$threadsTimeline2","timelineSet","rootEvent","removeEvent","id","hasServerSideSupport","addLiveEvent","duplicateStrategy","Replace","fromCache","roomState","currentState","addEventToTimeline","getLiveTimeline","event","isRedaction","redactId","redacts","redactedEvent","findEventById","threadRootId","makeRedacted","isState","currentStateEvent","getStateEvents","getType","getStateKey","getId","setStateEvents","emit","Redaction","visibilityEvents","delete","isVisibilityEvent","redactVisibilityChangeEvent","setMaxListeners","reEmitter","pendingEventOrdering","Chronological","name","normalizedName","relations","on","Receipt","onReceipt","timelineSets","reEmit","getUnfilteredTimelineSet","Timeline","TimelineReset","fixUpLegacyTimelineFields","Detached","pendingEventList","store","getPendingEvents","then","events","mapper","getEventMapper","toDevice","decrypt","forEach","_ref","_asyncToGenerator","serializedEvent","setStatus","NOT_SENT","addPendingEvent","getTxnId","_x","apply","lazyLoadMembers","membersPromise","Promise","resolve","createThreadsTimelineSets","_this2","_this2$client","threadTimelineSetsPromise","supportsThreads","all","createThreadTimelineSet","My","_unused","getCreator","_createEvent$getSende","createEvent","RoomCreate","getSender","getVersion","_createEvent$getConte","getVersionWarning","warn","getContent","getRecommendedVersion","_this3","capabilities","getCapabilities","_unused2","versionCap","default","available","safeVer","Stable","result","checkVersionAgainstCapability","urgent","needsUpgrade","fetchCapabilities","e","currentVersion","log","concat","version","stableVersions","Object","keys","filter","v","includes","match","userMayUpgradeRoom","userId","maySendStateEvent","RoomTombstone","Error","removePendingEvent","eventId","removed","ev","savePendingEvents","hasPendingEvent","_this$pendingEventLis","_this$pendingEventLis2","some","getPendingEvent","_this$pendingEventLis3","_this$pendingEventLis4","find","timeline","getEvents","getLastActiveTimestamp","lastEvent","getTs","Number","MIN_SAFE_INTEGER","getLastLiveEvent","_lastRoomEvent$getTs","_lastThreadEvent$getT","roomEvents","lastRoomEvent","lastThread","getLastThread","lastThreadEvent","getThreads","reduce","_threadEvent$getTs","_lastThreadEvent$getT2","threadEvent","getMyMembership","_this$selfMembership","selfMembership","Leave","getDMInviter","me","getMember","Invite","memberCount","getInvitedAndJoinedMemberCount","_this$summaryHeroes","summaryHeroes","guessDMUserId","inviterId","Array","isArray","members","getMembers","anyMember","m","getFunctionalMembers","mFunctionalMembers","service_members","getAvatarFallbackMember","_this$summaryHeroes2","functionalMembers","nonFunctionalMemberCount","membership","nonFunctionalHeroes","h","hasHeroes","availableMember","map","member","nonFunctionalMembers","availableUser","getUser","user","updateMyMembership","prevMembership","cleanupAfterLeaving","MyMembership","loadMembersFromServer","_this4","lastSyncToken","getSyncToken","response","chunk","loadMembers","_this5","fromServer","rawMembersEvents","getOutOfBandMembers","hasEncryptionStateEvent","memberEvents","membersLoaded","outOfBandMembersReady","loadMembersIfNeeded","markOutOfBandMembersStarted","inMemoryUpdate","setOutOfBandMembers","catch","err","markOutOfBandMembersFailed","oobMembers","isOutOfBand","_m$events$member","error","clearLoadedMembersIfNeeded","_this6","clearOutOfBandMembers","refreshLiveTimeline","_this7","liveTimelineBefore","forwardPaginationToken","getPaginationToken","FORWARDS","backwardPaginationToken","BACKWARDS","eventsBefore","mostRecentEventInTimeline","toString","newTimeline","getLatestTimeline","resetLiveTimeline","TimelineRefresh","getEventTimeline","liveTimeline","Forward","Backward","setPaginationToken","setLiveTimeline","setTimelineNeedsRefresh","backPaginationToken","threads","values","previousOldState","oldState","previousCurrentState","getState","OldStateUpdated","CurrentStateUpdated","stopReEmitting","Events","Members","NewMember","Update","Marker","New","Destroy","LivenessChange","clearNotificationsOnReceipt","threadIds","hasUnthreadedReceipt","content","receiptGroup","receiptType","userReceipt","entries","isSupportedReceiptType","singleReceipt","typedSingleReceipt","getUserId","thread_id","push","getThreadUnreadNotificationCount","Total","Highlight","threadId","_this$getThread","maxHistory","getThread","highlightCount","i","_pushActions$tweaks","hasUserReadEvent","pushActions","getPushActionsForEvent","tweaks","highlight","setUnreadNotificationCount","setThreadUnreadNotificationCount","getTimelineSets","getTimelineForEvent","findThreadForEvent","addTimeline","value","timelineNeedsRefresh","getTimelineNeedsRefresh","getUnreadNotificationCount","type","count","getRoomUnreadNotificationCount","threadNotification","threadNotifications","_threadNotification$t","getUnreadCountForEventContext","_ref2","isThreadEvent","isThreadRoot","_this$notificationCou","notificationCounts","_this$threadNotificat","_this$threadNotificat2","get","hasThreadUnreadNotification","notification","_notification$highlig","_notification$total","total","_this$threadNotificat3","_this$threadNotificat4","_objectSpread","set","UnreadNotifications","threadsAggregateNotificationType","_threadNotification$h","_threadNotification$t2","resetThreadUnreadNotificationCountFromSync","exceptThreadIds","isEncrypted","notifs","setUnread","setSummary","summary","heroes","joinedCount","invitedCount","isInteger","setJoinedMemberCount","setInvitedMemberCount","Summary","setBlacklistUnverifiedDevices","blacklistUnverifiedDevices","getBlacklistUnverifiedDevices","getAvatarUrl","baseUrl","width","height","resizeMethod","allowDefault","roomAvatarEvent","RoomAvatar","mainUrl","url","getMxcAvatarUrl","_this$currentState$ge","getCanonicalAlias","canonicalAlias","RoomCanonicalAlias","alias","getAltAliases","alt_aliases","addEventsToTimeline","paginationToken","getTimelineSet","_this$threads$get","from","getJoinedMembers","getMembersWithMembership","Join","getJoinedMemberCount","getInvitedMemberCount","getEncryptionTargetMembers","_this8","shouldEncryptForInvitedMembers","_ev$getContent","RoomHistoryVisibility","history_visibility","getDefaultRoomName","calculateRoomName","hasMembershipState","getOrCreateFilteredTimelineSet","prepopulateTimeline","useSyncEvents","pendingEvents","filteredTimelineSets","filterId","assign","unfilteredLiveTimeline","getNeighbouringTimeline","livePaginationToken","getThreadListFilter","_arguments","_this9","filterType","All","definition","room","setDefinition","getOrCreateFilter","_this10","hasServerSideListSupport","_ref3","currentUserParticipated","addEvent","processThreadRoots","setEventMetadata","createThread","fetchRoomThreads","_this11","threadsReady","fetchRoomThreadList","allThreadsFilter","createMessagesRequest","MAX_SAFE_INTEGER","threadRoots","sort","eventA","eventB","threadAMetadata","getServerAggregatedRelation","threadBMetadata","latest_event","origin_server_ts","_this11$threadsTimeli","Ignore","threadRelationship","current_user_participated","_this11$threadsTimeli2","NewReply","onThreadReply","onThreadUpdate","Delete","onThreadDelete","processPollEvents","_this12","processPollEvent","_this13","matches","poll","polls","once","BeforeRedaction","_unused3","relationEventId","has","onNewRelation","_this14","end","createThreadListMessagesRequest","threadListType","getFilter","matrixEvents","updateThreadRootEvents","_timeline$getEvents","roomEvent","it","clearEventMetadata","debug","removeFilteredTimelineSet","indexOf","splice","eventShouldLiveIn","roots","_this$client","shouldLiveInRoom","shouldLiveInThread","isThreadRelation","isRelation","parentEventId","getAssociatedId","parentEvent","_this$findEventById","replyEventId","addThreadedEvents","addEvents","_this$findEventById2","processThreadedEvents","applyRedaction","eventsByThread","_eventsByThread","_ref4","threadEvents","_this$cachedThreadRea","relatedEvents","getAllChildEventsForEvent","receipts","cachedThreadReadReceipts","initialEventsFetched","processLiveEvent","applyNewVisibilityEvent","applyPendingVisibilityEvents","txnId","getUnsigned","transaction_id","tid","localEvent","txnToEvent","unsigned","setUnsigned","addLiveEventOptions","timelineWasEmpty","sender","RoomRedaction","addReceipt","Read","status","SENDING","aggregateNonLiveRelation","markLocallyRedacted","filterRoomTimeline","LocalEchoUpdated","txn_id","isEventEncrypted","RoomMessageEncrypted","isRoomEncrypted","setPendingEvents","aggregateChildEvent","getEventForTxnId","handleRemoteEcho","remoteEvent","oldEventId","newEventId","oldStatus","updatePendingEvent","newStatus","getRoomId","SENT","remoteTxnId","allowed","ALLOWED_TRANSITIONS","replaceLocalEventId","replaceEventId","CANCELLED","removedEvent","revertRedactionLocalEcho","redactionEvent","unmarkLocallyRedacted","RedactionCancelled","assertTimelineSetsAreLive","addLiveEvents","_this15","findThreadRoots","options","neighbouringEvents","_eventsByThread$threa","existingEvent","fetchRoomEvent","add","_ref5","partitionThreadedEvents","ROOM","THREAD","UNKNOWN_RELATION","memo","setThreadId","Set","synthetic","roomReceipts","_receipt$thread_id","_this$unthreadedRecei","_this$unthreadedRecei2","receipt","receiptForMainTimeline","receiptDestination","addReceiptToStructure","isInitialSyncComplete","_this$cachedThreadRea2","ts","oldestThreadedReceiptTs","unthreadedReceipts","addEphemeralEvents","Typing","setTypingEvent","removeEvents","eventIds","removedAny","recalculate","membershipEvent","strippedStateEvents","invite_room_state","strippedEvent","state_key","event_id","Date","now","room_id","oldName","title","Name","addTags","tags","Tags","addAccountData","eventType","accountData","AccountData","getAccountData","maySendMessage","maySendEvent","RoomMessage","canInvite","powerLevelsEvent","RoomPowerLevels","powerLevels","invite","powerLevel","getJoinRule","getHistoryVisibility","getGuestAccess","getTypeWarning","isSpaceRoom","Space","isCallRoom","UnstableCall","isElementVideoRoom","ElementVideo","findPredecessor","msc3946ProcessDynamicPredecessor","roomNameGenerator","state","RoomNameType","Actual","Generated","subtype","memberNamesToRoomName","names","EmptyRoom","ignoreRoomNameEvent","mRoomName","RoomName","joinedMemberCount","invitedMemberCount","inviteJoinCount","excludedUserIds","otherNames","otherMembers","_ref6","collator","Intl","Collator","a","b","compare","slice","myMembership","thirdPartyInvites","RoomThirdPartyInvite","thirdPartyNames","display_name","leftNames","visibilityChange","asVisibilityChange","isPowerSufficient","altName","visibilityEventsOnOriginalEvent","index","min","Math","max","target","unshift","originalEvent","applyVisibilityEvent","relation","getRelation","originalEventId","findIndex","change","newEvent","newVisibility","visibilityEvent","visible","getOldestThreadedReceiptTs","getLastUnthreadedReceiptFor","fixupNotifications","unreadThreads","leftEventId","rightEventId","_this$getLiveTimeline","Boolean","RoomEncryption","ENCRYPTING","QUEUED","countWithoutMe","plural"],"sources":["../../src/models/room.ts"],"sourcesContent":["/*\nCopyright 2015 - 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { M_POLL_START, Optional } from \"matrix-events-sdk\";\n\nimport {\n EventTimelineSet,\n DuplicateStrategy,\n IAddLiveEventOptions,\n EventTimelineSetHandlerMap,\n} from \"./event-timeline-set.ts\";\nimport { Direction, EventTimeline } from \"./event-timeline.ts\";\nimport { getHttpUriForMxc } from \"../content-repo.ts\";\nimport { removeElement } from \"../utils.ts\";\nimport { normalize, noUnsafeEventProps } from \"../utils.ts\";\nimport { IEvent, IThreadBundledRelationship, MatrixEvent, MatrixEventEvent, MatrixEventHandlerMap } from \"./event.ts\";\nimport { EventStatus } from \"./event-status.ts\";\nimport { RoomMember } from \"./room-member.ts\";\nimport { IRoomSummary, RoomSummary } from \"./room-summary.ts\";\nimport { logger } from \"../logger.ts\";\nimport { TypedReEmitter } from \"../ReEmitter.ts\";\nimport {\n EventType,\n RoomCreateTypeField,\n RoomType,\n UNSTABLE_ELEMENT_FUNCTIONAL_USERS,\n EVENT_VISIBILITY_CHANGE_TYPE,\n RelationType,\n UNSIGNED_THREAD_ID_FIELD,\n} from \"../@types/event.ts\";\nimport { MatrixClient, PendingEventOrdering } from \"../client.ts\";\nimport { GuestAccess, HistoryVisibility, JoinRule, ResizeMethod } from \"../@types/partials.ts\";\nimport { Filter, IFilterDefinition } from \"../filter.ts\";\nimport { RoomState, RoomStateEvent, RoomStateEventHandlerMap } from \"./room-state.ts\";\nimport { BeaconEvent, BeaconEventHandlerMap } from \"./beacon.ts\";\nimport {\n Thread,\n ThreadEvent,\n ThreadEventHandlerMap as ThreadHandlerMap,\n FILTER_RELATED_BY_REL_TYPES,\n THREAD_RELATION_TYPE,\n FILTER_RELATED_BY_SENDERS,\n ThreadFilterType,\n} from \"./thread.ts\";\nimport {\n CachedReceiptStructure,\n MAIN_ROOM_TIMELINE,\n Receipt,\n ReceiptContent,\n ReceiptType,\n} from \"../@types/read_receipts.ts\";\nimport { IStateEventWithRoomId } from \"../@types/search.ts\";\nimport { RelationsContainer } from \"./relations-container.ts\";\nimport { ReadReceipt, synthesizeReceipt } from \"./read-receipt.ts\";\nimport { isPollEvent, Poll, PollEvent } from \"./poll.ts\";\nimport { RoomReceipts } from \"./room-receipts.ts\";\nimport { compareEventOrdering } from \"./compare-event-ordering.ts\";\nimport * as utils from \"../utils.ts\";\nimport { KnownMembership, Membership } from \"../@types/membership.ts\";\nimport { Capabilities, IRoomVersionsCapability, RoomVersionStability } from \"../serverCapabilities.ts\";\n\n// These constants are used as sane defaults when the homeserver doesn't support\n// the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be\n// the same as the common default room version whereas SAFE_ROOM_VERSIONS are the\n// room versions which are considered okay for people to run without being asked\n// to upgrade (ie: \"stable\"). Eventually, we should remove these when all homeservers\n// return an m.room_versions capability.\nexport const KNOWN_SAFE_ROOM_VERSION = \"10\";\nconst SAFE_ROOM_VERSIONS = [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"];\n\ninterface IOpts {\n /**\n * Controls where pending messages appear in a room's timeline.\n * If \"<b>chronological</b>\", messages will appear in the timeline when the call to `sendEvent` was made.\n * If \"<b>detached</b>\", pending messages will appear in a separate list,\n * accessible via {@link Room#getPendingEvents}.\n * Default: \"chronological\".\n */\n pendingEventOrdering?: PendingEventOrdering;\n /**\n * Set to true to enable improved timeline support.\n */\n timelineSupport?: boolean;\n lazyLoadMembers?: boolean;\n}\n\nexport interface IRecommendedVersion {\n version: string;\n needsUpgrade: boolean;\n urgent: boolean;\n}\n\n// When inserting a visibility event affecting event `eventId`, we\n// need to scan through existing visibility events for `eventId`.\n// In theory, this could take an unlimited amount of time if:\n//\n// - the visibility event was sent by a moderator; and\n// - `eventId` already has many visibility changes (usually, it should\n// be 2 or less); and\n// - for some reason, the visibility changes are received out of order\n// (usually, this shouldn't happen at all).\n//\n// For this reason, we limit the number of events to scan through,\n// expecting that a broken visibility change for a single event in\n// an extremely uncommon case (possibly a DoS) is a small\n// price to pay to keep matrix-js-sdk responsive.\nconst MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30;\n\nexport type NotificationCount = Partial<Record<NotificationCountType, number>>;\n\nexport enum NotificationCountType {\n Highlight = \"highlight\",\n Total = \"total\",\n}\n\nexport interface ICreateFilterOpts {\n // Populate the filtered timeline with already loaded events in the room\n // timeline. Useful to disable for some filters that can't be achieved by the\n // client in an efficient manner\n prepopulateTimeline?: boolean;\n useSyncEvents?: boolean;\n pendingEvents?: boolean;\n}\n\nexport enum RoomEvent {\n MyMembership = \"Room.myMembership\",\n Tags = \"Room.tags\",\n AccountData = \"Room.accountData\",\n Receipt = \"Room.receipt\",\n Name = \"Room.name\",\n Redaction = \"Room.redaction\",\n RedactionCancelled = \"Room.redactionCancelled\",\n LocalEchoUpdated = \"Room.localEchoUpdated\",\n Timeline = \"Room.timeline\",\n TimelineReset = \"Room.timelineReset\",\n TimelineRefresh = \"Room.TimelineRefresh\",\n OldStateUpdated = \"Room.OldStateUpdated\",\n CurrentStateUpdated = \"Room.CurrentStateUpdated\",\n HistoryImportedWithinTimeline = \"Room.historyImportedWithinTimeline\",\n UnreadNotifications = \"Room.UnreadNotifications\",\n Summary = \"Room.Summary\",\n}\n\nexport type RoomEmittedEvents =\n | RoomEvent\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker\n | ThreadEvent.New\n | ThreadEvent.Update\n | ThreadEvent.NewReply\n | ThreadEvent.Delete\n | MatrixEventEvent.BeforeRedaction\n | BeaconEvent.New\n | BeaconEvent.Update\n | BeaconEvent.Destroy\n | BeaconEvent.LivenessChange\n | PollEvent.New;\n\nexport type RoomEventHandlerMap = {\n /**\n * Fires when the logged in user's membership in the room is updated.\n *\n * @param room - The room in which the membership has been updated\n * @param membership - The new membership value\n * @param prevMembership - The previous membership value\n */\n [RoomEvent.MyMembership]: (room: Room, membership: Membership, prevMembership?: Membership) => void;\n /**\n * Fires whenever a room's tags are updated.\n * @param event - The tags event\n * @param room - The room whose Room.tags was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.tags\", function(event, room){\n * var newTags = event.getContent().tags;\n * if (newTags[\"favourite\"]) showStar(room);\n * });\n * ```\n */\n [RoomEvent.Tags]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires whenever a room's account_data is updated.\n * @param event - The account_data event\n * @param room - The room whose account_data was updated.\n * @param prevEvent - The event being replaced by\n * the new account data, if known.\n * @example\n * ```\n * matrixClient.on(\"Room.accountData\", function(event, room, oldEvent){\n * if (event.getType() === \"m.room.colorscheme\") {\n * applyColorScheme(event.getContents());\n * }\n * });\n * ```\n */\n [RoomEvent.AccountData]: (event: MatrixEvent, room: Room, prevEvent?: MatrixEvent) => void;\n /**\n * Fires whenever a receipt is received for a room\n * @param event - The receipt event\n * @param room - The room whose receipts was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.receipt\", function(event, room){\n * var receiptContent = event.getContent();\n * });\n * ```\n */\n [RoomEvent.Receipt]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires whenever the name of a room is updated.\n * @param room - The room whose Room.name was updated.\n * @example\n * ```\n * matrixClient.on(\"Room.name\", function(room){\n * var newName = room.name;\n * });\n * ```\n */\n [RoomEvent.Name]: (room: Room) => void;\n /**\n * Fires when an event we had previously received is redacted.\n *\n * (Note this is *not* fired when the redaction happens before we receive the\n * event).\n *\n * @param event - The matrix redaction event\n * @param room - The room containing the redacted event\n * @param threadId - The thread containing the redacted event (before it was redacted)\n */\n [RoomEvent.Redaction]: (event: MatrixEvent, room: Room, threadId?: string) => void;\n /**\n * Fires when an event that was previously redacted isn't anymore.\n * This happens when the redaction couldn't be sent and\n * was subsequently cancelled by the user. Redactions have a local echo\n * which is undone in this scenario.\n *\n * @param event - The matrix redaction event that was cancelled.\n * @param room - The room containing the unredacted event\n */\n [RoomEvent.RedactionCancelled]: (event: MatrixEvent, room: Room) => void;\n /**\n * Fires when the status of a transmitted event is updated.\n *\n * <p>When an event is first transmitted, a temporary copy of the event is\n * inserted into the timeline, with a temporary event id, and a status of\n * 'SENDING'.\n *\n * <p>Once the echo comes back from the server, the content of the event\n * (MatrixEvent.event) is replaced by the complete event from the homeserver,\n * thus updating its event id, as well as server-generated fields such as the\n * timestamp. Its status is set to null.\n *\n * <p>Once the /send request completes, if the remote echo has not already\n * arrived, the event is updated with a new event id and the status is set to\n * 'SENT'. The server-generated fields are of course not updated yet.\n *\n * <p>If the /send fails, In this case, the event's status is set to\n * 'NOT_SENT'. If it is later resent, the process starts again, setting the\n * status to 'SENDING'. Alternatively, the message may be cancelled, which\n * removes the event from the room, and sets the status to 'CANCELLED'.\n *\n * <p>This event is raised to reflect each of the transitions above.\n *\n * @param event - The matrix event which has been updated\n *\n * @param room - The room containing the redacted event\n *\n * @param oldEventId - The previous event id (the temporary event id,\n * except when updating a successfully-sent event when its echo arrives)\n *\n * @param oldStatus - The previous event status.\n */\n [RoomEvent.LocalEchoUpdated]: (\n event: MatrixEvent,\n room: Room,\n oldEventId?: string,\n oldStatus?: EventStatus | null,\n ) => void;\n [RoomEvent.OldStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;\n [RoomEvent.CurrentStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;\n [RoomEvent.HistoryImportedWithinTimeline]: (markerEvent: MatrixEvent, room: Room) => void;\n [RoomEvent.UnreadNotifications]: (unreadNotifications?: NotificationCount, threadId?: string) => void;\n [RoomEvent.TimelineRefresh]: (room: Room, eventTimelineSet: EventTimelineSet) => void;\n /**\n * Fires when a new room summary is returned by `/sync`.\n *\n * See https://spec.matrix.org/v1.8/client-server-api/#_matrixclientv3sync_roomsummary\n * for full details\n * @param summary - the room summary object\n */\n [RoomEvent.Summary]: (summary: IRoomSummary) => void;\n [ThreadEvent.New]: (thread: Thread, toStartOfTimeline: boolean) => void;\n /**\n * Fires when a new poll instance is added to the room state\n * @param poll - the new poll\n */\n [PollEvent.New]: (poll: Poll) => void;\n} & Pick<ThreadHandlerMap, ThreadEvent.Update | ThreadEvent.NewReply | ThreadEvent.Delete> &\n EventTimelineSetHandlerMap &\n Pick<MatrixEventHandlerMap, MatrixEventEvent.BeforeRedaction> &\n Pick<\n RoomStateEventHandlerMap,\n | RoomStateEvent.Events\n | RoomStateEvent.Members\n | RoomStateEvent.NewMember\n | RoomStateEvent.Update\n | RoomStateEvent.Marker\n | BeaconEvent.New\n > &\n Pick<BeaconEventHandlerMap, BeaconEvent.Update | BeaconEvent.Destroy | BeaconEvent.LivenessChange>;\n\nexport class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {\n public readonly reEmitter: TypedReEmitter<RoomEmittedEvents, RoomEventHandlerMap>;\n private txnToEvent: Map<string, MatrixEvent> = new Map(); // Pending in-flight requests { string: MatrixEvent }\n private notificationCounts: NotificationCount = {};\n private readonly threadNotifications = new Map<string, NotificationCount>();\n public readonly cachedThreadReadReceipts = new Map<string, CachedReceiptStructure[]>();\n // Useful to know at what point the current user has started using threads in this room\n private oldestThreadedReceiptTs = Infinity;\n /**\n * A record of the latest unthread receipts per user\n * This is useful in determining whether a user has read a thread or not\n */\n private unthreadedReceipts = new Map<string, Receipt>();\n private readonly timelineSets: EventTimelineSet[];\n public readonly polls: Map<string, Poll> = new Map<string, Poll>();\n\n /**\n * Empty array if the timeline sets have not been initialised. After initialisation:\n * 0: All threads\n * 1: Threads the current user has participated in\n */\n public readonly threadsTimelineSets: [] | [EventTimelineSet, EventTimelineSet] = [];\n\n // any filtered timeline sets we're maintaining for this room\n private readonly filteredTimelineSets: Record<string, EventTimelineSet> = {}; // filter_id: timelineSet\n private timelineNeedsRefresh = false;\n private readonly pendingEventList?: MatrixEvent[];\n // read by megolm via getter; boolean value - null indicates \"use global value\"\n private blacklistUnverifiedDevices?: boolean;\n private selfMembership?: Membership;\n private summaryHeroes: string[] | null = null;\n // flags to stop logspam about missing m.room.create events\n private getTypeWarning = false;\n private getVersionWarning = false;\n private membersPromise?: Promise<boolean>;\n\n // XXX: These should be read-only\n /**\n * The human-readable display name for this room.\n */\n public name: string;\n /**\n * The un-homoglyphed name for this room.\n */\n public normalizedName: string;\n /**\n * Dict of room tags; the keys are the tag name and the values\n * are any metadata associated with the tag - e.g. `{ \"fav\" : { order: 1 } }`\n */\n public tags: Record<string, Record<string, any>> = {}; // $tagName: { $metadata: $value }\n /**\n * accountData Dict of per-room account_data events; the keys are the\n * event type and the values are the events.\n */\n public accountData: Map<string, MatrixEvent> = new Map(); // $eventType: $event\n /**\n * The room summary.\n */\n public summary: RoomSummary | null = null;\n /**\n * oldState The state of the room at the time of the oldest event in the live timeline.\n *\n * @deprecated Present for backwards compatibility.\n * Use getLiveTimeline().getState(EventTimeline.BACKWARDS) instead\n */\n public oldState!: RoomState;\n /**\n * currentState The state of the room at the time of the newest event in the timeline.\n *\n * @deprecated Present for backwards compatibility.\n * Use getLiveTimeline().getState(EventTimeline.FORWARDS) instead.\n */\n public currentState!: RoomState;\n\n public readonly relations;\n\n /**\n * A collection of events known by the client\n * This is not a comprehensive list of the threads that exist in this room\n */\n private threads = new Map<string, Thread>();\n\n /**\n * A mapping of eventId to all visibility changes to apply\n * to the event, by chronological order, as per\n * https://github.com/matrix-org/matrix-doc/pull/3531\n *\n * # Invariants\n *\n * - within each list, all events are classed by\n * chronological order;\n * - all events are events such that\n * `asVisibilityEvent()` returns a non-null `IVisibilityChange`;\n * - within each list with key `eventId`, all events\n * are in relation to `eventId`.\n *\n * @experimental\n */\n private visibilityEvents = new Map<string, MatrixEvent[]>();\n\n /**\n * The latest receipts (synthetic and real) for each user in each thread\n * (and unthreaded).\n */\n private roomReceipts = new RoomReceipts(this);\n\n /**\n * Construct a new Room.\n *\n * <p>For a room, we store an ordered sequence of timelines, which may or may not\n * be continuous. Each timeline lists a series of events, as well as tracking\n * the room state at the start and the end of the timeline. It also tracks\n * forward and backward pagination tokens, as well as containing links to the\n * next timeline in the sequence.\n *\n * <p>There is one special timeline - the 'live' timeline, which represents the\n * timeline to which events are being added in real-time as they are received\n * from the /sync API. Note that you should not retain references to this\n * timeline - even if it is the current timeline right now, it may not remain\n * so if the server gives us a timeline gap in /sync.\n *\n * <p>In order that we can find events from their ids later, we also maintain a\n * map from event_id to timeline and index.\n *\n * @param roomId - Required. The ID of this room.\n * @param client - Required. The client, used to lazy load members.\n * @param myUserId - Required. The ID of the syncing user.\n * @param opts - Configuration options\n */\n public constructor(\n public readonly roomId: string,\n public readonly client: MatrixClient,\n public readonly myUserId: string,\n private readonly opts: IOpts = {},\n ) {\n super();\n\n // In some cases, we add listeners for every displayed Matrix event, so it's\n // common to have quite a few more than the default limit.\n this.setMaxListeners(100);\n this.reEmitter = new TypedReEmitter(this);\n\n opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological;\n\n this.name = roomId;\n this.normalizedName = roomId;\n\n this.relations = new RelationsContainer(this.client, this);\n\n // Listen to our own receipt event as a more modular way of processing our own\n // receipts. No need to remove the listener: it's on ourself anyway.\n this.on(RoomEvent.Receipt, this.onReceipt);\n\n // all our per-room timeline sets. the first one is the unfiltered ones;\n // the subsequent ones are the filtered ones in no particular order.\n this.timelineSets = [new EventTimelineSet(this, opts)];\n this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n\n this.fixUpLegacyTimelineFields();\n\n if (this.opts.pendingEventOrdering === PendingEventOrdering.Detached) {\n this.pendingEventList = [];\n this.client.store.getPendingEvents(this.roomId).then((events) => {\n const mapper = this.client.getEventMapper({\n toDevice: false,\n decrypt: false,\n });\n events.forEach(async (serializedEvent: Partial<IEvent>) => {\n const event = mapper(serializedEvent);\n event.setStatus(EventStatus.NOT_SENT);\n this.addPendingEvent(event, event.getTxnId()!);\n });\n });\n }\n\n // awaited by getEncryptionTargetMembers while room members are loading\n if (!this.opts.lazyLoadMembers) {\n this.membersPromise = Promise.resolve(false);\n } else {\n this.membersPromise = undefined;\n }\n }\n\n private threadTimelineSetsPromise: Promise<[EventTimelineSet, EventTimelineSet]> | null = null;\n public async createThreadsTimelineSets(): Promise<[EventTimelineSet, EventTimelineSet] | null> {\n if (this.threadTimelineSetsPromise) {\n return this.threadTimelineSetsPromise;\n }\n\n if (this.client?.supportsThreads()) {\n try {\n this.threadTimelineSetsPromise = Promise.all([\n this.createThreadTimelineSet(),\n this.createThreadTimelineSet(ThreadFilterType.My),\n ]);\n const timelineSets = await this.threadTimelineSetsPromise;\n this.threadsTimelineSets[0] = timelineSets[0];\n this.threadsTimelineSets[1] = timelineSets[1];\n return timelineSets;\n } catch {\n this.threadTimelineSetsPromise = null;\n return null;\n }\n }\n return null;\n }\n\n /**\n * Gets the creator of the room\n * @returns The creator of the room, or null if it could not be determined\n */\n public getCreator(): string | null {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n return createEvent?.getSender() ?? null;\n }\n\n /**\n * Gets the version of the room\n * @returns The version of the room, or null if it could not be determined\n */\n public getVersion(): string {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getVersionWarning) {\n logger.warn(\"[getVersion] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getVersionWarning = true;\n }\n return \"1\";\n }\n return createEvent.getContent()[\"room_version\"] ?? \"1\";\n }\n\n /**\n * Determines the recommended room version for the room. This returns an\n * object with 3 properties: `version` as the new version the\n * room should be upgraded to (may be the same as the current version);\n * `needsUpgrade` to indicate if the room actually can be\n * upgraded (ie: does the current version not match?); and `urgent`\n * to indicate if the new version patches a vulnerability in a previous\n * version.\n * @returns\n * Resolves to the version the room should be upgraded to.\n */\n public async getRecommendedVersion(): Promise<IRecommendedVersion> {\n let capabilities: Capabilities = {};\n try {\n capabilities = await this.client.getCapabilities();\n } catch {}\n let versionCap = capabilities[\"m.room_versions\"];\n if (!versionCap) {\n versionCap = {\n default: KNOWN_SAFE_ROOM_VERSION,\n available: {},\n };\n for (const safeVer of SAFE_ROOM_VERSIONS) {\n versionCap.available[safeVer] = RoomVersionStability.Stable;\n }\n }\n\n let result = this.checkVersionAgainstCapability(versionCap);\n if (result.urgent && result.needsUpgrade) {\n // Something doesn't feel right: we shouldn't need to update\n // because the version we're on should be in the protocol's\n // namespace. This usually means that the server was updated\n // before the client was, making us think the newest possible\n // room version is not stable. As a solution, we'll refresh\n // the capability we're using to determine this.\n logger.warn(\n \"Refreshing room version capability because the server looks \" +\n \"to be supporting a newer room version we don't know about.\",\n );\n\n try {\n capabilities = await this.client.fetchCapabilities();\n } catch (e) {\n logger.warn(\"Failed to refresh room version capabilities\", e);\n }\n versionCap = capabilities[\"m.room_versions\"];\n if (!versionCap) {\n logger.warn(\"No room version capability - assuming upgrade required.\");\n return result;\n } else {\n result = this.checkVersionAgainstCapability(versionCap);\n }\n }\n\n return result;\n }\n\n private checkVersionAgainstCapability(versionCap: IRoomVersionsCapability): IRecommendedVersion {\n const currentVersion = this.getVersion();\n logger.log(`[${this.roomId}] Current version: ${currentVersion}`);\n logger.log(`[${this.roomId}] Version capability: `, versionCap);\n\n const result: IRecommendedVersion = {\n version: currentVersion,\n needsUpgrade: false,\n urgent: false,\n };\n\n // If the room is on the default version then nothing needs to change\n if (currentVersion === versionCap.default) return result;\n\n const stableVersions = Object.keys(versionCap.available).filter((v) => versionCap.available[v] === \"stable\");\n\n // Check if the room is on an unstable version. We determine urgency based\n // off the version being in the Matrix spec namespace or not (if the version\n // is in the current namespace and unstable, the room is probably vulnerable).\n if (!stableVersions.includes(currentVersion)) {\n result.version = versionCap.default;\n result.needsUpgrade = true;\n result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);\n if (result.urgent) {\n logger.warn(`URGENT upgrade required on ${this.roomId}`);\n } else {\n logger.warn(`Non-urgent upgrade required on ${this.roomId}`);\n }\n return result;\n }\n\n // The room is on a stable, but non-default, version by this point.\n // No upgrade needed.\n return result;\n }\n\n /**\n * Determines whether the given user is permitted to perform a room upgrade\n * @param userId - The ID of the user to test against\n * @returns True if the given user is permitted to upgrade the room\n */\n public userMayUpgradeRoom(userId: string): boolean {\n return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);\n }\n\n /**\n * Get the list of pending sent events for this room\n *\n * @returns A list of the sent events\n * waiting for remote echo.\n *\n * @throws If `opts.pendingEventOrdering` was not 'detached'\n */\n public getPendingEvents(): MatrixEvent[] {\n if (!this.pendingEventList) {\n throw new Error(\n \"Cannot call getPendingEvents with pendingEventOrdering == \" + this.opts.pendingEventOrdering,\n );\n }\n\n return this.pendingEventList;\n }\n\n /**\n * Removes a pending event for this room\n *\n * @returns True if an element was removed.\n */\n public removePendingEvent(eventId: string): boolean {\n if (!this.pendingEventList) {\n throw new Error(\n \"Cannot call removePendingEvent with pendingEventOrdering == \" + this.opts.pendingEventOrdering,\n );\n }\n\n const removed = removeElement(\n this.pendingEventList,\n function (ev) {\n return ev.getId() == eventId;\n },\n false,\n );\n\n this.savePendingEvents();\n\n return removed;\n }\n\n /**\n * Check whether the pending event list contains a given event by ID.\n * If pending event ordering is not \"detached\" then this returns false.\n *\n * @param eventId - The event ID to check for.\n */\n public hasPendingEvent(eventId: string): boolean {\n return this.pendingEventList?.some((event) => event.getId() === eventId) ?? false;\n }\n\n /**\n * Get a specific event from the pending event list, if configured, null otherwise.\n *\n * @param eventId - The event ID to check for.\n */\n public getPendingEvent(eventId: string): MatrixEvent | null {\n return this.pendingEventList?.find((event) => event.getId() === eventId) ?? null;\n }\n\n /**\n * Get the live unfiltered timeline for this room.\n *\n * @returns live timeline\n */\n public getLiveTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().getLiveTimeline();\n }\n\n /**\n * The live event timeline for this room, with the oldest event at index 0.\n *\n * @deprecated Present for backwards compatibility.\n * Use getLiveTimeline().getEvents() instead\n */\n public get timeline(): MatrixEvent[] {\n return this.getLiveTimeline().getEvents();\n }\n\n /**\n * Get the timestamp of the last message in the room\n *\n * @returns the timestamp of the last message in the room\n */\n public getLastActiveTimestamp(): number {\n const timeline = this.getLiveTimeline();\n const events = timeline.getEvents();\n if (events.length) {\n const lastEvent = events[events.length - 1];\n return lastEvent.getTs();\n } else {\n return Number.MIN_SAFE_INTEGER;\n }\n }\n\n /**\n * Returns the last live event of this room.\n * \"last\" means latest timestamp.\n * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.\n * Unfortunately, this information is currently not available in the client.\n * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.\n * \"live of this room\" means from all live timelines: the room and the threads.\n *\n * @returns MatrixEvent if there is a last event; else undefined.\n */\n public getLastLiveEvent(): MatrixEvent | undefined {\n const roomEvents = this.getLiveTimeline().getEvents();\n const lastRoomEvent = roomEvents[roomEvents.length - 1] as MatrixEvent | undefined;\n const lastThread = this.getLastThread();\n\n if (!lastThread) return lastRoomEvent;\n\n const lastThreadEvent = lastThread.events[lastThread.events.length - 1];\n\n return (lastRoomEvent?.getTs() ?? 0) > (lastThreadEvent?.getTs() ?? 0) ? lastRoomEvent : lastThreadEvent;\n }\n\n /**\n * Returns the last thread of this room.\n * \"last\" means latest timestamp of the last thread event.\n * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.\n * Unfortunately, this information is currently not available in the client.\n * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.\n *\n * @returns the thread with the most recent event in its live time line. undefined if there is no thread.\n */\n public getLastThread(): Thread | undefined {\n return this.getThreads().reduce<Thread | undefined>((lastThread: Thread | undefined, thread: Thread) => {\n if (!lastThread) return thread;\n\n const threadEvent = thread.events[thread.events.length - 1];\n const lastThreadEvent = lastThread.events[lastThread.events.length - 1];\n\n if ((threadEvent?.getTs() ?? 0) >= (lastThreadEvent?.getTs() ?? 0)) {\n // Last message of current thread is newer → new last thread.\n // Equal also means newer, because it was added to the thread map later.\n return thread;\n }\n\n return lastThread;\n }, undefined);\n }\n\n /**\n * @returns the membership type (join | leave | invite | knock) for the logged in user\n */\n public getMyMembership(): Membership {\n return this.selfMembership ?? KnownMembership.Leave;\n }\n\n /**\n * If this room is a DM we're invited to,\n * try to find out who invited us\n * @returns user id of the inviter\n */\n public getDMInviter(): string | undefined {\n const me = this.getMember(this.myUserId);\n if (me) {\n return me.getDMInviter();\n }\n\n if (this.selfMembership === KnownMembership.Invite) {\n // fall back to summary information\n const memberCount = this.getInvitedAndJoinedMemberCount();\n if (memberCount === 2) {\n return this.summaryHeroes?.[0];\n }\n }\n }\n\n /**\n * Assuming this room is a DM room, tries to guess with which user.\n * @returns user id of the other member (could be syncing user)\n */\n public guessDMUserId(): string {\n const me = this.getMember(this.myUserId);\n if (me) {\n const inviterId = me.getDMInviter();\n if (inviterId) {\n return inviterId;\n }\n }\n // Remember, we're assuming this room is a DM, so returning the first member we find should be fine\n if (Array.isArray(this.summaryHeroes) && this.summaryHeroes.length) {\n return this.summaryHeroes[0];\n }\n const members = this.currentState.getMembers();\n const anyMember = members.find((m) => m.userId !== this.myUserId);\n if (anyMember) {\n return anyMember.userId;\n }\n // it really seems like I'm the only user in the room\n // so I probably created a room with just me in it\n // and marked it as a DM. Ok then\n return this.myUserId;\n }\n\n /**\n * Gets the \"functional members\" in this room.\n *\n * Returns the list of userIDs from the `io.element.functional_members` event. Does not consider the\n * current membership states of those users.\n *\n * @see https://github.com/element-hq/element-meta/blob/develop/spec/functional_members.md.\n */\n private getFunctionalMembers(): string[] {\n const mFunctionalMembers = this.currentState.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, \"\");\n if (Array.isArray(mFunctionalMembers?.getContent().service_members)) {\n return mFunctionalMembers!.getContent().service_members;\n }\n return [];\n }\n\n public getAvatarFallbackMember(): RoomMember | undefined {\n const functionalMembers = this.getFunctionalMembers();\n\n // Only generate a fallback avatar if the conversation is with a single specific other user (a \"DM\").\n let nonFunctionalMemberCount = 0;\n this.getMembers()!.forEach((m) => {\n if (m.membership !== \"join\" && m.membership !== \"invite\") return;\n if (functionalMembers.includes(m.userId)) return;\n nonFunctionalMemberCount++;\n });\n if (nonFunctionalMemberCount > 2) return;\n\n // Prefer the list of heroes, if present. It should only include the single other user in the DM.\n const nonFunctionalHeroes = this.summaryHeroes?.filter((h) => !functionalMembers.includes(h));\n const hasHeroes = Array.isArray(nonFunctionalHeroes) && nonFunctionalHeroes.length;\n if (hasHeroes) {\n const availableMember = nonFunctionalHeroes\n .map((userId) => {\n return this.getMember(userId);\n })\n .find((member) => !!member);\n if (availableMember) {\n return availableMember;\n }\n }\n\n // Consider *all*, including previous, members, to generate the avatar for DMs where the other user left.\n // Needed to generate a matching avatar for rooms named \"Empty Room (was Alice)\".\n const members = this.getMembers();\n const nonFunctionalMembers = members?.filter((m) => !functionalMembers.includes(m.userId));\n if (nonFunctionalMembers.length <= 2) {\n const availableMember = nonFunctionalMembers.find((m) => {\n return m.userId !== this.myUserId;\n });\n if (availableMember) {\n return availableMember;\n }\n }\n\n // If all else failed, but the homeserver gave us heroes that previously could not be found in the room members,\n // trust and try falling back to a hero, creating a one-off member for it\n if (hasHeroes) {\n const availableUser = nonFunctionalHeroes\n .map((userId) => {\n return this.client.getUser(userId);\n })\n .find((user) => !!user);\n if (availableUser) {\n const member = new RoomMember(this.roomId, availableUser.userId);\n member.user = availableUser;\n return member;\n }\n }\n }\n\n /**\n * Sets the membership this room was received as during sync\n * @param membership - join | leave | invite\n */\n public updateMyMembership(membership: Membership): void {\n const prevMembership = this.selfMembership;\n this.selfMembership = membership;\n if (prevMembership !== membership) {\n if (membership === KnownMembership.Leave) {\n this.cleanupAfterLeaving();\n }\n this.emit(RoomEvent.MyMembership, this, membership, prevMembership);\n }\n }\n\n private async loadMembersFromServer(): Promise<IStateEventWithRoomId[]> {\n const lastSyncToken = this.client.store.getSyncToken();\n const response = await this.client.members(\n this.roomId,\n undefined,\n KnownMembership.Leave,\n lastSyncToken ?? undefined,\n );\n return response.chunk;\n }\n\n private async loadMembers(): Promise<{ memberEvents: MatrixEvent[]; fromServer: boolean }> {\n // were the members loaded from the server?\n let fromServer = false;\n let rawMembersEvents = await this.client.store.getOutOfBandMembers(this.roomId);\n // If the room is encrypted, we always fetch members from the server at\n // least once, in case the latest state wasn't persisted properly. Note\n // that this function is only called once (unless loading the members\n // fails), since loadMembersIfNeeded always returns this.membersPromise\n // if set, which will be the result of the first (successful) call.\n if (rawMembersEvents === null || this.hasEncryptionStateEvent()) {\n fromServer = true;\n rawMembersEvents = await this.loadMembersFromServer();\n logger.log(`LL: got ${rawMembersEvents.length} ` + `members from server for room ${this.roomId}`);\n }\n const memberEvents = rawMembersEvents.filter(noUnsafeEventProps).map(this.client.getEventMapper());\n return { memberEvents, fromServer };\n }\n\n /**\n * Check if loading of out-of-band-members has completed\n *\n * @returns true if the full membership list of this room has been loaded (including if lazy-loading is disabled).\n * False if the load is not started or is in progress.\n */\n public membersLoaded(): boolean {\n if (!this.opts.lazyLoadMembers) {\n return true;\n }\n\n return this.currentState.outOfBandMembersReady();\n }\n\n /**\n * Preloads the member list in case lazy loading\n * of memberships is in use. Can be called multiple times,\n * it will only preload once.\n * @returns when preloading is done and\n * accessing the members on the room will take\n * all members in the room into account\n */\n public loadMembersIfNeeded(): Promise<boolean> {\n if (this.membersPromise) {\n return this.membersPromise;\n }\n\n // mark the state so that incoming messages while\n // the request is in flight get marked as superseding\n // the OOB members\n this.currentState.markOutOfBandMembersStarted();\n\n const inMemoryUpdate = this.loadMembers()\n .then((result) => {\n this.currentState.setOutOfBandMembers(result.memberEvents);\n return result.fromServer;\n })\n .catch((err) => {\n // allow retries on fail\n this.membersPromise = undefined;\n this.currentState.markOutOfBandMembersFailed();\n throw err;\n });\n // update members in storage, but don't wait for it\n inMemoryUpdate\n .then((fromServer) => {\n if (fromServer) {\n const oobMembers = this.currentState\n .getMembers()\n .filter((m) => m.isOutOfBand())\n .map((m) => m.events.member?.event as IStateEventWithRoomId);\n logger.log(`LL: telling store to write ${oobMembers.length}` + ` members for room ${this.roomId}`);\n const store = this.client.store;\n return (\n store\n .setOutOfBandMembers(this.roomId, oobMembers)\n // swallow any IDB error as we don't want to fail\n // because of this\n .catch((err) => {\n logger.log(\"LL: storing OOB room members failed, oh well\", err);\n })\n );\n }\n })\n .catch((err) => {\n // as this is not awaited anywhere,\n // at least show the error in the console\n logger.error(err);\n });\n\n this.membersPromise = inMemoryUpdate;\n\n return this.membersPromise;\n }\n\n /**\n * Removes the lazily loaded members from storage if needed\n */\n public async clearLoadedMembersIfNeeded(): Promise<void> {\n if (this.opts.lazyLoadMembers && this.membersPromise) {\n await this.loadMembersIfNeeded();\n await this.client.store.clearOutOfBandMembers(this.roomId);\n this.currentState.clearOutOfBandMembers();\n this.membersPromise = undefined;\n }\n }\n\n /**\n * called when sync receives this room in the leave section\n * to do cleanup after leaving a room. Possibly called multiple times.\n */\n private cleanupAfterLeaving(): void {\n this.clearLoadedMembersIfNeeded().catch((err) => {\n logger.error(`error after clearing loaded members from ` + `room ${this.roomId} after leaving`);\n logger.log(err);\n });\n }\n\n /**\n * Empty out the current live timeline and re-request it. This is used when\n * historical messages are imported into the room via MSC2716 `/batch_send`\n * because the client may already have that section of the timeline loaded.\n * We need to force the client to throw away their current timeline so that\n * when they back paginate over the area again with the historical messages\n * in between, it grabs the newly imported messages. We can listen for\n * `UNSTABLE_MSC2716_MARKER`, in order to tell when historical messages are ready\n * to be discovered in the room and the timeline needs a refresh. The SDK\n * emits a `RoomEvent.HistoryImportedWithinTimeline` event when we detect a\n * valid marker and can check the needs refresh status via\n * `room.getTimelineNeedsRefresh()`.\n */\n public async refreshLiveTimeline(): Promise<void> {\n const liveTimelineBefore = this.getLiveTimeline();\n const forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS);\n const backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS);\n const eventsBefore = liveTimelineBefore.getEvents();\n const mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];\n logger.log(\n `[refreshLiveTimeline for ${this.roomId}] at ` +\n `mostRecentEventInTimeline=${mostRecentEventInTimeline && mostRecentEventInTimeline.getId()} ` +\n `liveTimelineBefore=${liveTimelineBefore.toString()} ` +\n `forwardPaginationToken=${forwardPaginationToken} ` +\n `backwardPaginationToken=${backwardPaginationToken}`,\n );\n\n // Get the main TimelineSet\n const timelineSet = this.getUnfilteredTimelineSet();\n\n let newTimeline: Optional<EventTimeline>;\n // If there isn't any event in the timeline, let's go fetch the latest\n // event and construct a timeline from it.\n //\n // This should only really happen if the user ran into an error\n // with refreshing the timeline before which left them in a blank\n // timeline from `resetLiveTimeline`.\n if (!mostRecentEventInTimeline) {\n newTimeline = await this.client.getLatestTimeline(timelineSet);\n } else {\n // Empty out all of `this.timelineSets`. But we also need to keep the\n // same `timelineSet` references around so the React code updates\n // properly and doesn't ignore the room events we emit because it checks\n // that the `timelineSet` references are the same. We need the\n // `timelineSet` empty so that the `client.getEventTimeline(...)` call\n // later, will call `/context` and create a new timeline instead of\n // returning the same one.\n this.resetLiveTimeline(null, null);\n\n // Make the UI timeline show the new blank live timeline we just\n // reset so that if the network fails below it's showing the\n // accurate state of what we're working with instead of the\n // disconnected one in the TimelineWindow which is just hanging\n // around by reference.\n this.emit(RoomEvent.TimelineRefresh, this, timelineSet);\n\n // Use `client.getEventTimeline(...)` to construct a new timeline from a\n // `/context` response state and events for the most recent event before\n // we reset everything. The `timelineSet` we pass in needs to be empty\n // in order for this function to call `/context` and generate a new\n // timeline.\n newTimeline = await this.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId()!);\n }\n\n // If a racing `/sync` beat us to creating a new timeline, use that\n // instead because it's the latest in the room and any new messages in\n // the scrollback will include the history.\n const liveTimeline = timelineSet.getLiveTimeline();\n if (\n !liveTimeline ||\n (liveTimeline.getPaginationToken(Direction.Forward) === null &&\n liveTimeline.getPaginationToken(Direction.Backward) === null &&\n liveTimeline.getEvents().length === 0)\n ) {\n logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`);\n // Set the pagination token back to the live sync token (`null`) instead\n // of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`)\n // so that it matches the next response from `/sync` and we can properly\n // continue the timeline.\n newTimeline!.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);\n\n // Set our new fresh timeline as the live timeline to continue syncing\n // forwards and back paginating from.\n timelineSet.setLiveTimeline(newTimeline!);\n // Fixup `this.oldstate` so that `scrollback` has the pagination tokens\n // available\n this.fixUpLegacyTimelineFields();\n } else {\n logger.log(\n `[refreshLiveTimeline for ${this.roomId}] \\`/sync\\` or some other request beat us to creating a new ` +\n `live timeline after we reset it. We'll use that instead since any events in the scrollback from ` +\n `this timeline will include the history.`,\n );\n }\n\n // The timeline has now been refreshed ✅\n this.setTimelineNeedsRefresh(false);\n\n // Emit an event which clients can react to and re-load the timeline\n // from the SDK\n this.emit(RoomEvent.TimelineRefresh, this, timelineSet);\n }\n\n /**\n * Reset the live timeline of all timelineSets, and start new ones.\n *\n * <p>This is used when /sync returns a 'limited' timeline.\n *\n * @param backPaginationToken - token for back-paginating the new timeline\n * @param forwardPaginationToken - token for forward-paginating the old live timeline,\n * if absent or null, all timelines are reset, removing old ones (including the previous live\n * timeline which would otherwise be unable to paginate forwards without this token).\n * Removing just the old live timeline whilst preserving previous ones is not supported.\n */\n public resetLiveTimeline(backPaginationToken?: string | null, forwardPaginationToken?: string | null): void {\n for (const timelineSet of this.timelineSets) {\n timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);\n }\n for (const thread of this.threads.values()) {\n thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken);\n }\n\n this.fixUpLegacyTimelineFields();\n }\n\n /**\n * Fix up this.timeline, this.oldState and this.currentState\n *\n * @internal\n */\n private fixUpLegacyTimelineFields(): void {\n const previousOldState = this.oldState;\n const previousCurrentState = this.currentState;\n\n // maintain this.oldState and this.currentState as references to the\n // state at the start and end of that timeline. These are more\n // for backwards-compatibility than anything else.\n this.oldState = this.getLiveTimeline().getState(EventTimeline.BACKWARDS)!;\n this.currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS)!;\n\n // Let people know to register new listeners for the new state\n // references. The reference won't necessarily change every time so only\n // emit when we see a change.\n if (previousOldState !== this.oldState) {\n this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);\n }\n\n if (previousCurrentState !== this.currentState) {\n this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);\n\n // Re-emit various events on the current room state\n // TODO: If currentState really only exists for backwards\n // compatibility, shouldn't we be doing this some other way?\n this.reEmitter.stopReEmitting(previousCurrentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n RoomStateEvent.Marker,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n this.reEmitter.reEmit(this.currentState, [\n RoomStateEvent.Events,\n RoomStateEvent.Members,\n RoomStateEvent.NewMember,\n RoomStateEvent.Update,\n RoomStateEvent.Marker,\n BeaconEvent.New,\n BeaconEvent.Update,\n BeaconEvent.Destroy,\n BeaconEvent.LivenessChange,\n ]);\n }\n }\n\n private onReceipt(event: MatrixEvent): void {\n if (this.hasEncryptionStateEvent()) {\n this.clearNotificationsOnReceipt(event);\n }\n }\n\n private clearNotificationsOnReceipt(event: MatrixEvent): void {\n // Like above, we have to listen for read receipts from ourselves in order to\n // correctly handle notification counts on encrypted rooms.\n // This fixes https://github.com/vector-im/element-web/issues/9421\n\n // Figure out if we've read something or if it's just informational\n // We need to work out what threads we've just recieved receipts for, so we\n // know which ones to update. If we've received an unthreaded receipt, we'll\n // need to update all threads.\n let threadIds: string[] = [];\n let hasUnthreadedReceipt = false;\n\n const content = event.getContent();\n\n for (const receiptGroup of Object.values(content)) {\n for (const [receiptType, userReceipt] of Object.entries(receiptGroup)) {\n if (!utils.isSupportedReceiptType(receiptType)) continue;\n if (!userReceipt) continue;\n\n for (const [userId, singleReceipt] of Object.entries(userReceipt)) {\n if (!singleReceipt || typeof singleReceipt !== \"object\") continue;\n const typedSingleReceipt = singleReceipt as Record<string, any>;\n if (userId !== this.client.getUserId()) continue;\n if (typedSingleReceipt.thread_id === undefined) {\n hasUnthreadedReceipt = true;\n } else if (typeof typedSingleReceipt.thread_id === \"string\") {\n threadIds.push(typedSingleReceipt.thread_id);\n }\n }\n }\n }\n\n if (hasUnthreadedReceipt) {\n // If we have an unthreaded receipt, we need to update any threads that have a notification\n // in them (because we know the receipt can't go backwards so we don't need to check any with\n // no notifications: the number can only decrease from a receipt).\n threadIds = this.getThreads()\n .filter(\n (thread) =>\n this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0 ||\n this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Highlight) > 0,\n )\n .map((thread) => thread.id);\n threadIds.push(\"main\");\n }\n\n for (const threadId of threadIds) {\n // Work backwards to determine how many events are unread. We also set\n // a limit for how back we'll look to avoid spinning CPU for too long.\n // If we hit the limit, we assume the count is unchanged.\n const maxHistory = 20;\n const timeline = threadId === \"main\" ? this.getLiveTimeline() : this.getThread(threadId)?.liveTimeline;\n\n if (!timeline) {\n logger.warn(`Couldn't find timeline for thread ID ${threadId} in room ${this.roomId}`);\n continue;\n }\n\n const events = timeline.getEvents();\n\n let highlightCount = 0;\n\n for (let i = events.length - 1; i >= 0; i--) {\n if (i === events.length - maxHistory) return; // limit reached\n\n const event = events[i];\n\n if (this.hasUserReadEvent(this.client.getUserId()!, event.getId()!)) {\n // If the user has read the event, then the counting is done.\n break;\n }\n\n const pushActions = this.client.getPushActionsForEvent(event);\n highlightCount += pushActions?.tweaks?.highlight ? 1 : 0;\n }\n\n // Note: we don't need to handle 'total' notifications because the counts\n // will come from the server.\n if (threadId === \"main\") {\n this.setUnreadNotificationCount(NotificationCountType.Highlight, highlightCount);\n } else {\n this.setThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight, highlightCount);\n }\n }\n }\n\n /**\n * Return the timeline sets for this room.\n * @returns array of timeline sets for this room\n */\n public getTimelineSets(): EventTimelineSet[] {\n return this.timelineSets;\n }\n\n /**\n * Helper to return the main unfiltered timeline set for this room\n * @returns room's unfiltered timeline set\n */\n public getUnfilteredTimelineSet(): EventTimelineSet {\n return this.timelineSets[0];\n }\n\n /**\n * Get the timeline which contains the given event from the unfiltered set, if any\n *\n * @param eventId - event ID to look for\n * @returns timeline containing\n * the given event, or null if unknown\n */\n public getTimelineForEvent(eventId: string): EventTimeline | null {\n const event = this.findEventById(eventId);\n const thread = this.findThreadForEvent(event);\n if (thread) {\n return thread.timelineSet.getTimelineForEvent(eventId);\n } else {\n return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);\n }\n }\n\n /**\n * Add a new timeline to this room's unfiltered timeline set\n *\n * @returns newly-created timeline\n */\n public addTimeline(): EventTimeline {\n return this.getUnfilteredTimelineSet().addTimeline();\n }\n\n /**\n * Whether the timeline needs to be refreshed in order to pull in new\n * historical messages that were imported.\n * @param value - The value to set\n */\n public setTimelineNeedsRefresh(value: boolean): void {\n this.timelineNeedsRefresh = value;\n }\n\n /**\n * Whether the timeline needs to be refreshed in order to pull in new\n * historical messages that were imported.\n * @returns .\n */\n public getTimelineNeedsRefresh(): boolean {\n return this.timelineNeedsRefresh;\n }\n\n /**\n * Get an event which is stored in our unfiltered timeline set, or in a thread\n *\n * @param eventId - event ID to look for\n * @returns the given event, or undefined if unknown\n */\n public findEventById(eventId: string): MatrixEvent | undefined {\n let event = this.getUnfilteredTimelineSet().findEventById(eventId);\n\n if (!event) {\n const threads = this.getThreads();\n for (let i = 0; i < threads.length; i++) {\n const thread = threads[i];\n event = thread.findEventById(eventId);\n if (event) {\n return event;\n }\n }\n }\n\n return event;\n }\n\n /**\n * Get one of the notification counts for this room\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getUnreadNotificationCount(type = NotificationCountType.Total): number {\n let count = this.getRoomUnreadNotificationCount(type);\n for (const threadNotification of this.threadNotifications.values()) {\n count += threadNotification[type] ?? 0;\n }\n return count;\n }\n\n /**\n * Get the notification for the event context (room or thread timeline)\n */\n public getUnreadCountForEventContext(type = NotificationCountType.Total, event: MatrixEvent): number {\n const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;\n\n return (\n (isThreadEvent\n ? this.getThreadUnreadNotificationCount(event.threadRootId, type)\n : this.getRoomUnreadNotificationCount(type)) ?? 0\n );\n }\n\n /**\n * Get one of the notification counts for this room\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getRoomUnreadNotificationCount(type = NotificationCountType.Total): number {\n return this.notificationCounts[type] ?? 0;\n }\n\n /**\n * Get one of the notification counts for a thread\n * @param threadId - the root event ID\n * @param type - The type of notification count to get. default: 'total'\n * @returns The notification count, or undefined if there is no count\n * for this type.\n */\n public getThreadUnreadNotificationCount(threadId: string, type = NotificationCountType.Total): number {\n return this.threadNotifications.get(threadId)?.[type] ?? 0;\n }\n\n /**\n * Checks if the current room has unread thread notifications\n * @returns\n */\n public hasThreadUnreadNotification(): boolean {\n for (const notification of this.threadNotifications.values()) {\n if ((notification.highlight ?? 0) > 0 || (notification.total ?? 0) > 0) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Swet one of the notification count for a thread\n * @param threadId - the root event ID\n * @param type - The type of notification count to get. default: 'total'\n * @returns\n */\n public setThreadUnreadNotificationCount(threadId: string, type: NotificationCountType, count: number): void {\n const notification: NotificationCount = {\n highlight: this.threadNotifications.get(threadId)?.highlight,\n total: this.threadNotifications.get(threadId)?.total,\n ...{\n [type]: count,\n },\n };\n\n this.threadNotifications.set(threadId, notification);\n\n this.emit(RoomEvent.UnreadNotifications, notification, threadId);\n }\n\n /**\n * @returns the notification count type for all the threads in the room\n */\n public get threadsAggregateNotificationType(): NotificationCountType | null {\n let type: NotificationCountType | null = null;\n for (const threadNotification of this.threadNotifications.values()) {\n if ((threadNotification.highlight ?? 0) > 0) {\n return NotificationCountType.Highlight;\n } else if ((threadNotification.total ?? 0) > 0 && !type) {\n type = NotificationCountType.Total;\n }\n }\n return type;\n }\n\n /**\n * Resets the total thread notifications for all threads in this room to zero,\n * excluding any threads whose IDs are given in `exceptThreadIds`.\n *\n * If the room is not encrypted, also resets the highlight notification count to zero\n * for the same set of threads.\n *\n * This is intended for use from the sync code since we calculate highlight notification\n * counts locally from decrypted messages. We want to partially trust the total from the\n * server such that we clear notifications when read receipts arrive. The weird name is\n * intended to reflect this. You probably do not want to use this.\n *\n * @param exceptThreadIds - The thread IDs to exclude from the reset.\n */\n public resetThreadUnreadNotificationCountFromSync(exceptThreadIds: string[] = []): void {\n const isEncrypted = this.hasEncryptionStateEvent();\n\n for (const [threadId, notifs] of this.threadNotifications) {\n if (!exceptThreadIds.includes(threadId)) {\n notifs.total = 0;\n if (!isEncrypted) {\n notifs.highlight = 0;\n }\n }\n }\n\n this.emit(RoomEvent.UnreadNotifications);\n }\n\n /**\n * Set one of the notification counts for this room\n * @param type - The type of notification count to set.\n * @param count - The new count\n */\n public setUnreadNotificationCount(type: NotificationCountType, count: number): void {\n this.notificationCounts[type] = count;\n this.emit(RoomEvent.UnreadNotifications, this.notificationCounts);\n }\n\n public setUnread(type: NotificationCountType, count: number): void {\n return this.setUnreadNotificationCount(type, count);\n }\n\n public setSummary(summary: IRoomSummary): void {\n const heroes = summary[\"m.heroes\"];\n const joinedCount = summary[\"m.joined_member_count\"];\n const invitedCount = summary[\"m.invited_member_count\"];\n if (Number.isInteger(joinedCount)) {\n this.currentState.setJoinedMemberCount(joinedCount!);\n }\n if (Number.isInteger(invitedCount)) {\n this.currentState.setInvitedMemberCount(invitedCount!);\n }\n if (Array.isArray(heroes)) {\n // be cautious about trusting server values,\n // and make sure heroes doesn't contain our own id\n // just to be sure\n this.summaryHeroes = heroes.filter((userId) => {\n return userId !== this.myUserId;\n });\n }\n\n this.emit(RoomEvent.Summary, summary);\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @param value - true to blacklist unverified devices, null\n * to use the global value for this room.\n */\n public setBlacklistUnverifiedDevices(value: boolean): void {\n this.blacklistUnverifiedDevices = value;\n }\n\n /**\n * Whether to send encrypted messages to devices within this room.\n * @returns true if blacklisting unverified devices, null\n * if the global value should be used for this room.\n */\n public getBlacklistUnverifiedDevices(): boolean | null {\n if (this.blacklistUnverifiedDevices === undefined) return null;\n return this.blacklistUnverifiedDevices;\n }\n\n /**\n * Get the avatar URL for a room if one was set.\n * @param baseUrl - The homeserver base URL. See\n * {@link MatrixClient#getHomeserverUrl}.\n * @param width - The desired width of the thumbnail.\n * @param height - The desired height of the thumbnail.\n * @param resizeMethod - The thumbnail resize method to use, either\n * \"crop\" or \"scale\".\n * @param allowDefault - True to allow an identicon for this room if an\n * avatar URL wasn't explicitly set. Default: true. (Deprecated)\n * @returns the avatar URL or null.\n */\n public getAvatarUrl(\n baseUrl: string,\n width: number,\n height: number,\n resizeMethod: ResizeMethod,\n allowDefault = true,\n ): string | null {\n const roomAvatarEvent = this.currentState.getStateEvents(EventType.RoomAvatar, \"\");\n if (!roomAvatarEvent && !allowDefault) {\n return null;\n }\n\n const mainUrl = roomAvatarEvent ? roomAvatarEvent.getContent().url : null;\n if (mainUrl) {\n return getHttpUriForMxc(baseUrl, mainUrl, width, height, resizeMethod);\n }\n\n return null;\n }\n\n /**\n * Get the mxc avatar url for the room, if one was set.\n * @returns the mxc avatar url or falsy\n */\n public getMxcAvatarUrl(): string | null {\n return this.currentState.getStateEvents(EventType.RoomAvatar, \"\")?.getContent()?.url || null;\n }\n\n /**\n * Get this room's canonical alias\n * The alias returned by this function may not necessarily\n * still point to this room.\n * @returns The room's canonical alias, or null if there is none\n */\n public getCanonicalAlias(): string | null {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alias || null;\n }\n return null;\n }\n\n /**\n * Get this room's alternative aliases\n * @returns The room's alternative aliases, or an empty array\n */\n public getAltAliases(): string[] {\n const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, \"\");\n if (canonicalAlias) {\n return canonicalAlias.getContent().alt_aliases || [];\n }\n return [];\n }\n\n /**\n * Add events to a timeline\n *\n * <p>Will fire \"Room.timeline\" for each event added.\n *\n * @param events - A list of events to add.\n *\n * @param toStartOfTimeline - True to add these events to the start\n * (oldest) instead of the end (newest) of the timeline. If true, the oldest\n * event will be the <b>last</b> element of 'events'.\n *\n * @param timeline - timeline to\n * add events to.\n *\n * @param paginationToken - token for the next batch of events\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n public addEventsToTimeline(\n events: MatrixEvent[],\n toStartOfTimeline: boolean,\n timeline: EventTimeline,\n paginationToken?: string,\n ): void {\n timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, timeline, paginationToken);\n }\n\n /**\n * Get the instance of the thread associated with the current event\n * @param eventId - the ID of the current event\n * @returns a thread instance if known\n */\n public getThread(eventId: string): Thread | null {\n return this.threads.get(eventId) ?? null;\n }\n\n /**\n * Get all the known threads in the room\n */\n public getThreads(): Thread[] {\n return Array.from(this.threads.values());\n }\n\n /**\n * Get a member from the current room state.\n * @param userId - The user ID of the member.\n * @returns The member or `null`.\n */\n public getMember(userId: string): RoomMember | null {\n return this.currentState.getMember(userId);\n }\n\n /**\n * Get all currently loaded members from the current\n * room state.\n * @returns Room members\n */\n public getMembers(): RoomMember[] {\n return this.currentState.getMembers();\n }\n\n /**\n * Get a list of members whose membership state is \"join\".\n * @returns A list of currently joined members.\n */\n public getJoinedMembers(): RoomMember[] {\n return this.getMembersWithMembership(KnownMembership.Join);\n }\n\n /**\n * Returns the number of joined members in this room\n * This method caches the result.\n * This is a wrapper around the method of the same name in roomState, returning\n * its result for the room's current state.\n * @returns The number of members in this room whose membership is 'join'\n */\n public getJoinedMemberCount(): number {\n return this.currentState.getJoinedMemberCount();\n }\n\n /**\n * Returns the number of invited members in this room\n * @returns The number of members in this room whose membership is 'invite'\n */\n public getInvitedMemberCount(): number {\n return this.currentState.getInvitedMemberCount();\n }\n\n /**\n * Returns the number of invited + joined members in this room\n * @returns The number of members in this room whose membership is 'invite' or 'join'\n */\n public getInvitedAndJoinedMemberCount(): number {\n return this.getInvitedMemberCount() + this.getJoinedMemberCount();\n }\n\n /**\n * Get a list of members with given membership state.\n * @param membership - The membership state.\n * @returns A list of members with the given membership state.\n */\n public getMembersWithMembership(membership: Membership): RoomMember[] {\n return this.currentState.getMembers().filter(function (m) {\n return m.membership === membership;\n });\n }\n\n /**\n * Get a list of members we should be encrypting for in this room\n * @returns A list of members who\n * we should encrypt messages for in this room.\n */\n public async getEncryptionTargetMembers(): Promise<RoomMember[]> {\n await this.loadMembersIfNeeded();\n let members = this.getMembersWithMembership(KnownMembership.Join);\n if (this.shouldEncryptForInvitedMembers()) {\n members = members.concat(this.getMembersWithMembership(KnownMembership.Invite));\n }\n return members;\n }\n\n /**\n * Determine whether we should encrypt messages for invited users in this room\n * @returns if we should encrypt messages for invited users\n */\n public shouldEncryptForInvitedMembers(): boolean {\n const ev = this.currentState.getStateEvents(EventType.RoomHistoryVisibility, \"\");\n return ev?.getContent()?.history_visibility !== \"joined\";\n }\n\n /**\n * Get the default room name (i.e. what a given user would see if the\n * room had no m.room.name)\n * @param userId - The userId from whose perspective we want\n * to calculate the default name\n * @returns The default room name\n */\n public getDefaultRoomName(userId: string): string {\n return this.calculateRoomName(userId, true);\n }\n\n /**\n * Check if the given user_id has the given membership state.\n * @param userId - The user ID to check.\n * @param membership - The membership e.g. `'join'`\n * @returns True if this user_id has the given membership state.\n */\n public hasMembershipState(userId: string, membership: Membership): boolean {\n const member = this.getMember(userId);\n if (!member) {\n return false;\n }\n return member.membership === membership;\n }\n\n /**\n * Add a timelineSet for this room with the given filter\n * @param filter - The filter to be applied to this timelineSet\n * @param opts - Configuration options\n * @returns The timelineSet\n */\n public getOrCreateFilteredTimelineSet(\n filter: Filter,\n { prepopulateTimeline = true, useSyncEvents = true, pendingEvents = true }: ICreateFilterOpts = {},\n ): EventTimelineSet {\n if (this.filteredTimelineSets[filter.filterId!]) {\n return this.filteredTimelineSets[filter.filterId!];\n }\n const opts = Object.assign({ filter, pendingEvents }, this.opts);\n const timelineSet = new EventTimelineSet(this, opts);\n this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n if (useSyncEvents) {\n this.filteredTimelineSets[filter.filterId!] = timelineSet;\n this.timelineSets.push(timelineSet);\n }\n\n const unfilteredLiveTimeline = this.getLiveTimeline();\n // Not all filter are possible to replicate client-side only\n // When that's the case we do not want to prepopulate from the live timeline\n // as we would get incorrect results compared to what the server would send back\n if (prepopulateTimeline) {\n // populate up the new timelineSet with filtered events from our live\n // unfiltered timeline.\n //\n // XXX: This is risky as our timeline\n // may have grown huge and so take a long time to filter.\n // see https://github.com/vector-im/vector-web/issues/2109\n\n unfilteredLiveTimeline.getEvents().forEach(function (event) {\n timelineSet.addLiveEvent(event);\n });\n\n // find the earliest unfiltered timeline\n let timeline = unfilteredLiveTimeline;\n while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) {\n timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)!;\n }\n\n timelineSet\n .getLiveTimeline()\n .setPaginationToken(timeline.getPaginationToken(EventTimeline.BACKWARDS), EventTimeline.BACKWARDS);\n } else if (useSyncEvents) {\n const livePaginationToken = unfilteredLiveTimeline.getPaginationToken(Direction.Forward);\n timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, Direction.Backward);\n }\n\n // alternatively, we could try to do something like this to try and re-paginate\n // in the filtered events from nothing, but Mark says it's an abuse of the API\n // to do so:\n //\n // timelineSet.resetLiveTimeline(\n // unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)\n // );\n\n return timelineSet;\n }\n\n private async getThreadListFilter(filterType = ThreadFilterType.All): Promise<Filter> {\n const myUserId = this.client.getUserId()!;\n const filter = new Filter(myUserId);\n\n const definition: IFilterDefinition = {\n room: {\n timeline: {\n [FILTER_RELATED_BY_REL_TYPES.name]: [THREAD_RELATION_TYPE.name],\n },\n },\n };\n\n if (filterType === ThreadFilterType.My) {\n definition!.room!.timeline![FILTER_RELATED_BY_SENDERS.name] = [myUserId];\n }\n\n filter.setDefinition(definition);\n const filterId = await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${filterType}`, filter);\n\n filter.filterId = filterId;\n\n return filter;\n }\n\n private async createThreadTimelineSet(filterType?: ThreadFilterType): Promise<EventTimelineSet> {\n let timelineSet: EventTimelineSet;\n if (Thread.hasServerSideListSupport) {\n timelineSet = new EventTimelineSet(\n this,\n {\n ...this.opts,\n pendingEvents: false,\n },\n undefined,\n undefined,\n filterType ?? ThreadFilterType.All,\n );\n this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);\n } else if (Thread.hasServerSideSupport) {\n const filter = await this.getThreadListFilter(filterType);\n\n timelineSet = this.getOrCreateFilteredTimelineSet(filter, {\n prepopulateTimeline: false,\n useSyncEvents: false,\n pendingEvents: false,\n });\n } else {\n timelineSet = new EventTimelineSet(this, {\n pendingEvents: false,\n });\n\n Array.from(this.threads).forEach(([, thread]) => {\n if (thread.length === 0) return;\n const currentUserParticipated = thread.timeline.some((event) => {\n return event.getSender() === this.client.getUserId();\n });\n if (filterType !== ThreadFilterType.My || currentUserParticipated) {\n timelineSet.getLiveTimeline().addEvent(thread.rootEvent!, {\n toStartOfTimeline: false,\n });\n }\n });\n }\n\n return timelineSet;\n }\n\n private threadsReady = false;\n\n /**\n * Takes the given thread root events and creates threads for them.\n */\n public processThreadRoots(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n if (!this.client.supportsThreads()) return;\n for (const rootEvent of events) {\n EventTimeline.setEventMetadata(rootEvent, this.currentState, toStartOfTimeline);\n if (!this.getThread(rootEvent.getId()!)) {\n this.createThread(rootEvent.getId()!, rootEvent, [], toStartOfTimeline);\n }\n }\n }\n\n /**\n * Fetch the bare minimum of room threads required for the thread list to work reliably.\n * With server support that means fetching one page.\n * Without server support that means fetching as much at once as the server allows us to.\n */\n public async fetchRoomThreads(): Promise<void> {\n if (this.threadsReady || !this.client.supportsThreads()) {\n return;\n }\n\n if (Thread.hasServerSideListSupport) {\n await Promise.all([\n this.fetchRoomThreadList(ThreadFilterType.All),\n this.fetchRoomThreadList(ThreadFilterType.My),\n ]);\n } else {\n const allThreadsFilter = await this.getThreadListFilter();\n\n const { chunk: events } = await this.client.createMessagesRequest(\n this.roomId,\n \"\",\n Number.MAX_SAFE_INTEGER,\n Direction.Backward,\n allThreadsFilter,\n );\n\n if (!events.length) return;\n\n // Sorted by last_reply origin_server_ts\n const threadRoots = events.map(this.client.getEventMapper()).sort((eventA, eventB) => {\n /**\n * `origin_server_ts` in a decentralised world is far from ideal\n * but for lack of any better, we will have to use this\n * Long term the sorting should be handled by homeservers and this\n * is only meant as a short term patch\n */\n const threadAMetadata = eventA.getServerAggregatedRelation<IThreadBundledRelationship>(\n THREAD_RELATION_TYPE.name,\n )!;\n const threadBMetadata = eventB.getServerAggregatedRelation<IThreadBundledRelationship>(\n THREAD_RELATION_TYPE.name,\n )!;\n return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts;\n });\n\n const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n for (const rootEvent of threadRoots) {\n const opts = {\n duplicateStrategy: DuplicateStrategy.Ignore,\n fromCache: false,\n roomState,\n };\n this.threadsTimelineSets[0]?.addLiveEvent(rootEvent, opts);\n\n const threadRelationship = rootEvent.getServerAggregatedRelation<IThreadBundledRelationship>(\n THREAD_RELATION_TYPE.name,\n );\n if (threadRelationship?.current_user_participated) {\n this.threadsTimelineSets[1]?.addLiveEvent(rootEvent, opts);\n }\n }\n\n this.processThreadRoots(threadRoots, true);\n }\n\n this.on(ThreadEvent.NewReply, this.onThreadReply);\n this.on(ThreadEvent.Update, this.onThreadUpdate);\n this.on(ThreadEvent.Delete, this.onThreadDelete);\n this.threadsReady = true;\n }\n\n /**\n * Process a list of poll events.\n *\n * @param events - List of events\n */\n public async processPollEvents(events: MatrixEvent[]): Promise<void> {\n for (const event of events) {\n try {\n // Continue if the event is a clear text, non-poll event.\n if (!event.isEncrypted() && !isPollEvent(event)) continue;\n\n /**\n * Try to decrypt the event. Promise resolution does not guarantee a successful decryption.\n * Retry is handled in {@link processPollEvent}.\n */\n this.processPollEvent(event);\n } catch (err) {\n logger.warn(\"Error processing poll event\", event.getId(), err);\n }\n }\n }\n\n /**\n * Processes poll events:\n * If the event has a decryption failure, it will listen for decryption and tries again.\n * If it is a poll start event (`m.poll.start`),\n * it creates and stores a Poll model and emits a PollEvent.New event.\n * If the event is related to a poll, it will add it to the poll.\n * Noop for other cases.\n *\n * @param event - Event that could be a poll event\n */\n private async processPollEvent(event: MatrixEvent): Promise<void> {\n if (M_POLL_START.matches(event.getType())) {\n try {\n const poll = new Poll(event, this.client, this);\n this.polls.set(event.getId()!, poll);\n this.emit(PollEvent.New, poll);\n\n // remove the poll when redacted\n event.once(MatrixEventEvent.BeforeRedaction, (redactedEvent: MatrixEvent) => {\n this.polls.delete(redactedEvent.getId()!);\n });\n } catch {}\n // poll creation can fail for malformed poll start events\n return;\n }\n\n const relationEventId = event.relationEventId;\n\n if (relationEventId && this.polls.has(relationEventId)) {\n const poll = this.polls.get(relationEventId);\n poll?.onNewRelation(event);\n }\n }\n\n /**\n * Fetch a single page of threadlist messages for the specific thread filter\n * @internal\n */\n private async fetchRoomThreadList(filter?: ThreadFilterType): Promise<void> {\n if (!this.client.supportsThreads()) return;\n if (this.threadsTimelineSets.length === 0) return;\n\n const timelineSet = filter === ThreadFilterType.My ? this.threadsTimelineSets[1] : this.threadsTimelineSets[0];\n\n const { chunk: events, end } = await this.client.createThreadListMessagesRequest(\n this.roomId,\n null,\n undefined,\n Direction.Backward,\n timelineSet.threadListType,\n timelineSet.getFilter(),\n );\n\n timelineSet.getLiveTimeline().setPaginationToken(end ?? null, Direction.Backward);\n\n if (!events.length) return;\n\n const matrixEvents = events.map(this.client.getEventMapper());\n this.processThreadRoots(matrixEvents, true);\n const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n for (const rootEvent of matrixEvents) {\n timelineSet.addLiveEvent(rootEvent, {\n duplicateStrategy: DuplicateStrategy.Replace,\n fromCache: false,\n roomState,\n });\n }\n }\n\n private onThreadUpdate(thread: Thread): void {\n this.updateThreadRootEvents(thread, false, false);\n }\n\n private onThreadReply(thread: Thread): void {\n this.updateThreadRootEvents(thread, false, true);\n }\n\n private onThreadDelete(thread: Thread): void {\n this.threads.delete(thread.id);\n\n const timeline = this.getTimelineForEvent(thread.id);\n const roomEvent = timeline?.getEvents()?.find((it) => it.getId() === thread.id);\n if (roomEvent) {\n thread.clearEventMetadata(roomEvent);\n } else {\n logger.debug(\"onThreadDelete: Could not find root event in room timeline\");\n }\n for (const timelineSet of this.threadsTimelineSets) {\n timelineSet.removeEvent(thread.id);\n }\n }\n\n /**\n * Forget the timelineSet for this room with the given filter\n *\n * @param filter - the filter whose timelineSet is to be forgotten\n */\n public removeFilteredTimelineSet(filter: Filter): void {\n const timelineSet = this.filteredTimelineSets[filter.filterId!];\n delete this.filteredTimelineSets[filter.filterId!];\n const i = this.timelineSets.indexOf(timelineSet);\n if (i > -1) {\n this.timelineSets.splice(i, 1);\n }\n }\n\n /**\n * Determine which timeline(s) a given event should live in\n * Thread roots live in both the main timeline and their corresponding thread timeline\n * Relations, redactions, replies to thread relation events live only in the thread timeline\n * Relations (other than m.thread), redactions, replies to a thread root live only in the main timeline\n * Relations, redactions, replies where the parent cannot be found live in no timelines but should be aggregated regardless.\n * Otherwise, the event lives in the main timeline only.\n *\n * Note: when a redaction is applied, the redacted event, events relating\n * to it, and the redaction event itself, will all move to the main thread.\n * This method classifies them as inside the thread of the redacted event.\n * They are moved later as part of makeRedacted.\n * This will change if MSC3389 is merged.\n */\n public eventShouldLiveIn(\n event: MatrixEvent,\n events?: MatrixEvent[],\n roots?: Set<string>,\n ): {\n shouldLiveInRoom: boolean;\n shouldLiveInThread: boolean;\n threadId?: string;\n } {\n if (!this.client?.supportsThreads()) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n // A thread root is the only event shown in both timelines\n if (event.isThreadRoot || roots?.has(event.getId()!)) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: true,\n threadId: event.getId(),\n };\n }\n\n const isThreadRelation = event.isRelation(THREAD_RELATION_TYPE.name);\n const parentEventId = event.getAssociatedId();\n const threadRootId = event.threadRootId;\n\n // Where the parent is the thread root and this is a non-thread relation this should live only in the main timeline\n if (!!parentEventId && !isThreadRelation && (threadRootId === parentEventId || roots?.has(parentEventId!))) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n let parentEvent: MatrixEvent | undefined;\n if (parentEventId) {\n parentEvent = this.findEventById(parentEventId) ?? events?.find((e) => e.getId() === parentEventId);\n }\n\n // Treat non-thread-relations, redactions, and replies as extensions of their parents so evaluate parentEvent instead\n if (parentEvent && !isThreadRelation) {\n return this.eventShouldLiveIn(parentEvent, events, roots);\n }\n\n // A thread relation (1st and 2nd order) is always only shown in a thread\n if (threadRootId != undefined) {\n return {\n shouldLiveInRoom: false,\n shouldLiveInThread: true,\n threadId: threadRootId,\n };\n }\n\n // Due to replies not being typical relations and being used as fallbacks for threads relations\n // If we bypass the if case above then we know we are not a thread, so if we are still a reply\n // then we know that we must be in the main timeline. Same goes if we have no associated parent event.\n if (!parentEventId || !!event.replyEventId) {\n return {\n shouldLiveInRoom: true,\n shouldLiveInThread: false,\n };\n }\n\n // We've exhausted all scenarios,\n // we cannot assume that it lives in the main timeline as this may be a relation for an unknown thread\n // adding the event in the wrong timeline causes stuck notifications and can break ability to send read receipts\n return {\n shouldLiveInRoom: false,\n shouldLiveInThread: false,\n };\n }\n\n public findThreadForEvent(event?: MatrixEvent): Thread | null {\n if (!event) return null;\n\n const { threadId } = this.eventShouldLiveIn(event);\n return threadId ? this.getThread(threadId) : null;\n }\n\n private addThreadedEvents(threadId: string, events: MatrixEvent[], toStartOfTimeline = false): void {\n const thread = this.getThread(threadId);\n if (thread) {\n thread.addEvents(events, toStartOfTimeline);\n } else {\n const rootEvent = this.findEventById(threadId) ?? events.find((e) => e.getId() === threadId);\n this.createThread(threadId, rootEvent, events, toStartOfTimeline);\n }\n }\n\n /**\n * Adds events to a thread's timeline. Will fire \"Thread.update\"\n */\n public processThreadedEvents(events: MatrixEvent[], toStartOfTimeline: boolean): void {\n events.forEach(this.applyRedaction);\n\n const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};\n for (const event of events) {\n const { threadId, shouldLiveInThread } = this.eventShouldLiveIn(event);\n if (shouldLiveInThread && !eventsByThread[threadId!]) {\n eventsByThread[threadId!] = [];\n }\n eventsByThread[threadId!]?.push(event);\n }\n\n Object.entries(eventsByThread).map(([threadId, threadEvents]) =>\n this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline),\n );\n }\n\n private updateThreadRootEvents = (thread: Thread, toStartOfTimeline: boolean, recreateEvent: boolean): void => {\n if (thread.length) {\n this.updateThreadRootEvent(this.threadsTimelineSets?.[0], thread, toStartOfTimeline, recreateEvent);\n if (thread.hasCurrentUserParticipated) {\n this.updateThreadRootEvent(this.threadsTimelineSets?.[1], thread, toStartOfTimeline, recreateEvent);\n }\n }\n };\n\n private updateThreadRootEvent = (\n timelineSet: Optional<EventTimelineSet>,\n thread: Thread,\n toStartOfTimeline: boolean,\n recreateEvent: boolean,\n ): void => {\n if (timelineSet && thread.rootEvent) {\n if (recreateEvent) {\n timelineSet.removeEvent(thread.id);\n }\n if (Thread.hasServerSideSupport) {\n timelineSet.addLiveEvent(thread.rootEvent, {\n duplicateStrategy: DuplicateStrategy.Replace,\n fromCache: false,\n roomState: this.currentState,\n });\n } else {\n timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), { toStartOfTimeline });\n }\n }\n };\n\n public createThread(\n threadId: string,\n rootEvent: MatrixEvent | undefined,\n events: MatrixEvent[] = [],\n toStartOfTimeline: boolean,\n ): Thread {\n if (this.threads.has(threadId)) {\n return this.threads.get(threadId)!;\n }\n\n if (rootEvent) {\n const relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId()!);\n if (relatedEvents?.length) {\n // Include all relations of the root event, given it'll be visible in both timelines,\n // except `m.replace` as that will already be applied atop the event using `MatrixEvent::makeReplaced`\n events = events.concat(relatedEvents.filter((e) => !e.isRelation(RelationType.Replace)));\n }\n }\n\n const thread = new Thread(threadId, rootEvent, {\n room: this,\n client: this.client,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n receipts: this.cachedThreadReadReceipts.get(threadId) ?? [],\n });\n\n // Add the re-emitter before we start adding events to the thread so we don't miss events\n this.reEmitter.reEmit(thread, [\n ThreadEvent.Delete,\n ThreadEvent.Update,\n ThreadEvent.NewReply,\n RoomEvent.Timeline,\n RoomEvent.TimelineReset,\n ]);\n\n // All read receipts should now come down from sync, we do not need to keep\n // a reference to the cached receipts anymore.\n this.cachedThreadReadReceipts.delete(threadId);\n\n // If we managed to create a thread and figure out its `id` then we can use it\n // This has to happen before thread.addEvents, because that adds events to the eventtimeline, and the\n // eventtimeline sometimes looks up thread information via the room.\n this.threads.set(thread.id, thread);\n\n // This is necessary to be able to jump to events in threads:\n // If we jump to an event in a thread where neither the event, nor the root,\n // nor any thread event are loaded yet, we'll load the event as well as the thread root, create the thread,\n // and pass the event through this.\n thread.addEvents(events, false);\n\n // We need to update the thread root events, but the thread may not be ready yet.\n // If it isn't, it will fire ThreadEvent.Update when it is and we'll call updateThreadRootEvents then.\n if (this.threadsReady && thread.initialEventsFetched) {\n this.updateThreadRootEvents(thread, toStartOfTimeline, false);\n }\n this.emit(ThreadEvent.New, thread, toStartOfTimeline);\n\n return thread;\n }\n\n private applyRedaction = (event: MatrixEvent): void => {\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n\n // if we know about this event, redact its contents now.\n const redactedEvent = redactId ? this.findEventById(redactId) : undefined;\n if (redactedEvent) {\n const threadRootId = redactedEvent.threadRootId;\n redactedEvent.makeRedacted(event, this);\n\n // If this is in the current state, replace it with the redacted version\n if (redactedEvent.isState()) {\n const currentStateEvent = this.currentState.getStateEvents(\n redactedEvent.getType(),\n redactedEvent.getStateKey()!,\n );\n if (currentStateEvent?.getId() === redactedEvent.getId()) {\n this.currentState.setStateEvents([redactedEvent]);\n }\n }\n\n this.emit(RoomEvent.Redaction, event, this, threadRootId);\n\n // TODO: we stash user displaynames (among other things) in\n // RoomMember objects which are then attached to other events\n // (in the sender and target fields). We should get those\n // RoomMember objects to update themselves when the events that\n // they are based on are changed.\n\n // Remove any visibility change on this event.\n this.visibilityEvents.delete(redactId!);\n\n // If this event is a visibility change event, remove it from the\n // list of visibility changes and update any event affected by it.\n if (redactedEvent.isVisibilityEvent()) {\n this.redactVisibilityChangeEvent(event);\n }\n }\n\n // FIXME: apply redactions to notification list\n\n // NB: We continue to add the redaction event to the timeline so\n // clients can say \"so and so redacted an event\" if they wish to. Also\n // this may be needed to trigger an update.\n }\n };\n\n private processLiveEvent(event: MatrixEvent): void {\n this.applyRedaction(event);\n\n // Implement MSC3531: hiding messages.\n if (event.isVisibilityEvent()) {\n // This event changes the visibility of another event, record\n // the visibility change, inform clients if necessary.\n this.applyNewVisibilityEvent(event);\n }\n // If any pending visibility change is waiting for this (older) event,\n this.applyPendingVisibilityEvents(event);\n\n // Sliding Sync modifications:\n // The proxy cannot guarantee every sent event will have a transaction_id field, so we need\n // to check the event ID against the list of pending events if there is no transaction ID\n // field. Only do this for events sent by us though as it's potentially expensive to loop\n // the pending events map.\n const txnId = event.getUnsigned().transaction_id;\n if (!txnId && event.getSender() === this.myUserId) {\n // check the txn map for a matching event ID\n for (const [tid, localEvent] of this.txnToEvent) {\n if (localEvent.getId() === event.getId()) {\n logger.debug(\"processLiveEvent: found sent event without txn ID: \", tid, event.getId());\n // update the unsigned field so we can re-use the same codepaths\n const unsigned = event.getUnsigned();\n unsigned.transaction_id = tid;\n event.setUnsigned(unsigned);\n break;\n }\n }\n }\n }\n\n /**\n * Add an event to the end of this room's live timelines. Will fire\n * \"Room.timeline\".\n *\n * @param event - Event to be added\n * @param addLiveEventOptions - addLiveEvent options\n * @internal\n *\n * @remarks\n * Fires {@link RoomEvent.Timeline}\n */\n private addLiveEvent(event: MatrixEvent, addLiveEventOptions: IAddLiveEventOptions): void {\n const { duplicateStrategy, timelineWasEmpty, fromCache } = addLiveEventOptions;\n\n // add to our timeline sets\n for (const timelineSet of this.timelineSets) {\n timelineSet.addLiveEvent(event, {\n duplicateStrategy,\n fromCache,\n timelineWasEmpty,\n });\n }\n\n // synthesize and inject implicit read receipts\n // Done after adding the event because otherwise the app would get a read receipt\n // pointing to an event that wasn't yet in the timeline\n // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.\n if (event.sender && event.getType() !== EventType.RoomRedaction) {\n this.addReceipt(synthesizeReceipt(event.sender.userId, event, ReceiptType.Read), true);\n\n // Any live events from a user could be taken as implicit\n // presence information: evidence that they are currently active.\n // ...except in a world where we use 'user.currentlyActive' to reduce\n // presence spam, this isn't very useful - we'll get a transition when\n // they are no longer currently active anyway. So don't bother to\n // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.\n }\n }\n\n /**\n * Add a pending outgoing event to this room.\n *\n * <p>The event is added to either the pendingEventList, or the live timeline,\n * depending on the setting of opts.pendingEventOrdering.\n *\n * <p>This is an internal method, intended for use by MatrixClient.\n *\n * @param event - The event to add.\n *\n * @param txnId - Transaction id for this outgoing event\n *\n * @throws if the event doesn't have status SENDING, or we aren't given a\n * unique transaction id.\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public addPendingEvent(event: MatrixEvent, txnId: string): void {\n if (event.status !== EventStatus.SENDING && event.status !== EventStatus.NOT_SENT) {\n throw new Error(\"addPendingEvent called on an event with status \" + event.status);\n }\n\n if (this.txnToEvent.get(txnId)) {\n throw new Error(\"addPendingEvent called on an event with known txnId \" + txnId);\n }\n\n // call setEventMetadata to set up event.sender etc\n // as event is shared over all timelineSets, we set up its metadata based\n // on the unfiltered timelineSet.\n EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(EventTimeline.FORWARDS)!, false);\n\n this.txnToEvent.set(txnId, event);\n if (this.pendingEventList) {\n if (this.pendingEventList.some((e) => e.status === EventStatus.NOT_SENT)) {\n logger.warn(\"Setting event as NOT_SENT due to messages in the same state\");\n event.setStatus(EventStatus.NOT_SENT);\n }\n this.pendingEventList.push(event);\n this.savePendingEvents();\n if (event.isRelation()) {\n // For pending events, add them to the relations collection immediately.\n // (The alternate case below already covers this as part of adding to\n // the timeline set.)\n this.aggregateNonLiveRelation(event);\n }\n\n if (event.isRedaction()) {\n const redactId = event.event.redacts;\n let redactedEvent = this.pendingEventList.find((e) => e.getId() === redactId);\n if (!redactedEvent && redactId) {\n redactedEvent = this.findEventById(redactId);\n }\n if (redactedEvent) {\n redactedEvent.markLocallyRedacted(event);\n this.emit(RoomEvent.Redaction, event, this, redactedEvent.threadRootId);\n }\n }\n } else {\n for (const timelineSet of this.timelineSets) {\n if (timelineSet.getFilter()) {\n if (timelineSet.getFilter()!.filterRoomTimeline([event]).length) {\n timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n toStartOfTimeline: false,\n });\n }\n } else {\n timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {\n toStartOfTimeline: false,\n });\n }\n }\n }\n\n this.emit(RoomEvent.LocalEchoUpdated, event, this);\n }\n\n /**\n * Persists all pending events to local storage\n *\n * If the current room is encrypted only encrypted events will be persisted\n * all messages that are not yet encrypted will be discarded\n *\n * This is because the flow of EVENT_STATUS transition is\n * `queued => sending => encrypting => sending => sent`\n *\n * Steps 3 and 4 are skipped for unencrypted room.\n * It is better to discard an unencrypted message rather than persisting\n * it locally for everyone to read\n */\n private savePendingEvents(): void {\n if (this.pendingEventList) {\n const pendingEvents = this.pendingEventList\n .map((event) => {\n return {\n ...event.event,\n txn_id: event.getTxnId(),\n };\n })\n .filter((event) => {\n // Filter out the unencrypted messages if the room is encrypted\n const isEventEncrypted = event.type === EventType.RoomMessageEncrypted;\n const isRoomEncrypted = this.hasEncryptionStateEvent();\n return isEventEncrypted || !isRoomEncrypted;\n });\n\n this.client.store.setPendingEvents(this.roomId, pendingEvents);\n }\n }\n\n /**\n * Used to aggregate the local echo for a relation, and also\n * for re-applying a relation after it's redaction has been cancelled,\n * as the local echo for the redaction of the relation would have\n * un-aggregated the relation. Note that this is different from regular messages,\n * which are just kept detached for their local echo.\n *\n * Also note that live events are aggregated in the live EventTimelineSet.\n * @param event - the relation event that needs to be aggregated.\n */\n private aggregateNonLiveRelation(event: MatrixEvent): void {\n this.relations.aggregateChildEvent(event);\n }\n\n public getEventForTxnId(txnId: string): MatrixEvent | undefined {\n return this.txnToEvent.get(txnId);\n }\n\n /**\n * Deal with the echo of a message we sent.\n *\n * <p>We move the event to the live timeline if it isn't there already, and\n * update it.\n *\n * @param remoteEvent - The event received from\n * /sync\n * @param localEvent - The local echo, which\n * should be either in the pendingEventList or the timeline.\n *\n * @internal\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public handleRemoteEcho(remoteEvent: MatrixEvent, localEvent: MatrixEvent): void {\n const oldEventId = localEvent.getId()!;\n const newEventId = remoteEvent.getId()!;\n const oldStatus = localEvent.status;\n\n logger.debug(`Got remote echo for event ${oldEventId} -> ${newEventId} old status ${oldStatus}`);\n\n // no longer pending\n this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id!);\n\n // if it's in the pending list, remove it\n if (this.pendingEventList) {\n this.removePendingEvent(oldEventId);\n }\n\n // replace the event source (this will preserve the plaintext payload if\n // any, which is good, because we don't want to try decoding it again).\n localEvent.handleRemoteEcho(remoteEvent.event);\n\n const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(remoteEvent);\n const thread = threadId ? this.getThread(threadId) : null;\n thread?.setEventMetadata(localEvent);\n thread?.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n\n if (shouldLiveInRoom) {\n for (const timelineSet of this.timelineSets) {\n // if it's already in the timeline, update the timeline map. If it's not, add it.\n timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);\n }\n }\n\n this.emit(RoomEvent.LocalEchoUpdated, localEvent, this, oldEventId, oldStatus);\n }\n\n /**\n * Update the status / event id on a pending event, to reflect its transmission\n * progress.\n *\n * <p>This is an internal method.\n *\n * @param event - local echo event\n * @param newStatus - status to assign\n * @param newEventId - new event id to assign. Ignored unless newStatus == EventStatus.SENT.\n *\n * @remarks\n * Fires {@link RoomEvent.LocalEchoUpdated}\n */\n public updatePendingEvent(event: MatrixEvent, newStatus: EventStatus, newEventId?: string): void {\n logger.log(\n `setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` +\n `event ID ${event.getId()} -> ${newEventId}`,\n );\n\n // if the message was sent, we expect an event id\n if (newStatus == EventStatus.SENT && !newEventId) {\n throw new Error(\"updatePendingEvent called with status=SENT, but no new event id\");\n }\n\n // SENT races against /sync, so we have to special-case it.\n if (newStatus == EventStatus.SENT) {\n const timeline = this.getTimelineForEvent(newEventId!);\n if (timeline) {\n // we've already received the event via the event stream.\n // nothing more to do here, assuming the transaction ID was correctly matched.\n // Let's check that.\n const remoteEvent = this.findEventById(newEventId!);\n const remoteTxnId = remoteEvent?.getUnsigned().transaction_id;\n if (!remoteTxnId && remoteEvent) {\n // This code path is mostly relevant for the Sliding Sync proxy.\n // The remote event did not contain a transaction ID, so we did not handle\n // the remote echo yet. Handle it now.\n const unsigned = remoteEvent.getUnsigned();\n unsigned.transaction_id = event.getTxnId();\n remoteEvent.setUnsigned(unsigned);\n // the remote event is _already_ in the timeline, so we need to remove it so\n // we can convert the local event into the final event.\n this.removeEvent(remoteEvent.getId()!);\n this.handleRemoteEcho(remoteEvent, event);\n }\n return;\n }\n }\n\n const oldStatus = event.status;\n const oldEventId = event.getId()!;\n\n if (!oldStatus) {\n throw new Error(\"updatePendingEventStatus called on an event which is not a local echo.\");\n }\n\n const allowed = ALLOWED_TRANSITIONS[oldStatus];\n if (!allowed?.includes(newStatus)) {\n throw new Error(`Invalid EventStatus transition ${oldStatus}->${newStatus}`);\n }\n\n event.setStatus(newStatus);\n\n if (newStatus == EventStatus.SENT) {\n // update the event id\n event.replaceLocalEventId(newEventId!);\n\n const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(event);\n const thread = threadId ? this.getThread(threadId) : undefined;\n thread?.setEventMetadata(event);\n thread?.timelineSet.replaceEventId(oldEventId, newEventId!);\n\n if (shouldLiveInRoom) {\n // if the event was already in the timeline (which will be the case if\n // opts.pendingEventOrdering==chronological), we need to update the\n // timeline map.\n for (const timelineSet of this.timelineSets) {\n timelineSet.replaceEventId(oldEventId, newEventId!);\n }\n }\n } else if (newStatus == EventStatus.CANCELLED) {\n // remove it from the pending event list, or the timeline.\n if (this.pendingEventList) {\n const removedEvent = this.getPendingEvent(oldEventId);\n this.removePendingEvent(oldEventId);\n if (removedEvent?.isRedaction()) {\n this.revertRedactionLocalEcho(removedEvent);\n }\n }\n this.removeEvent(oldEventId);\n }\n this.savePendingEvents();\n\n this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus);\n }\n\n private revertRedactionLocalEcho(redactionEvent: MatrixEvent): void {\n const redactId = redactionEvent.event.redacts;\n if (!redactId) {\n return;\n }\n const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);\n if (redactedEvent) {\n redactedEvent.unmarkLocallyRedacted();\n // re-render after undoing redaction\n this.emit(RoomEvent.RedactionCancelled, redactionEvent, this);\n // reapply relation now redaction failed\n if (redactedEvent.isRelation()) {\n this.aggregateNonLiveRelation(redactedEvent);\n }\n }\n }\n\n private assertTimelineSetsAreLive(): void {\n for (let i = 0; i < this.timelineSets.length; i++) {\n const liveTimeline = this.timelineSets[i].getLiveTimeline();\n if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {\n throw new Error(\n \"live timeline \" +\n i +\n \" is no longer live - it has a pagination token \" +\n \"(\" +\n liveTimeline.getPaginationToken(EventTimeline.FORWARDS) +\n \")\",\n );\n }\n if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) {\n throw new Error(`live timeline ${i} is no longer live - it has a neighbouring timeline`);\n }\n }\n }\n\n /**\n * Add some events to this room. This can include state events, message\n * events and typing notifications. These events are treated as \"live\" so\n * they will go to the end of the timeline.\n *\n * @param events - A list of events to add.\n * @param addLiveEventOptions - addLiveEvent options\n * @throws If `duplicateStrategy` is not falsey, 'replace' or 'ignore'.\n */\n public async addLiveEvents(events: MatrixEvent[], addLiveEventOptions?: IAddLiveEventOptions): Promise<void> {\n const { duplicateStrategy, fromCache, timelineWasEmpty = false } = addLiveEventOptions ?? {};\n if (duplicateStrategy && [\"replace\", \"ignore\"].indexOf(duplicateStrategy) === -1) {\n throw new Error(\"duplicateStrategy MUST be either 'replace' or 'ignore'\");\n }\n\n // sanity check that the live timeline is still live\n this.assertTimelineSetsAreLive();\n\n const threadRoots = this.findThreadRoots(events);\n const eventsByThread: { [threadId: string]: MatrixEvent[] } = {};\n\n const options: IAddLiveEventOptions = {\n duplicateStrategy,\n fromCache,\n timelineWasEmpty,\n };\n\n // List of extra events to check for being parents of any relations encountered\n const neighbouringEvents = [...events];\n\n for (const event of events) {\n // TODO: We should have a filter to say \"only add state event types X Y Z to the timeline\".\n this.processLiveEvent(event);\n\n if (event.getUnsigned().transaction_id) {\n const existingEvent = this.txnToEvent.get(event.getUnsigned().transaction_id!);\n if (existingEvent) {\n // remote echo of an event we sent earlier\n this.handleRemoteEcho(event, existingEvent);\n continue; // we can skip adding the event to the timeline sets, it is already there\n }\n }\n\n let {\n shouldLiveInRoom,\n shouldLiveInThread,\n threadId = \"\",\n } = this.eventShouldLiveIn(event, neighbouringEvents, threadRoots);\n\n if (!shouldLiveInThread && !shouldLiveInRoom && event.isRelation()) {\n try {\n const parentEvent = new MatrixEvent(\n await this.client.fetchRoomEvent(this.roomId, event.relationEventId!),\n );\n neighbouringEvents.push(parentEvent);\n if (parentEvent.threadRootId) {\n threadRoots.add(parentEvent.threadRootId);\n const unsigned = event.getUnsigned();\n unsigned[UNSIGNED_THREAD_ID_FIELD.name] = parentEvent.threadRootId;\n event.setUnsigned(unsigned);\n }\n\n ({\n shouldLiveInRoom,\n shouldLiveInThread,\n threadId = \"\",\n } = this.eventShouldLiveIn(event, neighbouringEvents, threadRoots));\n } catch (e) {\n logger.error(\"Failed to load parent event of unhandled relation\", e);\n }\n }\n\n if (shouldLiveInThread && !eventsByThread[threadId]) {\n eventsByThread[threadId] = [];\n }\n eventsByThread[threadId]?.push(event);\n\n if (shouldLiveInRoom) {\n this.addLiveEvent(event, options);\n } else if (!shouldLiveInThread && event.isRelation()) {\n this.relations.aggregateChildEvent(event);\n }\n }\n\n Object.entries(eventsByThread).forEach(([threadId, threadEvents]) => {\n this.addThreadedEvents(threadId, threadEvents, false);\n });\n }\n\n public partitionThreadedEvents(\n events: MatrixEvent[],\n ): [timelineEvents: MatrixEvent[], threadedEvents: MatrixEvent[], unknownRelations: MatrixEvent[]] {\n // Indices to the events array, for readability\n const ROOM = 0;\n const THREAD = 1;\n const UNKNOWN_RELATION = 2;\n if (this.client.supportsThreads()) {\n const threadRoots = this.findThreadRoots(events);\n return events.reduce<[MatrixEvent[], MatrixEvent[], MatrixEvent[]]>(\n (memo, event: MatrixEvent) => {\n const { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(\n event,\n events,\n threadRoots,\n );\n\n if (shouldLiveInRoom) {\n memo[ROOM].push(event);\n }\n\n if (shouldLiveInThread) {\n event.setThreadId(threadId ?? \"\");\n memo[THREAD].push(event);\n }\n\n if (!shouldLiveInThread && !shouldLiveInRoom) {\n memo[UNKNOWN_RELATION].push(event);\n }\n\n return memo;\n },\n [[], [], []],\n );\n } else {\n // When `threadSupport` is disabled treat all events as timelineEvents\n return [events as MatrixEvent[], [] as MatrixEvent[], [] as MatrixEvent[]];\n }\n }\n\n /**\n * Given some events, find the IDs of all the thread roots that are referred to by them.\n */\n private findThreadRoots(events: MatrixEvent[]): Set<string> {\n const threadRoots = new Set<string>();\n for (const event of events) {\n const threadRootId = event.threadRootId;\n if (threadRootId != undefined) {\n threadRoots.add(threadRootId);\n }\n }\n return threadRoots;\n }\n\n /**\n * Add a receipt event to the room.\n * @param event - The m.receipt event.\n * @param synthetic - True if this event is implicit.\n */\n public addReceipt(event: MatrixEvent, synthetic = false): void {\n const content = event.getContent<ReceiptContent>();\n\n this.roomReceipts.add(content, synthetic);\n\n // TODO: delete the following code when it has been replaced by RoomReceipts\n Object.keys(content).forEach((eventId: string) => {\n Object.keys(content[eventId]).forEach((receiptType: ReceiptType | string) => {\n Object.keys(content[eventId][receiptType]).forEach((userId: string) => {\n const receipt = content[eventId][receiptType][userId] as Receipt;\n const receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === MAIN_ROOM_TIMELINE;\n const receiptDestination: Thread | this | undefined = receiptForMainTimeline\n ? this\n : this.threads.get(receipt.thread_id ?? \"\");\n\n if (receiptDestination) {\n receiptDestination.addReceiptToStructure(\n eventId,\n receiptType as ReceiptType,\n userId,\n receipt,\n synthetic,\n );\n\n // If the read receipt sent for the logged in user matches\n // the last event of the live timeline, then we know for a fact\n // that the user has read that message, so we can mark the room\n // as read and not wait for the remote echo from synapse.\n //\n // This needs to be done after the initial sync as we do not want this\n // logic to run whilst the room is being initialised\n //\n // We only do this for non-synthetic receipts, because\n // our intention is to do this when the user really did\n // just read a message, not when we are e.g. receiving\n // an event during the sync. More explanation at:\n // https://github.com/matrix-org/matrix-js-sdk/issues/3684\n if (!synthetic && this.client.isInitialSyncComplete() && userId === this.client.getUserId()) {\n const lastEvent = receiptDestination.timeline[receiptDestination.timeline.length - 1];\n if (lastEvent && eventId === lastEvent.getId() && userId === lastEvent.getSender()) {\n receiptDestination.setUnread(NotificationCountType.Total, 0);\n receiptDestination.setUnread(NotificationCountType.Highlight, 0);\n }\n }\n } else {\n // The thread does not exist locally, keep the read receipt\n // in a cache locally, and re-apply the `addReceipt` logic\n // when the thread is created\n this.cachedThreadReadReceipts.set(receipt.thread_id!, [\n ...(this.cachedThreadReadReceipts.get(receipt.thread_id!) ?? []),\n { eventId, receiptType, userId, receipt, synthetic },\n ]);\n }\n\n const me = this.client.getUserId();\n // Track the time of the current user's oldest threaded receipt in the room.\n if (userId === me && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) {\n this.oldestThreadedReceiptTs = receipt.ts;\n }\n\n // Track each user's unthreaded read receipt.\n if (!receipt.thread_id && receipt.ts > (this.unthreadedReceipts.get(userId)?.ts ?? 0)) {\n this.unthreadedReceipts.set(userId, receipt);\n }\n });\n });\n });\n // End of code to delete when replaced by RoomReceipts\n\n // send events after we've regenerated the structure & cache, otherwise things that\n // listened for the event would read stale data.\n this.emit(RoomEvent.Receipt, event, this);\n }\n\n /**\n * Adds/handles ephemeral events such as typing notifications and read receipts.\n * @param events - A list of events to process\n */\n public addEphemeralEvents(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === EventType.Typing) {\n this.currentState.setTypingEvent(event);\n } else if (event.getType() === EventType.Receipt) {\n this.addReceipt(event);\n } // else ignore - life is too short for us to care about these events\n }\n }\n\n /**\n * Removes events from this room.\n * @param eventIds - A list of eventIds to remove.\n */\n public removeEvents(eventIds: string[]): void {\n for (const eventId of eventIds) {\n this.removeEvent(eventId);\n }\n }\n\n /**\n * Removes a single event from this room.\n *\n * @param eventId - The id of the event to remove\n *\n * @returns true if the event was removed from any of the room's timeline sets\n */\n public removeEvent(eventId: string): boolean {\n let removedAny = false;\n for (const timelineSet of this.timelineSets) {\n const removed = timelineSet.removeEvent(eventId);\n if (removed) {\n if (removed.isRedaction()) {\n this.revertRedactionLocalEcho(removed);\n }\n removedAny = true;\n }\n }\n return removedAny;\n }\n\n /**\n * Recalculate various aspects of the room, including the room name and\n * room summary. Call this any time the room's current state is modified.\n * May fire \"Room.name\" if the room name is updated.\n *\n * @remarks\n * Fires {@link RoomEvent.Name}\n */\n public recalculate(): void {\n // set fake stripped state events if this is an invite room so logic remains\n // consistent elsewhere.\n const membershipEvent = this.currentState.getStateEvents(EventType.RoomMember, this.myUserId);\n if (membershipEvent) {\n const membership = membershipEvent.getContent().membership;\n this.updateMyMembership(membership!);\n\n if (membership === KnownMembership.Invite) {\n const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];\n strippedStateEvents.forEach((strippedEvent) => {\n const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);\n if (!existingEvent) {\n // set the fake stripped event instead\n this.currentState.setStateEvents([\n new MatrixEvent({\n type: strippedEvent.type,\n state_key: strippedEvent.state_key,\n content: strippedEvent.content,\n event_id: \"$fake\" + Date.now(),\n room_id: this.roomId,\n sender: this.myUserId, // technically a lie\n }),\n ]);\n }\n });\n }\n }\n\n const oldName = this.name;\n this.name = this.calculateRoomName(this.myUserId);\n this.normalizedName = normalize(this.name);\n this.summary = new RoomSummary(this.roomId, {\n title: this.name,\n });\n\n if (oldName !== this.name) {\n this.emit(RoomEvent.Name, this);\n }\n }\n\n /**\n * Update the room-tag event for the room. The previous one is overwritten.\n * @param event - the m.tag event\n */\n public addTags(event: MatrixEvent): void {\n // event content looks like:\n // content: {\n // tags: {\n // $tagName: { $metadata: $value },\n // $tagName: { $metadata: $value },\n // }\n // }\n\n // XXX: do we need to deep copy here?\n this.tags = event.getContent().tags || {};\n\n // XXX: we could do a deep-comparison to see if the tags have really\n // changed - but do we want to bother?\n this.emit(RoomEvent.Tags, event, this);\n }\n\n /**\n * Update the account_data events for this room, overwriting events of the same type.\n * @param events - an array of account_data events to add\n */\n public addAccountData(events: MatrixEvent[]): void {\n for (const event of events) {\n if (event.getType() === \"m.tag\") {\n this.addTags(event);\n }\n const eventType = event.getType();\n const lastEvent = this.accountData.get(eventType);\n this.accountData.set(eventType, event);\n this.emit(RoomEvent.AccountData, event, this, lastEvent);\n }\n }\n\n /**\n * Access account_data event of given event type for this room\n * @param type - the type of account_data event to be accessed\n * @returns the account_data event in question\n */\n public getAccountData(type: EventType | string): MatrixEvent | undefined {\n return this.accountData.get(type);\n }\n\n /**\n * Returns whether the syncing user has permission to send a message in the room\n * @returns true if the user should be permitted to send\n * message events into the room.\n */\n public maySendMessage(): boolean {\n return (\n this.getMyMembership() === KnownMembership.Join &&\n (this.hasEncryptionStateEvent()\n ? this.currentState.maySendEvent(EventType.RoomMessageEncrypted, this.myUserId)\n : this.currentState.maySendEvent(EventType.RoomMessage, this.myUserId))\n );\n }\n\n /**\n * Returns whether the given user has permissions to issue an invite for this room.\n * @param userId - the ID of the Matrix user to check permissions for\n * @returns true if the user should be permitted to issue invites for this room.\n */\n public canInvite(userId: string): boolean {\n let canInvite = this.getMyMembership() === KnownMembership.Join;\n const powerLevelsEvent = this.currentState.getStateEvents(EventType.RoomPowerLevels, \"\");\n const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();\n const me = this.getMember(userId);\n if (powerLevels && me && powerLevels.invite > me.powerLevel) {\n canInvite = false;\n }\n return canInvite;\n }\n\n /**\n * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.\n * @returns the join_rule applied to this room\n */\n public getJoinRule(): JoinRule {\n return this.currentState.getJoinRule();\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getHistoryVisibility(): HistoryVisibility {\n return this.currentState.getHistoryVisibility();\n }\n\n /**\n * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.\n * @returns the history_visibility applied to this room\n */\n public getGuestAccess(): GuestAccess {\n return this.currentState.getGuestAccess();\n }\n\n /**\n * Returns the type of the room from the `m.room.create` event content or undefined if none is set\n * @returns the type of the room.\n */\n public getType(): RoomType | string | undefined {\n const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, \"\");\n if (!createEvent) {\n if (!this.getTypeWarning) {\n logger.warn(\"[getType] Room \" + this.roomId + \" does not have an m.room.create event\");\n this.getTypeWarning = true;\n }\n return undefined;\n }\n return createEvent.getContent()[RoomCreateTypeField];\n }\n\n /**\n * Returns whether the room is a space-room as defined by MSC1772.\n * @returns true if the room's type is RoomType.Space\n */\n public isSpaceRoom(): boolean {\n return this.getType() === RoomType.Space;\n }\n\n /**\n * Returns whether the room is a call-room as defined by MSC3417.\n * @returns true if the room's type is RoomType.UnstableCall\n */\n public isCallRoom(): boolean {\n return this.getType() === RoomType.UnstableCall;\n }\n\n /**\n * Returns whether the room is a video room.\n * @returns true if the room's type is RoomType.ElementVideo\n */\n public isElementVideoRoom(): boolean {\n return this.getType() === RoomType.ElementVideo;\n }\n\n /**\n * Find the predecessor of this room.\n *\n * @param msc3946ProcessDynamicPredecessor - if true, look for an\n * m.room.predecessor state event and use it if found (MSC3946).\n * @returns null if this room has no predecessor. Otherwise, returns\n * the roomId, last eventId and viaServers of the predecessor room.\n *\n * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events\n * as well as m.room.create events to find predecessors.\n *\n * Note: if an m.predecessor event is used, eventId may be undefined\n * since last_known_event_id is optional.\n *\n * Note: viaServers may be undefined, and will definitely be undefined if\n * this predecessor comes from a RoomCreate event (rather than a\n * RoomPredecessor, which has the optional via_servers property).\n */\n public findPredecessor(\n msc3946ProcessDynamicPredecessor = false,\n ): { roomId: string; eventId?: string; viaServers?: string[] } | null {\n const currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);\n if (!currentState) {\n return null;\n }\n return currentState.findPredecessor(msc3946ProcessDynamicPredecessor);\n }\n\n private roomNameGenerator(state: RoomNameState): string {\n if (this.client.roomNameGenerator) {\n const name = this.client.roomNameGenerator(this.roomId, state);\n if (name !== null) {\n return name;\n }\n }\n\n switch (state.type) {\n case RoomNameType.Actual:\n return state.name;\n case RoomNameType.Generated:\n switch (state.subtype) {\n case \"Inviting\":\n return `Inviting ${memberNamesToRoomName(state.names, state.count)}`;\n default:\n return memberNamesToRoomName(state.names, state.count);\n }\n case RoomNameType.EmptyRoom:\n if (state.oldName) {\n return `Empty room (was ${state.oldName})`;\n } else {\n return \"Empty room\";\n }\n }\n }\n\n /**\n * This is an internal method. Calculates the name of the room from the current\n * room state.\n * @param userId - The client's user ID. Used to filter room members\n * correctly.\n * @param ignoreRoomNameEvent - Return the implicit room name that we'd see if there\n * was no m.room.name event.\n * @returns The calculated room name.\n */\n private calculateRoomName(userId: string, ignoreRoomNameEvent = false): string {\n if (!ignoreRoomNameEvent) {\n // check for an alias, if any. for now, assume first alias is the\n // official one.\n const mRoomName = this.currentState.getStateEvents(EventType.RoomName, \"\");\n if (mRoomName?.getContent().name) {\n return this.roomNameGenerator({\n type: RoomNameType.Actual,\n name: mRoomName.getContent().name,\n });\n }\n }\n\n const alias = this.getCanonicalAlias();\n if (alias) {\n return this.roomNameGenerator({\n type: RoomNameType.Actual,\n name: alias,\n });\n }\n\n const joinedMemberCount = this.currentState.getJoinedMemberCount();\n const invitedMemberCount = this.currentState.getInvitedMemberCount();\n // -1 because these numbers include the syncing user\n let inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;\n\n // get service members (e.g. helper bots) for exclusion\n const excludedUserIds = this.getFunctionalMembers();\n\n // get members that are NOT ourselves and are actually in the room.\n let otherNames: string[] = [];\n if (this.summaryHeroes) {\n // if we have a summary, the member state events should be in the room state\n this.summaryHeroes.forEach((userId) => {\n // filter service members\n if (excludedUserIds.includes(userId)) {\n inviteJoinCount--;\n return;\n }\n const member = this.getMember(userId);\n otherNames.push(member ? member.name : userId);\n });\n } else {\n let otherMembers = this.currentState.getMembers().filter((m) => {\n return (\n m.userId !== userId &&\n (m.membership === KnownMembership.Invite || m.membership === KnownMembership.Join)\n );\n });\n otherMembers = otherMembers.filter(({ userId }) => {\n // filter service members\n if (excludedUserIds.includes(userId)) {\n inviteJoinCount--;\n return false;\n }\n return true;\n });\n // make sure members have stable order\n const collator = new Intl.Collator();\n otherMembers.sort((a, b) => collator.compare(a.userId, b.userId));\n // only 5 first members, immitate summaryHeroes\n otherMembers = otherMembers.slice(0, 5);\n otherNames = otherMembers.map((m) => m.name);\n }\n\n if (inviteJoinCount) {\n return this.roomNameGenerator({\n type: RoomNameType.Generated,\n names: otherNames,\n count: inviteJoinCount,\n });\n }\n\n const myMembership = this.getMyMembership();\n // if I have created a room and invited people through\n // 3rd party invites\n if (myMembership == KnownMembership.Join) {\n const thirdPartyInvites = this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);\n\n if (thirdPartyInvites?.length) {\n const thirdPartyNames = thirdPartyInvites.map((i) => {\n return i.getContent().display_name;\n });\n\n return this.roomNameGenerator({\n type: RoomNameType.Generated,\n subtype: \"Inviting\",\n names: thirdPartyNames,\n count: thirdPartyNames.length + 1,\n });\n }\n }\n\n // let's try to figure out who was here before\n let leftNames = otherNames;\n // if we didn't have heroes, try finding them in the room state\n if (!leftNames.length) {\n leftNames = this.currentState\n .getMembers()\n .filter((m) => {\n return (\n m.userId !== userId &&\n m.membership !== KnownMembership.Invite &&\n m.membership !== KnownMembership.Join\n );\n })\n .map((m) => m.name);\n }\n\n let oldName: string | undefined;\n if (leftNames.length) {\n oldName = this.roomNameGenerator({\n type: RoomNameType.Generated,\n names: leftNames,\n count: leftNames.length + 1,\n });\n }\n\n return this.roomNameGenerator({\n type: RoomNameType.EmptyRoom,\n oldName,\n });\n }\n\n /**\n * When we receive a new visibility change event:\n *\n * - store this visibility change alongside the timeline, in case we\n * later need to apply it to an event that we haven't received yet;\n * - if we have already received the event whose visibility has changed,\n * patch it to reflect the visibility change and inform listeners.\n */\n private applyNewVisibilityEvent(event: MatrixEvent): void {\n const visibilityChange = event.asVisibilityChange();\n if (!visibilityChange) {\n // The event is ill-formed.\n return;\n }\n\n // Ignore visibility change events that are not emitted by moderators.\n const userId = event.getSender();\n if (!userId) {\n return;\n }\n const isPowerSufficient =\n (EVENT_VISIBILITY_CHANGE_TYPE.name &&\n this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.name, userId)) ||\n (EVENT_VISIBILITY_CHANGE_TYPE.altName &&\n this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.altName, userId));\n if (!isPowerSufficient) {\n // Powerlevel is insufficient.\n return;\n }\n\n // Record this change in visibility.\n // If the event is not in our timeline and we only receive it later,\n // we may need to apply the visibility change at a later date.\n\n const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId);\n if (visibilityEventsOnOriginalEvent) {\n // It would be tempting to simply erase the latest visibility change\n // but we need to record all of the changes in case the latest change\n // is ever redacted.\n //\n // In practice, linear scans through `visibilityEvents` should be fast.\n // However, to protect against a potential DoS attack, we limit the\n // number of iterations in this loop.\n let index = visibilityEventsOnOriginalEvent.length - 1;\n const min = Math.max(\n 0,\n visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH,\n );\n for (; index >= min; --index) {\n const target = visibilityEventsOnOriginalEvent[index];\n if (target.getTs() < event.getTs()) {\n break;\n }\n }\n if (index === -1) {\n visibilityEventsOnOriginalEvent.unshift(event);\n } else {\n visibilityEventsOnOriginalEvent.splice(index + 1, 0, event);\n }\n } else {\n this.visibilityEvents.set(visibilityChange.eventId, [event]);\n }\n\n // Finally, let's check if the event is already in our timeline.\n // If so, we need to patch it and inform listeners.\n\n const originalEvent = this.findEventById(visibilityChange.eventId);\n if (!originalEvent) {\n return;\n }\n originalEvent.applyVisibilityEvent(visibilityChange);\n }\n\n private redactVisibilityChangeEvent(event: MatrixEvent): void {\n // Sanity checks.\n if (!event.isVisibilityEvent) {\n throw new Error(\"expected a visibility change event\");\n }\n const relation = event.getRelation();\n const originalEventId = relation?.event_id;\n const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId!);\n if (!visibilityEventsOnOriginalEvent) {\n // No visibility changes on the original event.\n // In particular, this change event was not recorded,\n // most likely because it was ill-formed.\n return;\n }\n const index = visibilityEventsOnOriginalEvent.findIndex((change) => change.getId() === event.getId());\n if (index === -1) {\n // This change event was not recorded, most likely because\n // it was ill-formed.\n return;\n }\n // Remove visibility change.\n visibilityEventsOnOriginalEvent.splice(index, 1);\n\n // If we removed the latest visibility change event, propagate changes.\n if (index === visibilityEventsOnOriginalEvent.length) {\n const originalEvent = this.findEventById(originalEventId!);\n if (!originalEvent) {\n return;\n }\n if (index === 0) {\n // We have just removed the only visibility change event.\n this.visibilityEvents.delete(originalEventId!);\n originalEvent.applyVisibilityEvent();\n } else {\n const newEvent = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1];\n const newVisibility = newEvent.asVisibilityChange();\n if (!newVisibility) {\n // Event is ill-formed.\n // This breaks our invariant.\n throw new Error(\"at this stage, visibility changes should be well-formed\");\n }\n originalEvent.applyVisibilityEvent(newVisibility);\n }\n }\n }\n\n /**\n * When we receive an event whose visibility has been altered by\n * a (more recent) visibility change event, patch the event in\n * place so that clients now not to display it.\n *\n * @param event - Any matrix event. If this event has at least one a\n * pending visibility change event, apply the latest visibility\n * change event.\n */\n private applyPendingVisibilityEvents(event: MatrixEvent): void {\n const visibilityEvents = this.visibilityEvents.get(event.getId()!);\n if (!visibilityEvents || visibilityEvents.length == 0) {\n // No pending visibility change in store.\n return;\n }\n const visibilityEvent = visibilityEvents[visibilityEvents.length - 1];\n const visibilityChange = visibilityEvent.asVisibilityChange();\n if (!visibilityChange) {\n return;\n }\n if (visibilityChange.visible) {\n // Events are visible by default, no need to apply a visibility change.\n // Note that we need to keep the visibility changes in `visibilityEvents`,\n // in case we later fetch an older visibility change event that is superseded\n // by `visibilityChange`.\n }\n if (visibilityEvent.getTs() < event.getTs()) {\n // Something is wrong, the visibility change cannot happen before the\n // event. Presumably an ill-formed event.\n return;\n }\n event.applyVisibilityEvent(visibilityChange);\n }\n\n /**\n * Find when a client has gained thread capabilities by inspecting the oldest\n * threaded receipt\n * @returns the timestamp of the oldest threaded receipt\n */\n public getOldestThreadedReceiptTs(): number {\n return this.oldestThreadedReceiptTs;\n }\n\n /**\n * Determines if the given user has read a particular event ID with the known\n * history of the room. This is not a definitive check as it relies only on\n * what is available to the room at the time of execution.\n *\n * @param userId - The user ID to check the read state of.\n * @param eventId - The event ID to check if the user read.\n * @returns true if the user has read the event, false otherwise.\n */\n public hasUserReadEvent(userId: string, eventId: string): boolean {\n return this.roomReceipts.hasUserReadEvent(userId, eventId);\n }\n\n /**\n * Returns the most recent unthreaded receipt for a given user\n * @param userId - the MxID of the User\n * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled\n * or a user chooses to use private read receipts (or we have simply not received\n * a receipt from this user yet).\n */\n public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {\n return this.unthreadedReceipts.get(userId);\n }\n\n /**\n * This issue should also be addressed on synapse's side and is tracked as part\n * of https://github.com/matrix-org/synapse/issues/14837\n *\n *\n * We consider a room fully read if the current user has sent\n * the last event in the live timeline of that context and if the read receipt\n * we have on record matches.\n * This also detects all unread threads and applies the same logic to those\n * contexts\n */\n public fixupNotifications(userId: string): void {\n super.fixupNotifications(userId);\n\n const unreadThreads = this.getThreads().filter(\n (thread) => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0,\n );\n\n for (const thread of unreadThreads) {\n thread.fixupNotifications(userId);\n }\n }\n\n /**\n * Determine the order of two events in this room.\n *\n * In principle this should use the same order as the server, but in practice\n * this is difficult for events that were not received over the Sync API. See\n * MSC4033 for details.\n *\n * This implementation leans on the order of events within their timelines, and\n * falls back to comparing event timestamps when they are in different\n * timelines.\n *\n * See https://github.com/matrix-org/matrix-js-sdk/issues/3325 for where we are\n * tracking the work to fix this.\n *\n * @param leftEventId - the id of the first event\n * @param rightEventId - the id of the second event\n\n * @returns -1 if left \\< right, 1 if left \\> right, 0 if left == right, null if\n * we can't tell (because we can't find the events).\n */\n public compareEventOrdering(leftEventId: string, rightEventId: string): number | null {\n return compareEventOrdering(this, leftEventId, rightEventId);\n }\n\n /**\n * Return true if this room has an `m.room.encryption` state event.\n *\n * If this returns `true`, events sent to this room should be encrypted (and `MatrixClient.sendEvent` and friends\n * will encrypt outgoing events).\n */\n public hasEncryptionStateEvent(): boolean {\n return Boolean(\n this.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(EventType.RoomEncryption, \"\"),\n );\n }\n}\n\n// a map from current event status to a list of allowed next statuses\nconst ALLOWED_TRANSITIONS: Record<EventStatus, EventStatus[]> = {\n [EventStatus.ENCRYPTING]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n [EventStatus.SENDING]: [EventStatus.ENCRYPTING, EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.SENT],\n [EventStatus.QUEUED]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],\n [EventStatus.SENT]: [],\n [EventStatus.NOT_SENT]: [EventStatus.SENDING, EventStatus.QUEUED, EventStatus.CANCELLED],\n [EventStatus.CANCELLED]: [],\n};\n\nexport enum RoomNameType {\n EmptyRoom,\n Generated,\n Actual,\n}\n\nexport interface EmptyRoomNameState {\n type: RoomNameType.EmptyRoom;\n oldName?: string;\n}\n\nexport interface GeneratedRoomNameState {\n type: RoomNameType.Generated;\n subtype?: \"Inviting\";\n names: string[];\n count: number;\n}\n\nexport interface ActualRoomNameState {\n type: RoomNameType.Actual;\n name: string;\n}\n\nexport type RoomNameState = EmptyRoomNameState | GeneratedRoomNameState | ActualRoomNameState;\n\n// Can be overriden by IMatrixClientCreateOpts::memberNamesToRoomNameFn\nfunction memberNamesToRoomName(names: string[], count: number): string {\n const countWithoutMe = count - 1;\n if (!names.length) {\n return \"Empty room\";\n } else if (names.length === 1 && countWithoutMe <= 1) {\n return names[0];\n } else if (names.length === 2 && countWithoutMe <= 2) {\n return `${names[0]} and ${names[1]}`;\n } else {\n const plural = countWithoutMe > 1;\n if (plural) {\n return `${names[0]} and ${countWithoutMe} others`;\n } else {\n return `${names[0]} and 1 other`;\n }\n }\n}\n"],"mappings":";;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,YAAY,QAAkB,mBAAmB;AAE1D,SACIC,gBAAgB,EAChBC,iBAAiB,QAGd,yBAAyB;AAChC,SAASC,SAAS,EAAEC,aAAa,QAAQ,qBAAqB;AAC9D,SAASC,gBAAgB,QAAQ,oBAAoB;AACrD,SAASC,aAAa,QAAQ,aAAa;AAC3C,SAASC,SAAS,EAAEC,kBAAkB,QAAQ,aAAa;AAC3D,SAA6CC,WAAW,EAAEC,gBAAgB,QAA+B,YAAY;AACrH,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,SAASC,UAAU,QAAQ,kBAAkB;AAC7C,SAAuBC,WAAW,QAAQ,mBAAmB;AAC7D,SAASC,MAAM,QAAQ,cAAc;AACrC,SAASC,cAAc,QAAQ,iBAAiB;AAChD,SACIC,SAAS,EACTC,mBAAmB,EACnBC,QAAQ,EACRC,iCAAiC,E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