@textrp/briij-js-sdk 41.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1104) hide show
  1. package/CHANGELOG.md +6464 -0
  2. package/LICENSE +177 -0
  3. package/README.md +477 -0
  4. package/lib/@types/AESEncryptedSecretStoragePayload.d.ts +14 -0
  5. package/lib/@types/AESEncryptedSecretStoragePayload.d.ts.map +1 -0
  6. package/lib/@types/AESEncryptedSecretStoragePayload.js +1 -0
  7. package/lib/@types/AESEncryptedSecretStoragePayload.js.map +1 -0
  8. package/lib/@types/IIdentityServerProvider.d.ts +9 -0
  9. package/lib/@types/IIdentityServerProvider.d.ts.map +1 -0
  10. package/lib/@types/IIdentityServerProvider.js +1 -0
  11. package/lib/@types/IIdentityServerProvider.js.map +1 -0
  12. package/lib/@types/PushRules.d.ts +140 -0
  13. package/lib/@types/PushRules.d.ts.map +1 -0
  14. package/lib/@types/PushRules.js +94 -0
  15. package/lib/@types/PushRules.js.map +1 -0
  16. package/lib/@types/another-json.d.js +0 -0
  17. package/lib/@types/another-json.d.js.map +1 -0
  18. package/lib/@types/auth.d.ts +213 -0
  19. package/lib/@types/auth.d.ts.map +1 -0
  20. package/lib/@types/auth.js +107 -0
  21. package/lib/@types/auth.js.map +1 -0
  22. package/lib/@types/beacon.d.ts +106 -0
  23. package/lib/@types/beacon.d.ts.map +1 -0
  24. package/lib/@types/beacon.js +119 -0
  25. package/lib/@types/beacon.js.map +1 -0
  26. package/lib/@types/common.d.ts +10 -0
  27. package/lib/@types/common.d.ts.map +1 -0
  28. package/lib/@types/common.js +1 -0
  29. package/lib/@types/common.js.map +1 -0
  30. package/lib/@types/crypto.d.ts +46 -0
  31. package/lib/@types/crypto.d.ts.map +1 -0
  32. package/lib/@types/crypto.js +1 -0
  33. package/lib/@types/crypto.js.map +1 -0
  34. package/lib/@types/event.d.ts +356 -0
  35. package/lib/@types/event.d.ts.map +1 -0
  36. package/lib/@types/event.js +280 -0
  37. package/lib/@types/event.js.map +1 -0
  38. package/lib/@types/events.d.ts +92 -0
  39. package/lib/@types/events.d.ts.map +1 -0
  40. package/lib/@types/events.js +1 -0
  41. package/lib/@types/events.js.map +1 -0
  42. package/lib/@types/extensible_events.d.ts +98 -0
  43. package/lib/@types/extensible_events.d.ts.map +1 -0
  44. package/lib/@types/extensible_events.js +116 -0
  45. package/lib/@types/extensible_events.js.map +1 -0
  46. package/lib/@types/global.d.js +18 -0
  47. package/lib/@types/global.d.js.map +1 -0
  48. package/lib/@types/local_notifications.d.ts +4 -0
  49. package/lib/@types/local_notifications.d.ts.map +1 -0
  50. package/lib/@types/local_notifications.js +1 -0
  51. package/lib/@types/local_notifications.js.map +1 -0
  52. package/lib/@types/location.d.ts +60 -0
  53. package/lib/@types/location.d.ts.map +1 -0
  54. package/lib/@types/location.js +66 -0
  55. package/lib/@types/location.js.map +1 -0
  56. package/lib/@types/matrix-sdk-crypto-wasm.d.js +1 -0
  57. package/lib/@types/matrix-sdk-crypto-wasm.d.js.map +1 -0
  58. package/lib/@types/media.d.ts +220 -0
  59. package/lib/@types/media.d.ts.map +1 -0
  60. package/lib/@types/media.js +1 -0
  61. package/lib/@types/media.js.map +1 -0
  62. package/lib/@types/membership.d.ts +41 -0
  63. package/lib/@types/membership.d.ts.map +1 -0
  64. package/lib/@types/membership.js +58 -0
  65. package/lib/@types/membership.js.map +1 -0
  66. package/lib/@types/partials.d.ts +72 -0
  67. package/lib/@types/partials.d.ts.map +1 -0
  68. package/lib/@types/partials.js +71 -0
  69. package/lib/@types/partials.js.map +1 -0
  70. package/lib/@types/polls.d.ts +89 -0
  71. package/lib/@types/polls.d.ts.map +1 -0
  72. package/lib/@types/polls.js +86 -0
  73. package/lib/@types/polls.js.map +1 -0
  74. package/lib/@types/read_receipts.d.ts +36 -0
  75. package/lib/@types/read_receipts.d.ts.map +1 -0
  76. package/lib/@types/read_receipts.js +27 -0
  77. package/lib/@types/read_receipts.js.map +1 -0
  78. package/lib/@types/registration.d.ts +85 -0
  79. package/lib/@types/registration.d.ts.map +1 -0
  80. package/lib/@types/registration.js +1 -0
  81. package/lib/@types/registration.js.map +1 -0
  82. package/lib/@types/requests.d.ts +267 -0
  83. package/lib/@types/requests.d.ts.map +1 -0
  84. package/lib/@types/requests.js +42 -0
  85. package/lib/@types/requests.js.map +1 -0
  86. package/lib/@types/search.d.ts +90 -0
  87. package/lib/@types/search.d.ts.map +1 -0
  88. package/lib/@types/search.js +30 -0
  89. package/lib/@types/search.js.map +1 -0
  90. package/lib/@types/signed.d.ts +9 -0
  91. package/lib/@types/signed.d.ts.map +1 -0
  92. package/lib/@types/signed.js +1 -0
  93. package/lib/@types/signed.js.map +1 -0
  94. package/lib/@types/spaces.d.ts +16 -0
  95. package/lib/@types/spaces.d.ts.map +1 -0
  96. package/lib/@types/spaces.js +1 -0
  97. package/lib/@types/spaces.js.map +1 -0
  98. package/lib/@types/state_events.d.ts +121 -0
  99. package/lib/@types/state_events.d.ts.map +1 -0
  100. package/lib/@types/state_events.js +1 -0
  101. package/lib/@types/state_events.js.map +1 -0
  102. package/lib/@types/synapse.d.ts +19 -0
  103. package/lib/@types/synapse.d.ts.map +1 -0
  104. package/lib/@types/synapse.js +1 -0
  105. package/lib/@types/synapse.js.map +1 -0
  106. package/lib/@types/sync.d.ts +8 -0
  107. package/lib/@types/sync.d.ts.map +1 -0
  108. package/lib/@types/sync.js +25 -0
  109. package/lib/@types/sync.js.map +1 -0
  110. package/lib/@types/threepids.d.ts +12 -0
  111. package/lib/@types/threepids.d.ts.map +1 -0
  112. package/lib/@types/threepids.js +24 -0
  113. package/lib/@types/threepids.js.map +1 -0
  114. package/lib/@types/topic.d.ts +55 -0
  115. package/lib/@types/topic.d.ts.map +1 -0
  116. package/lib/@types/topic.js +62 -0
  117. package/lib/@types/topic.js.map +1 -0
  118. package/lib/@types/uia.d.ts +8 -0
  119. package/lib/@types/uia.d.ts.map +1 -0
  120. package/lib/@types/uia.js +1 -0
  121. package/lib/@types/uia.js.map +1 -0
  122. package/lib/NamespacedValue.d.ts +32 -0
  123. package/lib/NamespacedValue.d.ts.map +1 -0
  124. package/lib/NamespacedValue.js +113 -0
  125. package/lib/NamespacedValue.js.map +1 -0
  126. package/lib/ReEmitter.d.ts +15 -0
  127. package/lib/ReEmitter.d.ts.map +1 -0
  128. package/lib/ReEmitter.js +87 -0
  129. package/lib/ReEmitter.js.map +1 -0
  130. package/lib/ToDeviceMessageQueue.d.ts +30 -0
  131. package/lib/ToDeviceMessageQueue.d.ts.map +1 -0
  132. package/lib/ToDeviceMessageQueue.js +135 -0
  133. package/lib/ToDeviceMessageQueue.js.map +1 -0
  134. package/lib/autodiscovery.d.ts +136 -0
  135. package/lib/autodiscovery.d.ts.map +1 -0
  136. package/lib/autodiscovery.js +464 -0
  137. package/lib/autodiscovery.js.map +1 -0
  138. package/lib/base64.d.ts +25 -0
  139. package/lib/base64.d.ts.map +1 -0
  140. package/lib/base64.js +95 -0
  141. package/lib/base64.js.map +1 -0
  142. package/lib/briij.d.ts +116 -0
  143. package/lib/briij.d.ts.map +1 -0
  144. package/lib/briij.js +145 -0
  145. package/lib/briij.js.map +1 -0
  146. package/lib/browser-index.d.ts +8 -0
  147. package/lib/browser-index.d.ts.map +1 -0
  148. package/lib/browser-index.js +35 -0
  149. package/lib/browser-index.js.map +1 -0
  150. package/lib/client.d.ts +3493 -0
  151. package/lib/client.d.ts.map +1 -0
  152. package/lib/client.js +7482 -0
  153. package/lib/client.js.map +1 -0
  154. package/lib/common-crypto/CryptoBackend.d.ts +234 -0
  155. package/lib/common-crypto/CryptoBackend.d.ts.map +1 -0
  156. package/lib/common-crypto/CryptoBackend.js +69 -0
  157. package/lib/common-crypto/CryptoBackend.js.map +1 -0
  158. package/lib/common-crypto/key-passphrase.d.ts +14 -0
  159. package/lib/common-crypto/key-passphrase.d.ts.map +1 -0
  160. package/lib/common-crypto/key-passphrase.js +33 -0
  161. package/lib/common-crypto/key-passphrase.js.map +1 -0
  162. package/lib/content-helpers.d.ts +90 -0
  163. package/lib/content-helpers.d.ts.map +1 -0
  164. package/lib/content-helpers.js +262 -0
  165. package/lib/content-helpers.js.map +1 -0
  166. package/lib/content-repo.d.ts +25 -0
  167. package/lib/content-repo.d.ts.map +1 -0
  168. package/lib/content-repo.js +109 -0
  169. package/lib/content-repo.js.map +1 -0
  170. package/lib/crypto/store/base.d.ts +301 -0
  171. package/lib/crypto/store/base.d.ts.map +1 -0
  172. package/lib/crypto/store/base.js +145 -0
  173. package/lib/crypto/store/base.js.map +1 -0
  174. package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts +94 -0
  175. package/lib/crypto/store/indexeddb-crypto-store-backend.d.ts.map +1 -0
  176. package/lib/crypto/store/indexeddb-crypto-store-backend.js +604 -0
  177. package/lib/crypto/store/indexeddb-crypto-store-backend.js.map +1 -0
  178. package/lib/crypto/store/indexeddb-crypto-store.d.ts +251 -0
  179. package/lib/crypto/store/indexeddb-crypto-store.d.ts.map +1 -0
  180. package/lib/crypto/store/indexeddb-crypto-store.js +477 -0
  181. package/lib/crypto/store/indexeddb-crypto-store.js.map +1 -0
  182. package/lib/crypto/store/localStorage-crypto-store.d.ts +102 -0
  183. package/lib/crypto/store/localStorage-crypto-store.d.ts.map +1 -0
  184. package/lib/crypto/store/localStorage-crypto-store.js +374 -0
  185. package/lib/crypto/store/localStorage-crypto-store.js.map +1 -0
  186. package/lib/crypto/store/memory-crypto-store.d.ts +117 -0
  187. package/lib/crypto/store/memory-crypto-store.d.ts.map +1 -0
  188. package/lib/crypto/store/memory-crypto-store.js +311 -0
  189. package/lib/crypto/store/memory-crypto-store.js.map +1 -0
  190. package/lib/crypto-api/CryptoEvent.d.ts +120 -0
  191. package/lib/crypto-api/CryptoEvent.d.ts.map +1 -0
  192. package/lib/crypto-api/CryptoEvent.js +137 -0
  193. package/lib/crypto-api/CryptoEvent.js.map +1 -0
  194. package/lib/crypto-api/CryptoEventHandlerMap.d.ts +26 -0
  195. package/lib/crypto-api/CryptoEventHandlerMap.d.ts.map +1 -0
  196. package/lib/crypto-api/CryptoEventHandlerMap.js +1 -0
  197. package/lib/crypto-api/CryptoEventHandlerMap.js.map +1 -0
  198. package/lib/crypto-api/index.d.ts +1160 -0
  199. package/lib/crypto-api/index.d.ts.map +1 -0
  200. package/lib/crypto-api/index.js +410 -0
  201. package/lib/crypto-api/index.js.map +1 -0
  202. package/lib/crypto-api/key-passphrase.d.ts +11 -0
  203. package/lib/crypto-api/key-passphrase.d.ts.map +1 -0
  204. package/lib/crypto-api/key-passphrase.js +51 -0
  205. package/lib/crypto-api/key-passphrase.js.map +1 -0
  206. package/lib/crypto-api/keybackup.d.ts +87 -0
  207. package/lib/crypto-api/keybackup.d.ts.map +1 -0
  208. package/lib/crypto-api/keybackup.js +1 -0
  209. package/lib/crypto-api/keybackup.js.map +1 -0
  210. package/lib/crypto-api/recovery-key.d.ts +11 -0
  211. package/lib/crypto-api/recovery-key.d.ts.map +1 -0
  212. package/lib/crypto-api/recovery-key.js +65 -0
  213. package/lib/crypto-api/recovery-key.js.map +1 -0
  214. package/lib/crypto-api/verification.d.ts +315 -0
  215. package/lib/crypto-api/verification.d.ts.map +1 -0
  216. package/lib/crypto-api/verification.js +130 -0
  217. package/lib/crypto-api/verification.js.map +1 -0
  218. package/lib/digest.d.ts +10 -0
  219. package/lib/digest.d.ts.map +1 -0
  220. package/lib/digest.js +40 -0
  221. package/lib/digest.js.map +1 -0
  222. package/lib/embedded.d.ts +182 -0
  223. package/lib/embedded.d.ts.map +1 -0
  224. package/lib/embedded.js +746 -0
  225. package/lib/embedded.js.map +1 -0
  226. package/lib/errors.d.ts +38 -0
  227. package/lib/errors.d.ts.map +1 -0
  228. package/lib/errors.js +73 -0
  229. package/lib/errors.js.map +1 -0
  230. package/lib/event-mapper.d.ts +9 -0
  231. package/lib/event-mapper.d.ts.map +1 -0
  232. package/lib/event-mapper.js +74 -0
  233. package/lib/event-mapper.js.map +1 -0
  234. package/lib/extensible_events_v1/ExtensibleEvent.d.ts +38 -0
  235. package/lib/extensible_events_v1/ExtensibleEvent.d.ts.map +1 -0
  236. package/lib/extensible_events_v1/ExtensibleEvent.js +57 -0
  237. package/lib/extensible_events_v1/ExtensibleEvent.js.map +1 -0
  238. package/lib/extensible_events_v1/InvalidEventError.d.ts +7 -0
  239. package/lib/extensible_events_v1/InvalidEventError.d.ts.map +1 -0
  240. package/lib/extensible_events_v1/InvalidEventError.js +25 -0
  241. package/lib/extensible_events_v1/InvalidEventError.js.map +1 -0
  242. package/lib/extensible_events_v1/MessageEvent.d.ts +44 -0
  243. package/lib/extensible_events_v1/MessageEvent.d.ts.map +1 -0
  244. package/lib/extensible_events_v1/MessageEvent.js +134 -0
  245. package/lib/extensible_events_v1/MessageEvent.js.map +1 -0
  246. package/lib/extensible_events_v1/PollEndEvent.d.ts +33 -0
  247. package/lib/extensible_events_v1/PollEndEvent.d.ts.map +1 -0
  248. package/lib/extensible_events_v1/PollEndEvent.js +88 -0
  249. package/lib/extensible_events_v1/PollEndEvent.js.map +1 -0
  250. package/lib/extensible_events_v1/PollResponseEvent.d.ts +49 -0
  251. package/lib/extensible_events_v1/PollResponseEvent.d.ts.map +1 -0
  252. package/lib/extensible_events_v1/PollResponseEvent.js +135 -0
  253. package/lib/extensible_events_v1/PollResponseEvent.js.map +1 -0
  254. package/lib/extensible_events_v1/PollStartEvent.d.ts +71 -0
  255. package/lib/extensible_events_v1/PollStartEvent.d.ts.map +1 -0
  256. package/lib/extensible_events_v1/PollStartEvent.js +185 -0
  257. package/lib/extensible_events_v1/PollStartEvent.js.map +1 -0
  258. package/lib/extensible_events_v1/utilities.d.ts +14 -0
  259. package/lib/extensible_events_v1/utilities.d.ts.map +1 -0
  260. package/lib/extensible_events_v1/utilities.js +34 -0
  261. package/lib/extensible_events_v1/utilities.js.map +1 -0
  262. package/lib/feature.d.ts +20 -0
  263. package/lib/feature.d.ts.map +1 -0
  264. package/lib/feature.js +89 -0
  265. package/lib/feature.js.map +1 -0
  266. package/lib/filter-component.d.ts +64 -0
  267. package/lib/filter-component.d.ts.map +1 -0
  268. package/lib/filter-component.js +170 -0
  269. package/lib/filter-component.js.map +1 -0
  270. package/lib/filter.d.ts +97 -0
  271. package/lib/filter.d.ts.map +1 -0
  272. package/lib/filter.js +207 -0
  273. package/lib/filter.js.map +1 -0
  274. package/lib/http-api/errors.d.ts +117 -0
  275. package/lib/http-api/errors.d.ts.map +1 -0
  276. package/lib/http-api/errors.js +245 -0
  277. package/lib/http-api/errors.js.map +1 -0
  278. package/lib/http-api/fetch.d.ts +80 -0
  279. package/lib/http-api/fetch.d.ts.map +1 -0
  280. package/lib/http-api/fetch.js +332 -0
  281. package/lib/http-api/fetch.js.map +1 -0
  282. package/lib/http-api/index.d.ts +33 -0
  283. package/lib/http-api/index.d.ts.map +1 -0
  284. package/lib/http-api/index.js +178 -0
  285. package/lib/http-api/index.js.map +1 -0
  286. package/lib/http-api/interface.d.ts +186 -0
  287. package/lib/http-api/interface.d.ts.map +1 -0
  288. package/lib/http-api/interface.js +39 -0
  289. package/lib/http-api/interface.js.map +1 -0
  290. package/lib/http-api/method.d.ts +10 -0
  291. package/lib/http-api/method.d.ts.map +1 -0
  292. package/lib/http-api/method.js +27 -0
  293. package/lib/http-api/method.js.map +1 -0
  294. package/lib/http-api/prefix.d.ts +31 -0
  295. package/lib/http-api/prefix.d.ts.map +1 -0
  296. package/lib/http-api/prefix.js +50 -0
  297. package/lib/http-api/prefix.js.map +1 -0
  298. package/lib/http-api/refresh.d.ts +53 -0
  299. package/lib/http-api/refresh.d.ts.map +1 -0
  300. package/lib/http-api/refresh.js +174 -0
  301. package/lib/http-api/refresh.js.map +1 -0
  302. package/lib/http-api/utils.d.ts +37 -0
  303. package/lib/http-api/utils.d.ts.map +1 -0
  304. package/lib/http-api/utils.js +182 -0
  305. package/lib/http-api/utils.js.map +1 -0
  306. package/lib/index.d.ts +4 -0
  307. package/lib/index.d.ts.map +1 -0
  308. package/lib/index.js +24 -0
  309. package/lib/index.js.map +1 -0
  310. package/lib/indexeddb-helpers.d.ts +10 -0
  311. package/lib/indexeddb-helpers.d.ts.map +1 -0
  312. package/lib/indexeddb-helpers.js +51 -0
  313. package/lib/indexeddb-helpers.js.map +1 -0
  314. package/lib/indexeddb-worker.d.ts +7 -0
  315. package/lib/indexeddb-worker.d.ts.map +1 -0
  316. package/lib/indexeddb-worker.js +25 -0
  317. package/lib/indexeddb-worker.js.map +1 -0
  318. package/lib/interactive-auth.d.ts +341 -0
  319. package/lib/interactive-auth.d.ts.map +1 -0
  320. package/lib/interactive-auth.js +563 -0
  321. package/lib/interactive-auth.js.map +1 -0
  322. package/lib/logger.d.ts +124 -0
  323. package/lib/logger.d.ts.map +1 -0
  324. package/lib/logger.js +230 -0
  325. package/lib/logger.js.map +1 -0
  326. package/lib/matrixrtc/CallMembership.d.ts +154 -0
  327. package/lib/matrixrtc/CallMembership.d.ts.map +1 -0
  328. package/lib/matrixrtc/CallMembership.js +469 -0
  329. package/lib/matrixrtc/CallMembership.js.map +1 -0
  330. package/lib/matrixrtc/EncryptionManager.d.ts +44 -0
  331. package/lib/matrixrtc/EncryptionManager.d.ts.map +1 -0
  332. package/lib/matrixrtc/EncryptionManager.js +13 -0
  333. package/lib/matrixrtc/EncryptionManager.js.map +1 -0
  334. package/lib/matrixrtc/IKeyTransport.d.ts +37 -0
  335. package/lib/matrixrtc/IKeyTransport.d.ts.map +1 -0
  336. package/lib/matrixrtc/IKeyTransport.js +27 -0
  337. package/lib/matrixrtc/IKeyTransport.js.map +1 -0
  338. package/lib/matrixrtc/IMembershipManager.d.ts +94 -0
  339. package/lib/matrixrtc/IMembershipManager.d.ts.map +1 -0
  340. package/lib/matrixrtc/IMembershipManager.js +40 -0
  341. package/lib/matrixrtc/IMembershipManager.js.map +1 -0
  342. package/lib/matrixrtc/LivekitTransport.d.ts +23 -0
  343. package/lib/matrixrtc/LivekitTransport.d.ts.map +1 -0
  344. package/lib/matrixrtc/LivekitTransport.js +29 -0
  345. package/lib/matrixrtc/LivekitTransport.js.map +1 -0
  346. package/lib/matrixrtc/MatrixRTCSession.d.ts +343 -0
  347. package/lib/matrixrtc/MatrixRTCSession.d.ts.map +1 -0
  348. package/lib/matrixrtc/MatrixRTCSession.js +623 -0
  349. package/lib/matrixrtc/MatrixRTCSession.js.map +1 -0
  350. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts +46 -0
  351. package/lib/matrixrtc/MatrixRTCSessionManager.d.ts.map +1 -0
  352. package/lib/matrixrtc/MatrixRTCSessionManager.js +149 -0
  353. package/lib/matrixrtc/MatrixRTCSessionManager.js.map +1 -0
  354. package/lib/matrixrtc/MembershipManager.d.ts +210 -0
  355. package/lib/matrixrtc/MembershipManager.d.ts.map +1 -0
  356. package/lib/matrixrtc/MembershipManager.js +977 -0
  357. package/lib/matrixrtc/MembershipManager.js.map +1 -0
  358. package/lib/matrixrtc/MembershipManagerActionScheduler.d.ts +59 -0
  359. package/lib/matrixrtc/MembershipManagerActionScheduler.d.ts.map +1 -0
  360. package/lib/matrixrtc/MembershipManagerActionScheduler.js +125 -0
  361. package/lib/matrixrtc/MembershipManagerActionScheduler.js.map +1 -0
  362. package/lib/matrixrtc/RTCEncryptionManager.d.ts +110 -0
  363. package/lib/matrixrtc/RTCEncryptionManager.d.ts.map +1 -0
  364. package/lib/matrixrtc/RTCEncryptionManager.js +376 -0
  365. package/lib/matrixrtc/RTCEncryptionManager.js.map +1 -0
  366. package/lib/matrixrtc/ToDeviceKeyTransport.d.ts +30 -0
  367. package/lib/matrixrtc/ToDeviceKeyTransport.d.ts.map +1 -0
  368. package/lib/matrixrtc/ToDeviceKeyTransport.js +164 -0
  369. package/lib/matrixrtc/ToDeviceKeyTransport.js.map +1 -0
  370. package/lib/matrixrtc/index.d.ts +9 -0
  371. package/lib/matrixrtc/index.d.ts.map +1 -0
  372. package/lib/matrixrtc/index.js +23 -0
  373. package/lib/matrixrtc/index.js.map +1 -0
  374. package/lib/matrixrtc/membershipData/common.d.ts +8 -0
  375. package/lib/matrixrtc/membershipData/common.d.ts.map +1 -0
  376. package/lib/matrixrtc/membershipData/common.js +26 -0
  377. package/lib/matrixrtc/membershipData/common.js.map +1 -0
  378. package/lib/matrixrtc/membershipData/index.d.ts +4 -0
  379. package/lib/matrixrtc/membershipData/index.d.ts.map +1 -0
  380. package/lib/matrixrtc/membershipData/index.js +20 -0
  381. package/lib/matrixrtc/membershipData/index.js.map +1 -0
  382. package/lib/matrixrtc/membershipData/rtc.d.ts +33 -0
  383. package/lib/matrixrtc/membershipData/rtc.d.ts.map +1 -0
  384. package/lib/matrixrtc/membershipData/rtc.js +137 -0
  385. package/lib/matrixrtc/membershipData/rtc.js.map +1 -0
  386. package/lib/matrixrtc/membershipData/session.d.ts +77 -0
  387. package/lib/matrixrtc/membershipData/session.d.ts.map +1 -0
  388. package/lib/matrixrtc/membershipData/session.js +62 -0
  389. package/lib/matrixrtc/membershipData/session.js.map +1 -0
  390. package/lib/matrixrtc/types.d.ts +169 -0
  391. package/lib/matrixrtc/types.d.ts.map +1 -0
  392. package/lib/matrixrtc/types.js +117 -0
  393. package/lib/matrixrtc/types.js.map +1 -0
  394. package/lib/matrixrtc/utils.d.ts +27 -0
  395. package/lib/matrixrtc/utils.d.ts.map +1 -0
  396. package/lib/matrixrtc/utils.js +72 -0
  397. package/lib/matrixrtc/utils.js.map +1 -0
  398. package/lib/models/MSC3089Branch.d.ts +98 -0
  399. package/lib/models/MSC3089Branch.d.ts.map +1 -0
  400. package/lib/models/MSC3089Branch.js +240 -0
  401. package/lib/models/MSC3089Branch.js.map +1 -0
  402. package/lib/models/MSC3089TreeSpace.d.ts +166 -0
  403. package/lib/models/MSC3089TreeSpace.d.ts.map +1 -0
  404. package/lib/models/MSC3089TreeSpace.js +521 -0
  405. package/lib/models/MSC3089TreeSpace.js.map +1 -0
  406. package/lib/models/ToDeviceMessage.d.ts +17 -0
  407. package/lib/models/ToDeviceMessage.d.ts.map +1 -0
  408. package/lib/models/ToDeviceMessage.js +1 -0
  409. package/lib/models/ToDeviceMessage.js.map +1 -0
  410. package/lib/models/beacon.d.ts +52 -0
  411. package/lib/models/beacon.d.ts.map +1 -0
  412. package/lib/models/beacon.js +174 -0
  413. package/lib/models/beacon.js.map +1 -0
  414. package/lib/models/compare-event-ordering.d.ts +24 -0
  415. package/lib/models/compare-event-ordering.d.ts.map +1 -0
  416. package/lib/models/compare-event-ordering.js +120 -0
  417. package/lib/models/compare-event-ordering.js.map +1 -0
  418. package/lib/models/device.d.ts +45 -0
  419. package/lib/models/device.d.ts.map +1 -0
  420. package/lib/models/device.js +77 -0
  421. package/lib/models/device.js.map +1 -0
  422. package/lib/models/event-context.d.ts +62 -0
  423. package/lib/models/event-context.d.ts.map +1 -0
  424. package/lib/models/event-context.js +113 -0
  425. package/lib/models/event-context.js.map +1 -0
  426. package/lib/models/event-status.d.ts +19 -0
  427. package/lib/models/event-status.d.ts.map +1 -0
  428. package/lib/models/event-status.js +36 -0
  429. package/lib/models/event-status.js.map +1 -0
  430. package/lib/models/event-timeline-set.d.ts +308 -0
  431. package/lib/models/event-timeline-set.d.ts.map +1 -0
  432. package/lib/models/event-timeline-set.js +805 -0
  433. package/lib/models/event-timeline-set.js.map +1 -0
  434. package/lib/models/event-timeline.d.ts +224 -0
  435. package/lib/models/event-timeline.d.ts.map +1 -0
  436. package/lib/models/event-timeline.js +434 -0
  437. package/lib/models/event-timeline.js.map +1 -0
  438. package/lib/models/event.d.ts +844 -0
  439. package/lib/models/event.d.ts.map +1 -0
  440. package/lib/models/event.js +1600 -0
  441. package/lib/models/event.js.map +1 -0
  442. package/lib/models/invites-ignorer-types.d.ts +27 -0
  443. package/lib/models/invites-ignorer-types.d.ts.map +1 -0
  444. package/lib/models/invites-ignorer-types.js +56 -0
  445. package/lib/models/invites-ignorer-types.js.map +1 -0
  446. package/lib/models/invites-ignorer.d.ts +112 -0
  447. package/lib/models/invites-ignorer.d.ts.map +1 -0
  448. package/lib/models/invites-ignorer.js +357 -0
  449. package/lib/models/invites-ignorer.js.map +1 -0
  450. package/lib/models/poll.d.ts +67 -0
  451. package/lib/models/poll.d.ts.map +1 -0
  452. package/lib/models/poll.js +241 -0
  453. package/lib/models/poll.js.map +1 -0
  454. package/lib/models/profile-keys.d.ts +17 -0
  455. package/lib/models/profile-keys.d.ts.map +1 -0
  456. package/lib/models/profile-keys.js +34 -0
  457. package/lib/models/profile-keys.js.map +1 -0
  458. package/lib/models/read-receipt.d.ts +115 -0
  459. package/lib/models/read-receipt.d.ts.map +1 -0
  460. package/lib/models/read-receipt.js +366 -0
  461. package/lib/models/read-receipt.js.map +1 -0
  462. package/lib/models/related-relations.d.ts +11 -0
  463. package/lib/models/related-relations.d.ts.map +1 -0
  464. package/lib/models/related-relations.js +33 -0
  465. package/lib/models/related-relations.js.map +1 -0
  466. package/lib/models/relations-container.d.ts +44 -0
  467. package/lib/models/relations-container.d.ts.map +1 -0
  468. package/lib/models/relations-container.js +132 -0
  469. package/lib/models/relations-container.js.map +1 -0
  470. package/lib/models/relations.d.ts +123 -0
  471. package/lib/models/relations.d.ts.map +1 -0
  472. package/lib/models/relations.js +378 -0
  473. package/lib/models/relations.js.map +1 -0
  474. package/lib/models/room-member.d.ts +221 -0
  475. package/lib/models/room-member.d.ts.map +1 -0
  476. package/lib/models/room-member.js +376 -0
  477. package/lib/models/room-member.js.map +1 -0
  478. package/lib/models/room-receipts.d.ts +39 -0
  479. package/lib/models/room-receipts.d.ts.map +1 -0
  480. package/lib/models/room-receipts.js +392 -0
  481. package/lib/models/room-receipts.js.map +1 -0
  482. package/lib/models/room-state.d.ts +463 -0
  483. package/lib/models/room-state.d.ts.map +1 -0
  484. package/lib/models/room-state.js +1066 -0
  485. package/lib/models/room-state.js.map +1 -0
  486. package/lib/models/room-sticky-events.d.ts +110 -0
  487. package/lib/models/room-sticky-events.d.ts.map +1 -0
  488. package/lib/models/room-sticky-events.js +353 -0
  489. package/lib/models/room-sticky-events.js.map +1 -0
  490. package/lib/models/room-summary.d.ts +59 -0
  491. package/lib/models/room-summary.d.ts.map +1 -0
  492. package/lib/models/room-summary.js +39 -0
  493. package/lib/models/room-summary.js.map +1 -0
  494. package/lib/models/room.d.ts +1285 -0
  495. package/lib/models/room.d.ts.map +1 -0
  496. package/lib/models/room.js +3548 -0
  497. package/lib/models/room.js.map +1 -0
  498. package/lib/models/search-result.d.ts +20 -0
  499. package/lib/models/search-result.d.ts.map +1 -0
  500. package/lib/models/search-result.js +52 -0
  501. package/lib/models/search-result.js.map +1 -0
  502. package/lib/models/thread.d.ts +245 -0
  503. package/lib/models/thread.d.ts.map +1 -0
  504. package/lib/models/thread.js +866 -0
  505. package/lib/models/thread.js.map +1 -0
  506. package/lib/models/typed-event-emitter.d.ts +157 -0
  507. package/lib/models/typed-event-emitter.d.ts.map +1 -0
  508. package/lib/models/typed-event-emitter.js +227 -0
  509. package/lib/models/typed-event-emitter.js.map +1 -0
  510. package/lib/models/user.d.ts +195 -0
  511. package/lib/models/user.d.ts.map +1 -0
  512. package/lib/models/user.js +218 -0
  513. package/lib/models/user.js.map +1 -0
  514. package/lib/oidc/authorize.d.ts +93 -0
  515. package/lib/oidc/authorize.d.ts.map +1 -0
  516. package/lib/oidc/authorize.js +282 -0
  517. package/lib/oidc/authorize.js.map +1 -0
  518. package/lib/oidc/discovery.d.ts +22 -0
  519. package/lib/oidc/discovery.d.ts.map +1 -0
  520. package/lib/oidc/discovery.js +78 -0
  521. package/lib/oidc/discovery.js.map +1 -0
  522. package/lib/oidc/error.d.ts +18 -0
  523. package/lib/oidc/error.d.ts.map +1 -0
  524. package/lib/oidc/error.js +35 -0
  525. package/lib/oidc/error.js.map +1 -0
  526. package/lib/oidc/index.d.ts +16 -0
  527. package/lib/oidc/index.d.ts.map +1 -0
  528. package/lib/oidc/index.js +29 -0
  529. package/lib/oidc/index.js.map +1 -0
  530. package/lib/oidc/register.d.ts +70 -0
  531. package/lib/oidc/register.d.ts.map +1 -0
  532. package/lib/oidc/register.js +135 -0
  533. package/lib/oidc/register.js.map +1 -0
  534. package/lib/oidc/tokenRefresher.d.ts +91 -0
  535. package/lib/oidc/tokenRefresher.d.ts.map +1 -0
  536. package/lib/oidc/tokenRefresher.js +187 -0
  537. package/lib/oidc/tokenRefresher.js.map +1 -0
  538. package/lib/oidc/validate.d.ts +78 -0
  539. package/lib/oidc/validate.d.ts.map +1 -0
  540. package/lib/oidc/validate.js +181 -0
  541. package/lib/oidc/validate.js.map +1 -0
  542. package/lib/pushprocessor.d.ts +140 -0
  543. package/lib/pushprocessor.d.ts.map +1 -0
  544. package/lib/pushprocessor.js +702 -0
  545. package/lib/pushprocessor.js.map +1 -0
  546. package/lib/randomstring.d.ts +32 -0
  547. package/lib/randomstring.d.ts.map +1 -0
  548. package/lib/randomstring.js +97 -0
  549. package/lib/randomstring.js.map +1 -0
  550. package/lib/realtime-callbacks.d.ts +18 -0
  551. package/lib/realtime-callbacks.d.ts.map +1 -0
  552. package/lib/realtime-callbacks.js +177 -0
  553. package/lib/realtime-callbacks.js.map +1 -0
  554. package/lib/receipt-accumulator.d.ts +51 -0
  555. package/lib/receipt-accumulator.d.ts.map +1 -0
  556. package/lib/receipt-accumulator.js +164 -0
  557. package/lib/receipt-accumulator.js.map +1 -0
  558. package/lib/rendezvous/MSC4108SignInWithQR.d.ts +112 -0
  559. package/lib/rendezvous/MSC4108SignInWithQR.d.ts.map +1 -0
  560. package/lib/rendezvous/MSC4108SignInWithQR.js +389 -0
  561. package/lib/rendezvous/MSC4108SignInWithQR.js.map +1 -0
  562. package/lib/rendezvous/RendezvousChannel.d.ts +27 -0
  563. package/lib/rendezvous/RendezvousChannel.d.ts.map +1 -0
  564. package/lib/rendezvous/RendezvousChannel.js +1 -0
  565. package/lib/rendezvous/RendezvousChannel.js.map +1 -0
  566. package/lib/rendezvous/RendezvousCode.d.ts +9 -0
  567. package/lib/rendezvous/RendezvousCode.d.ts.map +1 -0
  568. package/lib/rendezvous/RendezvousCode.js +1 -0
  569. package/lib/rendezvous/RendezvousCode.js.map +1 -0
  570. package/lib/rendezvous/RendezvousError.d.ts +6 -0
  571. package/lib/rendezvous/RendezvousError.d.ts.map +1 -0
  572. package/lib/rendezvous/RendezvousError.js +23 -0
  573. package/lib/rendezvous/RendezvousError.js.map +1 -0
  574. package/lib/rendezvous/RendezvousFailureReason.d.ts +31 -0
  575. package/lib/rendezvous/RendezvousFailureReason.d.ts.map +1 -0
  576. package/lib/rendezvous/RendezvousFailureReason.js +47 -0
  577. package/lib/rendezvous/RendezvousFailureReason.js.map +1 -0
  578. package/lib/rendezvous/RendezvousIntent.d.ts +5 -0
  579. package/lib/rendezvous/RendezvousIntent.d.ts.map +1 -0
  580. package/lib/rendezvous/RendezvousIntent.js +22 -0
  581. package/lib/rendezvous/RendezvousIntent.js.map +1 -0
  582. package/lib/rendezvous/RendezvousTransport.d.ts +36 -0
  583. package/lib/rendezvous/RendezvousTransport.d.ts.map +1 -0
  584. package/lib/rendezvous/RendezvousTransport.js +1 -0
  585. package/lib/rendezvous/RendezvousTransport.js.map +1 -0
  586. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts +58 -0
  587. package/lib/rendezvous/channels/MSC4108SecureChannel.d.ts.map +1 -0
  588. package/lib/rendezvous/channels/MSC4108SecureChannel.js +246 -0
  589. package/lib/rendezvous/channels/MSC4108SecureChannel.js.map +1 -0
  590. package/lib/rendezvous/channels/index.d.ts +2 -0
  591. package/lib/rendezvous/channels/index.d.ts.map +1 -0
  592. package/lib/rendezvous/channels/index.js +18 -0
  593. package/lib/rendezvous/channels/index.js.map +1 -0
  594. package/lib/rendezvous/index.d.ts +10 -0
  595. package/lib/rendezvous/index.d.ts.map +1 -0
  596. package/lib/rendezvous/index.js +23 -0
  597. package/lib/rendezvous/index.js.map +1 -0
  598. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts +61 -0
  599. package/lib/rendezvous/transports/MSC4108RendezvousSession.d.ts.map +1 -0
  600. package/lib/rendezvous/transports/MSC4108RendezvousSession.js +254 -0
  601. package/lib/rendezvous/transports/MSC4108RendezvousSession.js.map +1 -0
  602. package/lib/rendezvous/transports/index.d.ts +2 -0
  603. package/lib/rendezvous/transports/index.d.ts.map +1 -0
  604. package/lib/rendezvous/transports/index.js +18 -0
  605. package/lib/rendezvous/transports/index.js.map +1 -0
  606. package/lib/room-hierarchy.d.ts +35 -0
  607. package/lib/room-hierarchy.d.ts.map +1 -0
  608. package/lib/room-hierarchy.js +136 -0
  609. package/lib/room-hierarchy.js.map +1 -0
  610. package/lib/rust-crypto/CrossSigningIdentity.d.ts +35 -0
  611. package/lib/rust-crypto/CrossSigningIdentity.d.ts.map +1 -0
  612. package/lib/rust-crypto/CrossSigningIdentity.js +163 -0
  613. package/lib/rust-crypto/CrossSigningIdentity.js.map +1 -0
  614. package/lib/rust-crypto/DehydratedDeviceManager.d.ts +118 -0
  615. package/lib/rust-crypto/DehydratedDeviceManager.d.ts.map +1 -0
  616. package/lib/rust-crypto/DehydratedDeviceManager.js +361 -0
  617. package/lib/rust-crypto/DehydratedDeviceManager.js.map +1 -0
  618. package/lib/rust-crypto/KeyClaimManager.d.ts +33 -0
  619. package/lib/rust-crypto/KeyClaimManager.d.ts.map +1 -0
  620. package/lib/rust-crypto/KeyClaimManager.js +82 -0
  621. package/lib/rust-crypto/KeyClaimManager.js.map +1 -0
  622. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts +36 -0
  623. package/lib/rust-crypto/OutgoingRequestProcessor.d.ts.map +1 -0
  624. package/lib/rust-crypto/OutgoingRequestProcessor.js +194 -0
  625. package/lib/rust-crypto/OutgoingRequestProcessor.js.map +1 -0
  626. package/lib/rust-crypto/OutgoingRequestsManager.d.ts +47 -0
  627. package/lib/rust-crypto/OutgoingRequestsManager.d.ts.map +1 -0
  628. package/lib/rust-crypto/OutgoingRequestsManager.js +175 -0
  629. package/lib/rust-crypto/OutgoingRequestsManager.js.map +1 -0
  630. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts +120 -0
  631. package/lib/rust-crypto/PerSessionKeyBackupDownloader.d.ts.map +1 -0
  632. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js +469 -0
  633. package/lib/rust-crypto/PerSessionKeyBackupDownloader.js.map +1 -0
  634. package/lib/rust-crypto/RoomEncryptor.d.ts +100 -0
  635. package/lib/rust-crypto/RoomEncryptor.d.ts.map +1 -0
  636. package/lib/rust-crypto/RoomEncryptor.js +308 -0
  637. package/lib/rust-crypto/RoomEncryptor.js.map +1 -0
  638. package/lib/rust-crypto/backup.d.ts +278 -0
  639. package/lib/rust-crypto/backup.d.ts.map +1 -0
  640. package/lib/rust-crypto/backup.js +898 -0
  641. package/lib/rust-crypto/backup.js.map +1 -0
  642. package/lib/rust-crypto/constants.d.ts +3 -0
  643. package/lib/rust-crypto/constants.d.ts.map +1 -0
  644. package/lib/rust-crypto/constants.js +19 -0
  645. package/lib/rust-crypto/constants.js.map +1 -0
  646. package/lib/rust-crypto/device-converter.d.ts +28 -0
  647. package/lib/rust-crypto/device-converter.d.ts.map +1 -0
  648. package/lib/rust-crypto/device-converter.js +123 -0
  649. package/lib/rust-crypto/device-converter.js.map +1 -0
  650. package/lib/rust-crypto/index.d.ts +65 -0
  651. package/lib/rust-crypto/index.d.ts.map +1 -0
  652. package/lib/rust-crypto/index.js +149 -0
  653. package/lib/rust-crypto/index.js.map +1 -0
  654. package/lib/rust-crypto/libolm_migration.d.ts +81 -0
  655. package/lib/rust-crypto/libolm_migration.d.ts.map +1 -0
  656. package/lib/rust-crypto/libolm_migration.js +456 -0
  657. package/lib/rust-crypto/libolm_migration.js.map +1 -0
  658. package/lib/rust-crypto/rust-crypto.d.ts +576 -0
  659. package/lib/rust-crypto/rust-crypto.d.ts.map +1 -0
  660. package/lib/rust-crypto/rust-crypto.js +2324 -0
  661. package/lib/rust-crypto/rust-crypto.js.map +1 -0
  662. package/lib/rust-crypto/secret-storage.d.ts +22 -0
  663. package/lib/rust-crypto/secret-storage.d.ts.map +1 -0
  664. package/lib/rust-crypto/secret-storage.js +63 -0
  665. package/lib/rust-crypto/secret-storage.js.map +1 -0
  666. package/lib/rust-crypto/verification.d.ts +321 -0
  667. package/lib/rust-crypto/verification.d.ts.map +1 -0
  668. package/lib/rust-crypto/verification.js +817 -0
  669. package/lib/rust-crypto/verification.js.map +1 -0
  670. package/lib/scheduler.d.ts +132 -0
  671. package/lib/scheduler.d.ts.map +1 -0
  672. package/lib/scheduler.js +259 -0
  673. package/lib/scheduler.js.map +1 -0
  674. package/lib/secret-storage.d.ts +383 -0
  675. package/lib/secret-storage.d.ts.map +1 -0
  676. package/lib/secret-storage.js +487 -0
  677. package/lib/secret-storage.js.map +1 -0
  678. package/lib/serverCapabilities.d.ts +78 -0
  679. package/lib/serverCapabilities.d.ts.map +1 -0
  680. package/lib/serverCapabilities.js +104 -0
  681. package/lib/serverCapabilities.js.map +1 -0
  682. package/lib/service-types.d.ts +5 -0
  683. package/lib/service-types.d.ts.map +1 -0
  684. package/lib/service-types.js +23 -0
  685. package/lib/service-types.js.map +1 -0
  686. package/lib/sliding-sync-sdk.d.ts +107 -0
  687. package/lib/sliding-sync-sdk.d.ts.map +1 -0
  688. package/lib/sliding-sync-sdk.js +892 -0
  689. package/lib/sliding-sync-sdk.js.map +1 -0
  690. package/lib/sliding-sync.d.ts +306 -0
  691. package/lib/sliding-sync.d.ts.map +1 -0
  692. package/lib/sliding-sync.js +585 -0
  693. package/lib/sliding-sync.js.map +1 -0
  694. package/lib/store/index.d.ts +201 -0
  695. package/lib/store/index.d.ts.map +1 -0
  696. package/lib/store/index.js +1 -0
  697. package/lib/store/index.js.map +1 -0
  698. package/lib/store/indexeddb-backend.d.ts +24 -0
  699. package/lib/store/indexeddb-backend.d.ts.map +1 -0
  700. package/lib/store/indexeddb-backend.js +1 -0
  701. package/lib/store/indexeddb-backend.js.map +1 -0
  702. package/lib/store/indexeddb-local-backend.d.ts +129 -0
  703. package/lib/store/indexeddb-local-backend.d.ts.map +1 -0
  704. package/lib/store/indexeddb-local-backend.js +599 -0
  705. package/lib/store/indexeddb-local-backend.js.map +1 -0
  706. package/lib/store/indexeddb-remote-backend.d.ts +79 -0
  707. package/lib/store/indexeddb-remote-backend.d.ts.map +1 -0
  708. package/lib/store/indexeddb-remote-backend.js +209 -0
  709. package/lib/store/indexeddb-remote-backend.js.map +1 -0
  710. package/lib/store/indexeddb-store-worker.d.ts +35 -0
  711. package/lib/store/indexeddb-store-worker.d.ts.map +1 -0
  712. package/lib/store/indexeddb-store-worker.js +146 -0
  713. package/lib/store/indexeddb-store-worker.js.map +1 -0
  714. package/lib/store/indexeddb.d.ts +142 -0
  715. package/lib/store/indexeddb.d.ts.map +1 -0
  716. package/lib/store/indexeddb.js +347 -0
  717. package/lib/store/indexeddb.js.map +1 -0
  718. package/lib/store/local-storage-events-emitter.d.ts +30 -0
  719. package/lib/store/local-storage-events-emitter.d.ts.map +1 -0
  720. package/lib/store/local-storage-events-emitter.js +37 -0
  721. package/lib/store/local-storage-events-emitter.js.map +1 -0
  722. package/lib/store/memory.d.ts +209 -0
  723. package/lib/store/memory.d.ts.map +1 -0
  724. package/lib/store/memory.js +432 -0
  725. package/lib/store/memory.js.map +1 -0
  726. package/lib/store/stub.d.ts +161 -0
  727. package/lib/store/stub.d.ts.map +1 -0
  728. package/lib/store/stub.js +268 -0
  729. package/lib/store/stub.js.map +1 -0
  730. package/lib/sync-accumulator.d.ts +207 -0
  731. package/lib/sync-accumulator.d.ts.map +1 -0
  732. package/lib/sync-accumulator.js +588 -0
  733. package/lib/sync-accumulator.js.map +1 -0
  734. package/lib/sync.d.ts +273 -0
  735. package/lib/sync.d.ts.map +1 -0
  736. package/lib/sync.js +1764 -0
  737. package/lib/sync.js.map +1 -0
  738. package/lib/testing.d.ts +98 -0
  739. package/lib/testing.d.ts.map +1 -0
  740. package/lib/testing.js +205 -0
  741. package/lib/testing.js.map +1 -0
  742. package/lib/thread-utils.d.ts +10 -0
  743. package/lib/thread-utils.d.ts.map +1 -0
  744. package/lib/thread-utils.js +31 -0
  745. package/lib/thread-utils.js.map +1 -0
  746. package/lib/timeline-window.d.ts +168 -0
  747. package/lib/timeline-window.d.ts.map +1 -0
  748. package/lib/timeline-window.js +494 -0
  749. package/lib/timeline-window.js.map +1 -0
  750. package/lib/types.d.ts +33 -0
  751. package/lib/types.d.ts.map +1 -0
  752. package/lib/types.js +52 -0
  753. package/lib/types.js.map +1 -0
  754. package/lib/utils/decryptAESSecretStorageItem.d.ts +12 -0
  755. package/lib/utils/decryptAESSecretStorageItem.d.ts.map +1 -0
  756. package/lib/utils/decryptAESSecretStorageItem.js +50 -0
  757. package/lib/utils/decryptAESSecretStorageItem.js.map +1 -0
  758. package/lib/utils/encryptAESSecretStorageItem.d.ts +16 -0
  759. package/lib/utils/encryptAESSecretStorageItem.d.ts.map +1 -0
  760. package/lib/utils/encryptAESSecretStorageItem.js +68 -0
  761. package/lib/utils/encryptAESSecretStorageItem.js.map +1 -0
  762. package/lib/utils/internal/deriveKeys.d.ts +10 -0
  763. package/lib/utils/internal/deriveKeys.d.ts.map +1 -0
  764. package/lib/utils/internal/deriveKeys.js +60 -0
  765. package/lib/utils/internal/deriveKeys.js.map +1 -0
  766. package/lib/utils/roomVersion.d.ts +13 -0
  767. package/lib/utils/roomVersion.d.ts.map +1 -0
  768. package/lib/utils/roomVersion.js +36 -0
  769. package/lib/utils/roomVersion.js.map +1 -0
  770. package/lib/utils.d.ts +270 -0
  771. package/lib/utils.d.ts.map +1 -0
  772. package/lib/utils.js +764 -0
  773. package/lib/utils.js.map +1 -0
  774. package/lib/version-support.d.ts +19 -0
  775. package/lib/version-support.d.ts.map +1 -0
  776. package/lib/version-support.js +37 -0
  777. package/lib/version-support.js.map +1 -0
  778. package/lib/webrtc/audioContext.d.ts +15 -0
  779. package/lib/webrtc/audioContext.d.ts.map +1 -0
  780. package/lib/webrtc/audioContext.js +46 -0
  781. package/lib/webrtc/audioContext.js.map +1 -0
  782. package/lib/webrtc/call.d.ts +560 -0
  783. package/lib/webrtc/call.d.ts.map +1 -0
  784. package/lib/webrtc/call.js +2596 -0
  785. package/lib/webrtc/call.js.map +1 -0
  786. package/lib/webrtc/callEventHandler.d.ts +37 -0
  787. package/lib/webrtc/callEventHandler.d.ts.map +1 -0
  788. package/lib/webrtc/callEventHandler.js +344 -0
  789. package/lib/webrtc/callEventHandler.js.map +1 -0
  790. package/lib/webrtc/callEventTypes.d.ts +79 -0
  791. package/lib/webrtc/callEventTypes.d.ts.map +1 -0
  792. package/lib/webrtc/callEventTypes.js +13 -0
  793. package/lib/webrtc/callEventTypes.js.map +1 -0
  794. package/lib/webrtc/callFeed.d.ts +128 -0
  795. package/lib/webrtc/callFeed.d.ts.map +1 -0
  796. package/lib/webrtc/callFeed.js +289 -0
  797. package/lib/webrtc/callFeed.js.map +1 -0
  798. package/lib/webrtc/groupCall.d.ts +319 -0
  799. package/lib/webrtc/groupCall.d.ts.map +1 -0
  800. package/lib/webrtc/groupCall.js +1334 -0
  801. package/lib/webrtc/groupCall.js.map +1 -0
  802. package/lib/webrtc/groupCallEventHandler.d.ts +31 -0
  803. package/lib/webrtc/groupCallEventHandler.d.ts.map +1 -0
  804. package/lib/webrtc/groupCallEventHandler.js +178 -0
  805. package/lib/webrtc/groupCallEventHandler.js.map +1 -0
  806. package/lib/webrtc/mediaHandler.d.ts +89 -0
  807. package/lib/webrtc/mediaHandler.d.ts.map +1 -0
  808. package/lib/webrtc/mediaHandler.js +454 -0
  809. package/lib/webrtc/mediaHandler.js.map +1 -0
  810. package/lib/webrtc/stats/callFeedStatsReporter.d.ts +8 -0
  811. package/lib/webrtc/stats/callFeedStatsReporter.d.ts.map +1 -0
  812. package/lib/webrtc/stats/callFeedStatsReporter.js +79 -0
  813. package/lib/webrtc/stats/callFeedStatsReporter.js.map +1 -0
  814. package/lib/webrtc/stats/callStatsReportGatherer.d.ts +25 -0
  815. package/lib/webrtc/stats/callStatsReportGatherer.d.ts.map +1 -0
  816. package/lib/webrtc/stats/callStatsReportGatherer.js +199 -0
  817. package/lib/webrtc/stats/callStatsReportGatherer.js.map +1 -0
  818. package/lib/webrtc/stats/callStatsReportSummary.d.ts +17 -0
  819. package/lib/webrtc/stats/callStatsReportSummary.d.ts.map +1 -0
  820. package/lib/webrtc/stats/callStatsReportSummary.js +1 -0
  821. package/lib/webrtc/stats/callStatsReportSummary.js.map +1 -0
  822. package/lib/webrtc/stats/connectionStats.d.ts +28 -0
  823. package/lib/webrtc/stats/connectionStats.d.ts.map +1 -0
  824. package/lib/webrtc/stats/connectionStats.js +26 -0
  825. package/lib/webrtc/stats/connectionStats.js.map +1 -0
  826. package/lib/webrtc/stats/connectionStatsBuilder.d.ts +5 -0
  827. package/lib/webrtc/stats/connectionStatsBuilder.d.ts.map +1 -0
  828. package/lib/webrtc/stats/connectionStatsBuilder.js +27 -0
  829. package/lib/webrtc/stats/connectionStatsBuilder.js.map +1 -0
  830. package/lib/webrtc/stats/connectionStatsReportBuilder.d.ts +7 -0
  831. package/lib/webrtc/stats/connectionStatsReportBuilder.d.ts.map +1 -0
  832. package/lib/webrtc/stats/connectionStatsReportBuilder.js +121 -0
  833. package/lib/webrtc/stats/connectionStatsReportBuilder.js.map +1 -0
  834. package/lib/webrtc/stats/groupCallStats.d.ts +22 -0
  835. package/lib/webrtc/stats/groupCallStats.d.ts.map +1 -0
  836. package/lib/webrtc/stats/groupCallStats.js +78 -0
  837. package/lib/webrtc/stats/groupCallStats.js.map +1 -0
  838. package/lib/webrtc/stats/media/mediaSsrcHandler.d.ts +10 -0
  839. package/lib/webrtc/stats/media/mediaSsrcHandler.d.ts.map +1 -0
  840. package/lib/webrtc/stats/media/mediaSsrcHandler.js +57 -0
  841. package/lib/webrtc/stats/media/mediaSsrcHandler.js.map +1 -0
  842. package/lib/webrtc/stats/media/mediaTrackHandler.d.ts +12 -0
  843. package/lib/webrtc/stats/media/mediaTrackHandler.d.ts.map +1 -0
  844. package/lib/webrtc/stats/media/mediaTrackHandler.js +58 -0
  845. package/lib/webrtc/stats/media/mediaTrackHandler.js.map +1 -0
  846. package/lib/webrtc/stats/media/mediaTrackStats.d.ts +86 -0
  847. package/lib/webrtc/stats/media/mediaTrackStats.d.ts.map +1 -0
  848. package/lib/webrtc/stats/media/mediaTrackStats.js +142 -0
  849. package/lib/webrtc/stats/media/mediaTrackStats.js.map +1 -0
  850. package/lib/webrtc/stats/media/mediaTrackStatsHandler.d.ts +22 -0
  851. package/lib/webrtc/stats/media/mediaTrackStatsHandler.d.ts.map +1 -0
  852. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js +76 -0
  853. package/lib/webrtc/stats/media/mediaTrackStatsHandler.js.map +1 -0
  854. package/lib/webrtc/stats/statsReport.d.ts +99 -0
  855. package/lib/webrtc/stats/statsReport.d.ts.map +1 -0
  856. package/lib/webrtc/stats/statsReport.js +32 -0
  857. package/lib/webrtc/stats/statsReport.js.map +1 -0
  858. package/lib/webrtc/stats/statsReportEmitter.d.ts +15 -0
  859. package/lib/webrtc/stats/statsReportEmitter.d.ts.map +1 -0
  860. package/lib/webrtc/stats/statsReportEmitter.js +33 -0
  861. package/lib/webrtc/stats/statsReportEmitter.js.map +1 -0
  862. package/lib/webrtc/stats/summaryStatsReportGatherer.d.ts +16 -0
  863. package/lib/webrtc/stats/summaryStatsReportGatherer.d.ts.map +1 -0
  864. package/lib/webrtc/stats/summaryStatsReportGatherer.js +116 -0
  865. package/lib/webrtc/stats/summaryStatsReportGatherer.js.map +1 -0
  866. package/lib/webrtc/stats/trackStatsBuilder.d.ts +19 -0
  867. package/lib/webrtc/stats/trackStatsBuilder.d.ts.map +1 -0
  868. package/lib/webrtc/stats/trackStatsBuilder.js +168 -0
  869. package/lib/webrtc/stats/trackStatsBuilder.js.map +1 -0
  870. package/lib/webrtc/stats/transportStats.d.ts +11 -0
  871. package/lib/webrtc/stats/transportStats.d.ts.map +1 -0
  872. package/lib/webrtc/stats/transportStats.js +1 -0
  873. package/lib/webrtc/stats/transportStats.js.map +1 -0
  874. package/lib/webrtc/stats/transportStatsBuilder.d.ts +5 -0
  875. package/lib/webrtc/stats/transportStatsBuilder.d.ts.map +1 -0
  876. package/lib/webrtc/stats/transportStatsBuilder.js +34 -0
  877. package/lib/webrtc/stats/transportStatsBuilder.js.map +1 -0
  878. package/lib/webrtc/stats/valueFormatter.d.ts +4 -0
  879. package/lib/webrtc/stats/valueFormatter.d.ts.map +1 -0
  880. package/lib/webrtc/stats/valueFormatter.js +25 -0
  881. package/lib/webrtc/stats/valueFormatter.js.map +1 -0
  882. package/package.json +129 -0
  883. package/src/@types/AESEncryptedSecretStoragePayload.ts +29 -0
  884. package/src/@types/IIdentityServerProvider.ts +24 -0
  885. package/src/@types/PushRules.ts +208 -0
  886. package/src/@types/another-json.d.ts +19 -0
  887. package/src/@types/auth.ts +258 -0
  888. package/src/@types/beacon.ts +140 -0
  889. package/src/@types/common.ts +24 -0
  890. package/src/@types/crypto.ts +71 -0
  891. package/src/@types/event.ts +449 -0
  892. package/src/@types/events.ts +119 -0
  893. package/src/@types/extensible_events.ts +147 -0
  894. package/src/@types/global.d.ts +67 -0
  895. package/src/@types/local_notifications.ts +19 -0
  896. package/src/@types/location.ts +92 -0
  897. package/src/@types/matrix-sdk-crypto-wasm.d.ts +39 -0
  898. package/src/@types/media.ts +245 -0
  899. package/src/@types/membership.ts +57 -0
  900. package/src/@types/partials.ts +103 -0
  901. package/src/@types/polls.ts +120 -0
  902. package/src/@types/read_receipts.ts +61 -0
  903. package/src/@types/registration.ts +102 -0
  904. package/src/@types/requests.ts +346 -0
  905. package/src/@types/search.ts +119 -0
  906. package/src/@types/signed.ts +25 -0
  907. package/src/@types/spaces.ts +37 -0
  908. package/src/@types/state_events.ts +153 -0
  909. package/src/@types/synapse.ts +40 -0
  910. package/src/@types/sync.ts +27 -0
  911. package/src/@types/threepids.ts +29 -0
  912. package/src/@types/topic.ts +69 -0
  913. package/src/@types/uia.ts +24 -0
  914. package/src/NamespacedValue.ts +121 -0
  915. package/src/ReEmitter.ts +93 -0
  916. package/src/ToDeviceMessageQueue.ts +156 -0
  917. package/src/autodiscovery.ts +505 -0
  918. package/src/base64.ts +86 -0
  919. package/src/briij.ts +173 -0
  920. package/src/browser-index.ts +44 -0
  921. package/src/client.ts +9031 -0
  922. package/src/common-crypto/CryptoBackend.ts +295 -0
  923. package/src/common-crypto/README.md +4 -0
  924. package/src/common-crypto/key-passphrase.ts +43 -0
  925. package/src/content-helpers.ts +298 -0
  926. package/src/content-repo.ts +122 -0
  927. package/src/crypto/store/base.ts +388 -0
  928. package/src/crypto/store/indexeddb-crypto-store-backend.ts +655 -0
  929. package/src/crypto/store/indexeddb-crypto-store.ts +555 -0
  930. package/src/crypto/store/localStorage-crypto-store.ts +409 -0
  931. package/src/crypto/store/memory-crypto-store.ts +326 -0
  932. package/src/crypto-api/CryptoEvent.ts +152 -0
  933. package/src/crypto-api/CryptoEventHandlerMap.ts +42 -0
  934. package/src/crypto-api/index.ts +1362 -0
  935. package/src/crypto-api/key-passphrase.ts +58 -0
  936. package/src/crypto-api/keybackup.ts +114 -0
  937. package/src/crypto-api/recovery-key.ts +69 -0
  938. package/src/crypto-api/verification.ts +382 -0
  939. package/src/digest.ts +34 -0
  940. package/src/embedded.ts +865 -0
  941. package/src/errors.ts +87 -0
  942. package/src/event-mapper.ts +88 -0
  943. package/src/extensible_events_v1/ExtensibleEvent.ts +58 -0
  944. package/src/extensible_events_v1/InvalidEventError.ts +24 -0
  945. package/src/extensible_events_v1/MessageEvent.ts +143 -0
  946. package/src/extensible_events_v1/PollEndEvent.ts +97 -0
  947. package/src/extensible_events_v1/PollResponseEvent.ts +148 -0
  948. package/src/extensible_events_v1/PollStartEvent.ts +207 -0
  949. package/src/extensible_events_v1/utilities.ts +35 -0
  950. package/src/feature.ts +88 -0
  951. package/src/filter-component.ts +209 -0
  952. package/src/filter.ts +245 -0
  953. package/src/http-api/errors.ts +261 -0
  954. package/src/http-api/fetch.ts +377 -0
  955. package/src/http-api/index.ts +194 -0
  956. package/src/http-api/interface.ts +229 -0
  957. package/src/http-api/method.ts +25 -0
  958. package/src/http-api/prefix.ts +48 -0
  959. package/src/http-api/refresh.ts +167 -0
  960. package/src/http-api/utils.ts +217 -0
  961. package/src/index.ts +25 -0
  962. package/src/indexeddb-helpers.ts +50 -0
  963. package/src/indexeddb-worker.ts +24 -0
  964. package/src/interactive-auth.ts +700 -0
  965. package/src/logger.ts +279 -0
  966. package/src/matrixrtc/CallMembership.ts +438 -0
  967. package/src/matrixrtc/EncryptionManager.ts +54 -0
  968. package/src/matrixrtc/IKeyTransport.ts +63 -0
  969. package/src/matrixrtc/IMembershipManager.ts +120 -0
  970. package/src/matrixrtc/LivekitTransport.ts +46 -0
  971. package/src/matrixrtc/MatrixRTCSession.ts +934 -0
  972. package/src/matrixrtc/MatrixRTCSessionManager.ts +170 -0
  973. package/src/matrixrtc/MembershipManager.ts +1122 -0
  974. package/src/matrixrtc/MembershipManagerActionScheduler.ts +135 -0
  975. package/src/matrixrtc/RTCEncryptionManager.ts +459 -0
  976. package/src/matrixrtc/ToDeviceKeyTransport.ts +197 -0
  977. package/src/matrixrtc/index.ts +24 -0
  978. package/src/matrixrtc/membershipData/common.ts +27 -0
  979. package/src/matrixrtc/membershipData/index.ts +19 -0
  980. package/src/matrixrtc/membershipData/rtc.ts +156 -0
  981. package/src/matrixrtc/membershipData/session.ts +146 -0
  982. package/src/matrixrtc/types.ts +227 -0
  983. package/src/matrixrtc/utils.ts +71 -0
  984. package/src/models/MSC3089Branch.ts +272 -0
  985. package/src/models/MSC3089TreeSpace.ts +565 -0
  986. package/src/models/ToDeviceMessage.ts +38 -0
  987. package/src/models/beacon.ts +213 -0
  988. package/src/models/compare-event-ordering.ts +139 -0
  989. package/src/models/device.ts +85 -0
  990. package/src/models/event-context.ts +110 -0
  991. package/src/models/event-status.ts +39 -0
  992. package/src/models/event-timeline-set.ts +962 -0
  993. package/src/models/event-timeline.ts +461 -0
  994. package/src/models/event.ts +1819 -0
  995. package/src/models/invites-ignorer-types.ts +58 -0
  996. package/src/models/invites-ignorer.ts +341 -0
  997. package/src/models/poll.ts +285 -0
  998. package/src/models/profile-keys.ts +33 -0
  999. package/src/models/read-receipt.ts +422 -0
  1000. package/src/models/related-relations.ts +39 -0
  1001. package/src/models/relations-container.ts +149 -0
  1002. package/src/models/relations.ts +392 -0
  1003. package/src/models/room-member.ts +486 -0
  1004. package/src/models/room-receipts.ts +439 -0
  1005. package/src/models/room-state.ts +1230 -0
  1006. package/src/models/room-sticky-events.ts +383 -0
  1007. package/src/models/room-summary.ts +78 -0
  1008. package/src/models/room.ts +4067 -0
  1009. package/src/models/search-result.ts +57 -0
  1010. package/src/models/thread.ts +928 -0
  1011. package/src/models/typed-event-emitter.ts +246 -0
  1012. package/src/models/user.ts +302 -0
  1013. package/src/oidc/authorize.ts +279 -0
  1014. package/src/oidc/discovery.ts +67 -0
  1015. package/src/oidc/error.ts +33 -0
  1016. package/src/oidc/index.ts +33 -0
  1017. package/src/oidc/register.ts +163 -0
  1018. package/src/oidc/tokenRefresher.ts +184 -0
  1019. package/src/oidc/validate.ts +265 -0
  1020. package/src/pushprocessor.ts +856 -0
  1021. package/src/randomstring.ts +103 -0
  1022. package/src/realtime-callbacks.ts +191 -0
  1023. package/src/receipt-accumulator.ts +189 -0
  1024. package/src/rendezvous/MSC4108SignInWithQR.ts +443 -0
  1025. package/src/rendezvous/RendezvousChannel.ts +48 -0
  1026. package/src/rendezvous/RendezvousCode.ts +25 -0
  1027. package/src/rendezvous/RendezvousError.ts +26 -0
  1028. package/src/rendezvous/RendezvousFailureReason.ts +49 -0
  1029. package/src/rendezvous/RendezvousIntent.ts +20 -0
  1030. package/src/rendezvous/RendezvousTransport.ts +58 -0
  1031. package/src/rendezvous/channels/MSC4108SecureChannel.ts +270 -0
  1032. package/src/rendezvous/channels/index.ts +17 -0
  1033. package/src/rendezvous/index.ts +25 -0
  1034. package/src/rendezvous/transports/MSC4108RendezvousSession.ts +272 -0
  1035. package/src/rendezvous/transports/index.ts +17 -0
  1036. package/src/room-hierarchy.ts +152 -0
  1037. package/src/rust-crypto/CrossSigningIdentity.ts +195 -0
  1038. package/src/rust-crypto/DehydratedDeviceManager.ts +392 -0
  1039. package/src/rust-crypto/KeyClaimManager.ts +86 -0
  1040. package/src/rust-crypto/OutgoingRequestProcessor.ts +233 -0
  1041. package/src/rust-crypto/OutgoingRequestsManager.ts +170 -0
  1042. package/src/rust-crypto/PerSessionKeyBackupDownloader.ts +501 -0
  1043. package/src/rust-crypto/RoomEncryptor.ts +362 -0
  1044. package/src/rust-crypto/backup.ts +942 -0
  1045. package/src/rust-crypto/constants.ts +18 -0
  1046. package/src/rust-crypto/device-converter.ts +128 -0
  1047. package/src/rust-crypto/index.ts +251 -0
  1048. package/src/rust-crypto/libolm_migration.ts +532 -0
  1049. package/src/rust-crypto/rust-crypto.ts +2542 -0
  1050. package/src/rust-crypto/secret-storage.ts +60 -0
  1051. package/src/rust-crypto/verification.ts +833 -0
  1052. package/src/scheduler.ts +309 -0
  1053. package/src/secret-storage.ts +714 -0
  1054. package/src/serverCapabilities.ts +146 -0
  1055. package/src/service-types.ts +20 -0
  1056. package/src/sliding-sync-sdk.ts +1005 -0
  1057. package/src/sliding-sync.ts +674 -0
  1058. package/src/store/index.ts +261 -0
  1059. package/src/store/indexeddb-backend.ts +41 -0
  1060. package/src/store/indexeddb-local-backend.ts +610 -0
  1061. package/src/store/indexeddb-remote-backend.ts +212 -0
  1062. package/src/store/indexeddb-store-worker.ts +157 -0
  1063. package/src/store/indexeddb.ts +397 -0
  1064. package/src/store/local-storage-events-emitter.ts +46 -0
  1065. package/src/store/memory.ts +448 -0
  1066. package/src/store/stub.ts +280 -0
  1067. package/src/sync-accumulator.ts +779 -0
  1068. package/src/sync.ts +2020 -0
  1069. package/src/testing.ts +231 -0
  1070. package/src/thread-utils.ts +31 -0
  1071. package/src/timeline-window.ts +534 -0
  1072. package/src/types.ts +59 -0
  1073. package/src/utils/decryptAESSecretStorageItem.ts +54 -0
  1074. package/src/utils/encryptAESSecretStorageItem.ts +73 -0
  1075. package/src/utils/internal/deriveKeys.ts +63 -0
  1076. package/src/utils/roomVersion.ts +35 -0
  1077. package/src/utils.ts +775 -0
  1078. package/src/version-support.ts +50 -0
  1079. package/src/webrtc/audioContext.ts +44 -0
  1080. package/src/webrtc/call.ts +3061 -0
  1081. package/src/webrtc/callEventHandler.ts +425 -0
  1082. package/src/webrtc/callEventTypes.ts +101 -0
  1083. package/src/webrtc/callFeed.ts +364 -0
  1084. package/src/webrtc/groupCall.ts +1729 -0
  1085. package/src/webrtc/groupCallEventHandler.ts +234 -0
  1086. package/src/webrtc/mediaHandler.ts +501 -0
  1087. package/src/webrtc/stats/callFeedStatsReporter.ts +91 -0
  1088. package/src/webrtc/stats/callStatsReportGatherer.ts +219 -0
  1089. package/src/webrtc/stats/callStatsReportSummary.ts +30 -0
  1090. package/src/webrtc/stats/connectionStats.ts +47 -0
  1091. package/src/webrtc/stats/connectionStatsBuilder.ts +28 -0
  1092. package/src/webrtc/stats/connectionStatsReportBuilder.ts +140 -0
  1093. package/src/webrtc/stats/groupCallStats.ts +93 -0
  1094. package/src/webrtc/stats/media/mediaSsrcHandler.ts +57 -0
  1095. package/src/webrtc/stats/media/mediaTrackHandler.ts +70 -0
  1096. package/src/webrtc/stats/media/mediaTrackStats.ts +176 -0
  1097. package/src/webrtc/stats/media/mediaTrackStatsHandler.ts +90 -0
  1098. package/src/webrtc/stats/statsReport.ts +133 -0
  1099. package/src/webrtc/stats/statsReportEmitter.ts +49 -0
  1100. package/src/webrtc/stats/summaryStatsReportGatherer.ts +148 -0
  1101. package/src/webrtc/stats/trackStatsBuilder.ts +207 -0
  1102. package/src/webrtc/stats/transportStats.ts +26 -0
  1103. package/src/webrtc/stats/transportStatsBuilder.ts +48 -0
  1104. package/src/webrtc/stats/valueFormatter.ts +27 -0
@@ -0,0 +1,4067 @@
1
+ /*
2
+ Copyright 2015 - 2023 The Matrix.org Foundation C.I.C.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ import { M_POLL_START } from "matrix-events-sdk";
18
+
19
+ import {
20
+ DuplicateStrategy,
21
+ EventTimelineSet,
22
+ type EventTimelineSetHandlerMap,
23
+ type IAddLiveEventOptions,
24
+ } from "./event-timeline-set.ts";
25
+ import { Direction, EventTimeline } from "./event-timeline.ts";
26
+ import { getHttpUriForMxc } from "../content-repo.ts";
27
+ import * as utils from "../utils.ts";
28
+ import { normalize, noUnsafeEventProps, removeElement } from "../utils.ts";
29
+ import {
30
+ type IEvent,
31
+ type IThreadBundledRelationship,
32
+ BriijEvent,
33
+ BriijEventEvent,
34
+ type BriijEventHandlerMap,
35
+ } from "./event.ts";
36
+ import { EventStatus } from "./event-status.ts";
37
+ import { RoomMember } from "./room-member.ts";
38
+ import { type Hero, type IRoomSummary, RoomSummary } from "./room-summary.ts";
39
+ import { logger } from "../logger.ts";
40
+ import { TypedReEmitter } from "../ReEmitter.ts";
41
+ import {
42
+ EVENT_VISIBILITY_CHANGE_TYPE,
43
+ EventType,
44
+ RelationType,
45
+ RoomCreateTypeField,
46
+ RoomType,
47
+ UNSIGNED_THREAD_ID_FIELD,
48
+ UNSTABLE_ELEMENT_FUNCTIONAL_USERS,
49
+ } from "../@types/event.ts";
50
+ import { type BriijClient, PendingEventOrdering } from "../client.ts";
51
+ import { type GuestAccess, type HistoryVisibility, type JoinRule, type ResizeMethod } from "../@types/partials.ts";
52
+ import { Filter, type IFilterDefinition } from "../filter.ts";
53
+ import { type RoomState, RoomStateEvent, type RoomStateEventHandlerMap } from "./room-state.ts";
54
+ import { BeaconEvent, type BeaconEventHandlerMap } from "./beacon.ts";
55
+ import {
56
+ FILTER_RELATED_BY_REL_TYPES,
57
+ FILTER_RELATED_BY_SENDERS,
58
+ Thread,
59
+ THREAD_RELATION_TYPE,
60
+ ThreadEvent,
61
+ type ThreadEventHandlerMap as ThreadHandlerMap,
62
+ ThreadFilterType,
63
+ } from "./thread.ts";
64
+ import {
65
+ type CachedReceiptStructure,
66
+ MAIN_ROOM_TIMELINE,
67
+ type Receipt,
68
+ type ReceiptContent,
69
+ ReceiptType,
70
+ } from "../@types/read_receipts.ts";
71
+ import { type IStateEventWithRoomId } from "../@types/search.ts";
72
+ import { RelationsContainer } from "./relations-container.ts";
73
+ import { ReadReceipt, synthesizeReceipt } from "./read-receipt.ts";
74
+ import { isPollEvent, Poll, PollEvent } from "./poll.ts";
75
+ import { RoomReceipts } from "./room-receipts.ts";
76
+ import { compareEventOrdering } from "./compare-event-ordering.ts";
77
+ import { KnownMembership, type Membership } from "../@types/membership.ts";
78
+ import { type Capabilities, type IRoomVersionsCapability, RoomVersionStability } from "../serverCapabilities.ts";
79
+ import { type MSC4186Hero } from "../sliding-sync.ts";
80
+ import { RoomStickyEventsStore, RoomStickyEventsEvent, type RoomStickyEventsMap } from "./room-sticky-events.ts";
81
+
82
+ // These constants are used as sane defaults when the homeserver doesn't support
83
+ // the m.room_versions capability. In practice, KNOWN_SAFE_ROOM_VERSION should be
84
+ // the same as the common default room version whereas SAFE_ROOM_VERSIONS are the
85
+ // room versions which are considered okay for people to run without being asked
86
+ // to upgrade (ie: "stable"). Eventually, we should remove these when all homeservers
87
+ // return an m.room_versions capability.
88
+ export const KNOWN_SAFE_ROOM_VERSION = "10";
89
+ const SAFE_ROOM_VERSIONS = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
90
+
91
+ interface IOpts {
92
+ /**
93
+ * Controls where pending messages appear in a room's timeline.
94
+ * If "<b>chronological</b>", messages will appear in the timeline when the call to `sendEvent` was made.
95
+ * If "<b>detached</b>", pending messages will appear in a separate list,
96
+ * accessible via {@link Room#getPendingEvents}.
97
+ * Default: "chronological".
98
+ */
99
+ pendingEventOrdering?: PendingEventOrdering;
100
+ /**
101
+ * Set to true to enable improved timeline support.
102
+ */
103
+ timelineSupport?: boolean;
104
+ lazyLoadMembers?: boolean;
105
+ }
106
+
107
+ export interface IRecommendedVersion {
108
+ version: string;
109
+ needsUpgrade: boolean;
110
+ urgent: boolean;
111
+ }
112
+
113
+ // When inserting a visibility event affecting event `eventId`, we
114
+ // need to scan through existing visibility events for `eventId`.
115
+ // In theory, this could take an unlimited amount of time if:
116
+ //
117
+ // - the visibility event was sent by a moderator; and
118
+ // - `eventId` already has many visibility changes (usually, it should
119
+ // be 2 or less); and
120
+ // - for some reason, the visibility changes are received out of order
121
+ // (usually, this shouldn't happen at all).
122
+ //
123
+ // For this reason, we limit the number of events to scan through,
124
+ // expecting that a broken visibility change for a single event in
125
+ // an extremely uncommon case (possibly a DoS) is a small
126
+ // price to pay to keep matrix-js-sdk responsive.
127
+ const MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH = 30;
128
+
129
+ export type NotificationCount = Partial<Record<NotificationCountType, number>>;
130
+
131
+ export enum NotificationCountType {
132
+ Highlight = "highlight",
133
+ Total = "total",
134
+ }
135
+
136
+ export interface ICreateFilterOpts {
137
+ // Populate the filtered timeline with already loaded events in the room
138
+ // timeline. Useful to disable for some filters that can't be achieved by the
139
+ // client in an efficient manner
140
+ prepopulateTimeline?: boolean;
141
+ useSyncEvents?: boolean;
142
+ pendingEvents?: boolean;
143
+ }
144
+
145
+ export enum RoomEvent {
146
+ MyMembership = "Room.myMembership",
147
+ Tags = "Room.tags",
148
+ AccountData = "Room.accountData",
149
+ Receipt = "Room.receipt",
150
+ Name = "Room.name",
151
+ Redaction = "Room.redaction",
152
+ RedactionCancelled = "Room.redactionCancelled",
153
+ LocalEchoUpdated = "Room.localEchoUpdated",
154
+ Timeline = "Room.timeline",
155
+ TimelineReset = "Room.timelineReset",
156
+ TimelineRefresh = "Room.TimelineRefresh",
157
+ OldStateUpdated = "Room.OldStateUpdated",
158
+ CurrentStateUpdated = "Room.CurrentStateUpdated",
159
+ HistoryImportedWithinTimeline = "Room.historyImportedWithinTimeline",
160
+ UnreadNotifications = "Room.UnreadNotifications",
161
+ Summary = "Room.Summary",
162
+ }
163
+
164
+ export type RoomEmittedEvents =
165
+ | RoomEvent
166
+ | RoomStateEvent.Events
167
+ | RoomStateEvent.Members
168
+ | RoomStateEvent.NewMember
169
+ | RoomStateEvent.Update
170
+ | RoomStateEvent.Marker
171
+ | RoomStickyEventsEvent.Update
172
+ | ThreadEvent.New
173
+ | ThreadEvent.Update
174
+ | ThreadEvent.NewReply
175
+ | ThreadEvent.Delete
176
+ | BriijEventEvent.BeforeRedaction
177
+ | BeaconEvent.New
178
+ | BeaconEvent.Update
179
+ | BeaconEvent.Destroy
180
+ | BeaconEvent.LivenessChange
181
+ | PollEvent.New;
182
+
183
+ export type RoomEventHandlerMap = {
184
+ /**
185
+ * Fires when the logged in user's membership in the room is updated.
186
+ *
187
+ * @param room - The room in which the membership has been updated
188
+ * @param membership - The new membership value
189
+ * @param prevMembership - The previous membership value
190
+ */
191
+ [RoomEvent.MyMembership]: (room: Room, membership: Membership, prevMembership?: Membership) => void;
192
+ /**
193
+ * Fires whenever a room's tags are updated.
194
+ * @param event - The tags event
195
+ * @param room - The room whose Room.tags was updated.
196
+ * @example
197
+ * ```
198
+ * matrixClient.on("Room.tags", function(event, room){
199
+ * var newTags = event.getContent().tags;
200
+ * if (newTags["favourite"]) showStar(room);
201
+ * });
202
+ * ```
203
+ */
204
+ [RoomEvent.Tags]: (event: BriijEvent, room: Room) => void;
205
+ /**
206
+ * Fires whenever a room's account_data is updated.
207
+ * @param event - The account_data event
208
+ * @param room - The room whose account_data was updated.
209
+ * @param prevEvent - The event being replaced by
210
+ * the new account data, if known.
211
+ * @example
212
+ * ```
213
+ * matrixClient.on("Room.accountData", function(event, room, oldEvent){
214
+ * if (event.getType() === "m.room.colorscheme") {
215
+ * applyColorScheme(event.getContents());
216
+ * }
217
+ * });
218
+ * ```
219
+ */
220
+ [RoomEvent.AccountData]: (event: BriijEvent, room: Room, prevEvent?: BriijEvent) => void;
221
+ /**
222
+ * Fires whenever a receipt is received for a room
223
+ * @param event - The receipt event
224
+ * @param room - The room whose receipts was updated.
225
+ * @example
226
+ * ```
227
+ * matrixClient.on("Room.receipt", function(event, room){
228
+ * var receiptContent = event.getContent();
229
+ * });
230
+ * ```
231
+ */
232
+ [RoomEvent.Receipt]: (event: BriijEvent, room: Room) => void;
233
+ /**
234
+ * Fires whenever the name of a room is updated.
235
+ * @param room - The room whose Room.name was updated.
236
+ * @example
237
+ * ```
238
+ * matrixClient.on("Room.name", function(room){
239
+ * var newName = room.name;
240
+ * });
241
+ * ```
242
+ */
243
+ [RoomEvent.Name]: (room: Room) => void;
244
+ /**
245
+ * Fires when an event we had previously received is redacted.
246
+ *
247
+ * (Note this is *not* fired when the redaction happens before we receive the
248
+ * event).
249
+ *
250
+ * @param event - The matrix redaction event
251
+ * @param room - The room containing the redacted event
252
+ * @param threadId - The thread containing the redacted event (before it was redacted)
253
+ */
254
+ [RoomEvent.Redaction]: (event: BriijEvent, room: Room, threadId?: string) => void;
255
+ /**
256
+ * Fires when an event that was previously redacted isn't anymore.
257
+ * This happens when the redaction couldn't be sent and
258
+ * was subsequently cancelled by the user. Redactions have a local echo
259
+ * which is undone in this scenario.
260
+ *
261
+ * @param event - The matrix redaction event that was cancelled.
262
+ * @param room - The room containing the unredacted event
263
+ */
264
+ [RoomEvent.RedactionCancelled]: (event: BriijEvent, room: Room) => void;
265
+ /**
266
+ * Fires when the status of a transmitted event is updated.
267
+ *
268
+ * <p>When an event is first transmitted, a temporary copy of the event is
269
+ * inserted into the timeline, with a temporary event id, and a status of
270
+ * 'SENDING'.
271
+ *
272
+ * <p>Once the echo comes back from the server, the content of the event
273
+ * (BriijEvent.event) is replaced by the complete event from the homeserver,
274
+ * thus updating its event id, as well as server-generated fields such as the
275
+ * timestamp. Its status is set to null.
276
+ *
277
+ * <p>Once the /send request completes, if the remote echo has not already
278
+ * arrived, the event is updated with a new event id and the status is set to
279
+ * 'SENT'. The server-generated fields are of course not updated yet.
280
+ *
281
+ * <p>If the /send fails, In this case, the event's status is set to
282
+ * 'NOT_SENT'. If it is later resent, the process starts again, setting the
283
+ * status to 'SENDING'. Alternatively, the message may be cancelled, which
284
+ * removes the event from the room, and sets the status to 'CANCELLED'.
285
+ *
286
+ * <p>This event is raised to reflect each of the transitions above.
287
+ *
288
+ * @param event - The matrix event which has been updated
289
+ *
290
+ * @param room - The room containing the redacted event
291
+ *
292
+ * @param oldEventId - The previous event id (the temporary event id,
293
+ * except when updating a successfully-sent event when its echo arrives)
294
+ *
295
+ * @param oldStatus - The previous event status.
296
+ */
297
+ [RoomEvent.LocalEchoUpdated]: (
298
+ event: BriijEvent,
299
+ room: Room,
300
+ oldEventId?: string,
301
+ oldStatus?: EventStatus | null,
302
+ ) => void;
303
+ [RoomEvent.OldStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;
304
+ [RoomEvent.CurrentStateUpdated]: (room: Room, previousRoomState: RoomState, roomState: RoomState) => void;
305
+ [RoomEvent.HistoryImportedWithinTimeline]: (markerEvent: BriijEvent, room: Room) => void;
306
+ [RoomEvent.UnreadNotifications]: (unreadNotifications?: NotificationCount, threadId?: string) => void;
307
+ [RoomEvent.TimelineRefresh]: (room: Room, eventTimelineSet: EventTimelineSet) => void;
308
+ /**
309
+ * Fires when a new room summary is returned by `/sync`.
310
+ *
311
+ * See https://spec.matrix.org/v1.8/client-server-api/#_matrixclientv3sync_roomsummary
312
+ * for full details
313
+ * @param summary - the room summary object
314
+ */
315
+ [RoomEvent.Summary]: (summary: IRoomSummary) => void;
316
+ [ThreadEvent.New]: (thread: Thread, toStartOfTimeline: boolean) => void;
317
+ /**
318
+ * Fires when a new poll instance is added to the room state
319
+ * @param poll - the new poll
320
+ */
321
+ [PollEvent.New]: (poll: Poll) => void;
322
+ } & Pick<ThreadHandlerMap, ThreadEvent.Update | ThreadEvent.NewReply | ThreadEvent.Delete> &
323
+ EventTimelineSetHandlerMap &
324
+ Pick<BriijEventHandlerMap, BriijEventEvent.BeforeRedaction> &
325
+ Pick<RoomStickyEventsMap, RoomStickyEventsEvent.Update> &
326
+ Pick<
327
+ RoomStateEventHandlerMap,
328
+ | RoomStateEvent.Events
329
+ | RoomStateEvent.Members
330
+ | RoomStateEvent.NewMember
331
+ | RoomStateEvent.Update
332
+ | RoomStateEvent.Marker
333
+ | BeaconEvent.New
334
+ > &
335
+ Pick<BeaconEventHandlerMap, BeaconEvent.Update | BeaconEvent.Destroy | BeaconEvent.LivenessChange>;
336
+
337
+ export class Room extends ReadReceipt<RoomEmittedEvents, RoomEventHandlerMap> {
338
+ public readonly reEmitter: TypedReEmitter<RoomEmittedEvents, RoomEventHandlerMap>;
339
+ private txnToEvent: Map<string, BriijEvent> = new Map(); // Pending in-flight requests { string: BriijEvent }
340
+ private notificationCounts: NotificationCount = {};
341
+ private bumpStamp: number | undefined = undefined;
342
+ private readonly threadNotifications = new Map<string, NotificationCount>();
343
+ public readonly cachedThreadReadReceipts = new Map<string, CachedReceiptStructure[]>();
344
+ // Useful to know at what point the current user has started using threads in this room
345
+ private oldestThreadedReceiptTs = Infinity;
346
+ /**
347
+ * A record of the latest unthread receipts per user
348
+ * This is useful in determining whether a user has read a thread or not
349
+ */
350
+ private unthreadedReceipts = new Map<string, Receipt>();
351
+ private readonly timelineSets: EventTimelineSet[];
352
+ public readonly polls: Map<string, Poll> = new Map<string, Poll>();
353
+
354
+ /**
355
+ * Empty array if the timeline sets have not been initialised. After initialisation:
356
+ * 0: All threads
357
+ * 1: Threads the current user has participated in
358
+ */
359
+ public readonly threadsTimelineSets: [] | [EventTimelineSet, EventTimelineSet] = [];
360
+
361
+ // any filtered timeline sets we're maintaining for this room
362
+ private readonly filteredTimelineSets: Record<string, EventTimelineSet> = {}; // filter_id: timelineSet
363
+ private timelineNeedsRefresh = false;
364
+ private readonly pendingEventList?: BriijEvent[];
365
+ // read by megolm via getter; boolean value - null indicates "use global value"
366
+ private blacklistUnverifiedDevices?: boolean;
367
+ private selfMembership?: Membership;
368
+ /**
369
+ * A `Hero` is a stripped `m.room.member` event which contains the important renderable fields from the event.
370
+ *
371
+ * It is used in MSC4186 (Simplified Sliding Sync) as a replacement for the old `summary` field.
372
+ *
373
+ * When we are doing old-style (`/v3/sync`) sync, we simulate the SSS behaviour by constructing
374
+ * a `Hero` object based on the user id we get from the summary. Obviously, in that case,
375
+ * the `Hero` will lack a `displayName` or `avatarUrl`.
376
+ */
377
+ private heroes: Hero[] | null = null;
378
+ // flags to stop logspam about missing m.room.create events
379
+ private getTypeWarning = false;
380
+ private membersPromise?: Promise<boolean>;
381
+
382
+ // XXX: These should be read-only
383
+ /**
384
+ * The human-readable display name for this room.
385
+ */
386
+ public name: string;
387
+ /**
388
+ * The un-homoglyphed name for this room.
389
+ */
390
+ public normalizedName: string;
391
+ /**
392
+ * Dict of room tags; the keys are the tag name and the values
393
+ * are any metadata associated with the tag - e.g. `{ "fav" : { order: 1 } }`
394
+ */
395
+ public tags: Record<string, Record<string, any>> = {}; // $tagName: { $metadata: $value }
396
+ /**
397
+ * accountData Dict of per-room account_data events; the keys are the
398
+ * event type and the values are the events.
399
+ */
400
+ public accountData: Map<string, BriijEvent> = new Map(); // $eventType: $event
401
+ /**
402
+ * The room summary.
403
+ */
404
+ public summary: RoomSummary | null = null;
405
+ /**
406
+ * oldState The state of the room at the time of the oldest event in the live timeline.
407
+ *
408
+ * @deprecated Present for backwards compatibility.
409
+ * Use getLiveTimeline().getState(EventTimeline.BACKWARDS) instead
410
+ */
411
+ public oldState!: RoomState;
412
+ /**
413
+ * currentState The state of the room at the time of the newest event in the timeline.
414
+ *
415
+ * @deprecated Present for backwards compatibility.
416
+ * Use getLiveTimeline().getState(EventTimeline.FORWARDS) instead.
417
+ */
418
+ public currentState!: RoomState;
419
+
420
+ public readonly relations;
421
+
422
+ /**
423
+ * A collection of events known by the client
424
+ * This is not a comprehensive list of the threads that exist in this room
425
+ */
426
+ private threads = new Map<string, Thread>();
427
+
428
+ /**
429
+ * A mapping of eventId to all visibility changes to apply
430
+ * to the event, by chronological order, as per
431
+ * https://github.com/matrix-org/matrix-doc/pull/3531
432
+ *
433
+ * # Invariants
434
+ *
435
+ * - within each list, all events are classed by
436
+ * chronological order;
437
+ * - all events are events such that
438
+ * `asVisibilityEvent()` returns a non-null `IVisibilityChange`;
439
+ * - within each list with key `eventId`, all events
440
+ * are in relation to `eventId`.
441
+ *
442
+ * @experimental
443
+ */
444
+ private visibilityEvents = new Map<string, BriijEvent[]>();
445
+
446
+ /**
447
+ * The latest receipts (synthetic and real) for each user in each thread
448
+ * (and unthreaded).
449
+ */
450
+ private roomReceipts = new RoomReceipts(this);
451
+
452
+ /**
453
+ * Stores and tracks sticky events
454
+ */
455
+ private stickyEvents = new RoomStickyEventsStore();
456
+
457
+ /**
458
+ * Construct a new Room.
459
+ *
460
+ * <p>For a room, we store an ordered sequence of timelines, which may or may not
461
+ * be continuous. Each timeline lists a series of events, as well as tracking
462
+ * the room state at the start and the end of the timeline. It also tracks
463
+ * forward and backward pagination tokens, as well as containing links to the
464
+ * next timeline in the sequence.
465
+ *
466
+ * <p>There is one special timeline - the 'live' timeline, which represents the
467
+ * timeline to which events are being added in real-time as they are received
468
+ * from the /sync API. Note that you should not retain references to this
469
+ * timeline - even if it is the current timeline right now, it may not remain
470
+ * so if the server gives us a timeline gap in /sync.
471
+ *
472
+ * <p>In order that we can find events from their ids later, we also maintain a
473
+ * map from event_id to timeline and index.
474
+ *
475
+ * @param roomId - Required. The ID of this room.
476
+ * @param client - Required. The client, used to lazy load members.
477
+ * @param myUserId - Required. The ID of the syncing user.
478
+ * @param opts - Configuration options
479
+ */
480
+ public constructor(
481
+ public readonly roomId: string,
482
+ public readonly client: BriijClient,
483
+ public readonly myUserId: string,
484
+ private readonly opts: IOpts = {},
485
+ ) {
486
+ super();
487
+
488
+ // In some cases, we add listeners for every displayed Matrix event, so it's
489
+ // common to have quite a few more than the default limit.
490
+ this.setMaxListeners(100);
491
+ this.reEmitter = new TypedReEmitter(this);
492
+
493
+ opts.pendingEventOrdering = opts.pendingEventOrdering || PendingEventOrdering.Chronological;
494
+
495
+ this.name = roomId;
496
+ this.normalizedName = roomId;
497
+
498
+ this.relations = new RelationsContainer(this.client, this);
499
+
500
+ // Listen to our own receipt event as a more modular way of processing our own
501
+ // receipts. No need to remove the listener: it's on ourself anyway.
502
+ this.on(RoomEvent.Receipt, this.onReceipt);
503
+ this.reEmitter.reEmit(this.stickyEvents, [RoomStickyEventsEvent.Update]);
504
+
505
+ // all our per-room timeline sets. the first one is the unfiltered ones;
506
+ // the subsequent ones are the filtered ones in no particular order.
507
+ this.timelineSets = [new EventTimelineSet(this, opts)];
508
+ this.reEmitter.reEmit(this.getUnfilteredTimelineSet(), [RoomEvent.Timeline, RoomEvent.TimelineReset]);
509
+
510
+ this.fixUpLegacyTimelineFields();
511
+
512
+ if (this.opts.pendingEventOrdering === PendingEventOrdering.Detached) {
513
+ this.pendingEventList = [];
514
+ this.client.store.getPendingEvents(this.roomId).then((events) => {
515
+ const mapper = this.client.getEventMapper({
516
+ decrypt: false,
517
+ });
518
+ events.forEach(async (serializedEvent: Partial<IEvent>) => {
519
+ const event = mapper(serializedEvent);
520
+ await client.decryptEventIfNeeded(event);
521
+ event.setStatus(EventStatus.NOT_SENT);
522
+ this.addPendingEvent(event, event.getTxnId()!);
523
+ });
524
+ });
525
+ }
526
+
527
+ // awaited by getEncryptionTargetMembers while room members are loading
528
+ if (!this.opts.lazyLoadMembers) {
529
+ this.membersPromise = Promise.resolve(false);
530
+ } else {
531
+ this.membersPromise = undefined;
532
+ }
533
+ }
534
+
535
+ private threadTimelineSetsPromise: Promise<[EventTimelineSet, EventTimelineSet]> | null = null;
536
+ public async createThreadsTimelineSets(): Promise<[EventTimelineSet, EventTimelineSet] | null> {
537
+ if (this.threadTimelineSetsPromise) {
538
+ return this.threadTimelineSetsPromise;
539
+ }
540
+
541
+ if (this.client?.supportsThreads()) {
542
+ try {
543
+ this.threadTimelineSetsPromise = Promise.all([
544
+ this.createThreadTimelineSet(),
545
+ this.createThreadTimelineSet(ThreadFilterType.My),
546
+ ]);
547
+ const timelineSets = await this.threadTimelineSetsPromise;
548
+ this.threadsTimelineSets[0] = timelineSets[0];
549
+ this.threadsTimelineSets[1] = timelineSets[1];
550
+ return timelineSets;
551
+ } catch {
552
+ this.threadTimelineSetsPromise = null;
553
+ return null;
554
+ }
555
+ }
556
+ return null;
557
+ }
558
+
559
+ /**
560
+ * Bulk decrypt critical events in a room
561
+ *
562
+ * Critical events represents the minimal set of events to decrypt
563
+ * for a typical UI to function properly
564
+ *
565
+ * - Last event of every room (to generate likely message preview)
566
+ * - All events up to the read receipt (to calculate an accurate notification count)
567
+ *
568
+ * @returns Signals when all events have been decrypted
569
+ */
570
+ public async decryptCriticalEvents(): Promise<void> {
571
+ if (!this.client.getCrypto()) return;
572
+
573
+ const readReceiptEventId = this.getEventReadUpTo(this.client.getUserId()!, true);
574
+ const events = this.getLiveTimeline().getEvents();
575
+ const readReceiptTimelineIndex = events.findIndex((matrixEvent) => {
576
+ return matrixEvent.event.event_id === readReceiptEventId;
577
+ });
578
+
579
+ const decryptionPromises = events
580
+ .slice(readReceiptTimelineIndex)
581
+ .reverse()
582
+ .map((event) => this.client.decryptEventIfNeeded(event));
583
+
584
+ await Promise.allSettled(decryptionPromises);
585
+ }
586
+
587
+ /**
588
+ * Bulk decrypt events in a room
589
+ *
590
+ * @returns Signals when all events have been decrypted
591
+ */
592
+ public async decryptAllEvents(): Promise<void> {
593
+ if (!this.client.getCrypto()) return;
594
+
595
+ const decryptionPromises = this.getUnfilteredTimelineSet()
596
+ .getLiveTimeline()
597
+ .getEvents()
598
+ .slice(0) // copy before reversing
599
+ .reverse()
600
+ .map((event) => this.client.decryptEventIfNeeded(event));
601
+
602
+ await Promise.allSettled(decryptionPromises);
603
+ }
604
+
605
+ /**
606
+ * Gets the creator of the room
607
+ * @returns The creator of the room, or null if it could not be determined
608
+ */
609
+ public getCreator(): string | null {
610
+ const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, "");
611
+ return createEvent?.getSender() ?? null;
612
+ }
613
+
614
+ /**
615
+ * Gets the version of the room
616
+ * @returns The version of the room
617
+ */
618
+ public getVersion(): string {
619
+ return this.currentState.getRoomVersion();
620
+ }
621
+
622
+ /**
623
+ * Determines the recommended room version for the room. This returns an
624
+ * object with 3 properties: `version` as the new version the
625
+ * room should be upgraded to (may be the same as the current version);
626
+ * `needsUpgrade` to indicate if the room actually can be
627
+ * upgraded (ie: does the current version not match?); and `urgent`
628
+ * to indicate if the new version patches a vulnerability in a previous
629
+ * version.
630
+ * @returns
631
+ * Resolves to the version the room should be upgraded to.
632
+ */
633
+ public async getRecommendedVersion(): Promise<IRecommendedVersion> {
634
+ let capabilities: Capabilities = {};
635
+ try {
636
+ capabilities = await this.client.getCapabilities();
637
+ } catch {}
638
+ let versionCap = capabilities["m.room_versions"];
639
+ if (!versionCap) {
640
+ versionCap = {
641
+ default: KNOWN_SAFE_ROOM_VERSION,
642
+ available: {},
643
+ };
644
+ for (const safeVer of SAFE_ROOM_VERSIONS) {
645
+ versionCap.available[safeVer] = RoomVersionStability.Stable;
646
+ }
647
+ }
648
+
649
+ let result = this.checkVersionAgainstCapability(versionCap);
650
+ if (result.urgent && result.needsUpgrade) {
651
+ // Something doesn't feel right: we shouldn't need to update
652
+ // because the version we're on should be in the protocol's
653
+ // namespace. This usually means that the server was updated
654
+ // before the client was, making us think the newest possible
655
+ // room version is not stable. As a solution, we'll refresh
656
+ // the capability we're using to determine this.
657
+ logger.warn(
658
+ "Refreshing room version capability because the server looks " +
659
+ "to be supporting a newer room version we don't know about.",
660
+ );
661
+
662
+ try {
663
+ capabilities = await this.client.fetchCapabilities();
664
+ } catch (e) {
665
+ logger.warn("Failed to refresh room version capabilities", e);
666
+ }
667
+ versionCap = capabilities["m.room_versions"];
668
+ if (!versionCap) {
669
+ logger.warn("No room version capability - assuming upgrade required.");
670
+ return result;
671
+ } else {
672
+ result = this.checkVersionAgainstCapability(versionCap);
673
+ }
674
+ }
675
+
676
+ return result;
677
+ }
678
+
679
+ private checkVersionAgainstCapability(versionCap: IRoomVersionsCapability): IRecommendedVersion {
680
+ const currentVersion = this.getVersion();
681
+ logger.log(`[${this.roomId}] Current version: ${currentVersion}`);
682
+ logger.log(`[${this.roomId}] Version capability: `, versionCap);
683
+
684
+ const result: IRecommendedVersion = {
685
+ version: currentVersion,
686
+ needsUpgrade: false,
687
+ urgent: false,
688
+ };
689
+
690
+ // If the room is on the default version then nothing needs to change
691
+ if (currentVersion === versionCap.default) return result;
692
+
693
+ const stableVersions = Object.keys(versionCap.available).filter((v) => versionCap.available[v] === "stable");
694
+
695
+ // Check if the room is on an unstable version. We determine urgency based
696
+ // off the version being in the Matrix spec namespace or not (if the version
697
+ // is in the current namespace and unstable, the room is probably vulnerable).
698
+ if (!stableVersions.includes(currentVersion)) {
699
+ result.version = versionCap.default;
700
+ result.needsUpgrade = true;
701
+ result.urgent = !!this.getVersion().match(/^[0-9]+[0-9.]*$/g);
702
+ if (result.urgent) {
703
+ logger.warn(`URGENT upgrade required on ${this.roomId}`);
704
+ } else {
705
+ logger.warn(`Non-urgent upgrade required on ${this.roomId}`);
706
+ }
707
+ return result;
708
+ }
709
+
710
+ // The room is on a stable, but non-default, version by this point.
711
+ // No upgrade needed.
712
+ return result;
713
+ }
714
+
715
+ /**
716
+ * Determines whether the given user is permitted to perform a room upgrade
717
+ * @param userId - The ID of the user to test against
718
+ * @returns True if the given user is permitted to upgrade the room
719
+ */
720
+ public userMayUpgradeRoom(userId: string): boolean {
721
+ return this.currentState.maySendStateEvent(EventType.RoomTombstone, userId);
722
+ }
723
+
724
+ /**
725
+ * Get the list of pending sent events for this room
726
+ *
727
+ * @returns A list of the sent events
728
+ * waiting for remote echo.
729
+ *
730
+ * @throws If `opts.pendingEventOrdering` was not 'detached'
731
+ */
732
+ public getPendingEvents(): BriijEvent[] {
733
+ if (!this.pendingEventList) {
734
+ throw new Error(
735
+ "Cannot call getPendingEvents with pendingEventOrdering == " + this.opts.pendingEventOrdering,
736
+ );
737
+ }
738
+
739
+ return this.pendingEventList;
740
+ }
741
+
742
+ /**
743
+ * Removes a pending event for this room
744
+ *
745
+ * @returns True if an element was removed.
746
+ */
747
+ public removePendingEvent(eventId: string): boolean {
748
+ if (!this.pendingEventList) {
749
+ throw new Error(
750
+ "Cannot call removePendingEvent with pendingEventOrdering == " + this.opts.pendingEventOrdering,
751
+ );
752
+ }
753
+
754
+ const removed = removeElement(
755
+ this.pendingEventList,
756
+ function (ev) {
757
+ return ev.getId() == eventId;
758
+ },
759
+ false,
760
+ );
761
+
762
+ this.savePendingEvents();
763
+
764
+ return removed;
765
+ }
766
+
767
+ /**
768
+ * Check whether the pending event list contains a given event by ID.
769
+ * If pending event ordering is not "detached" then this returns false.
770
+ *
771
+ * @param eventId - The event ID to check for.
772
+ */
773
+ public hasPendingEvent(eventId: string): boolean {
774
+ return this.pendingEventList?.some((event) => event.getId() === eventId) ?? false;
775
+ }
776
+
777
+ /**
778
+ * Get a specific event from the pending event list, if configured, null otherwise.
779
+ *
780
+ * @param eventId - The event ID to check for.
781
+ */
782
+ public getPendingEvent(eventId: string): BriijEvent | null {
783
+ return this.pendingEventList?.find((event) => event.getId() === eventId) ?? null;
784
+ }
785
+
786
+ /**
787
+ * Get the live unfiltered timeline for this room.
788
+ *
789
+ * @returns live timeline
790
+ */
791
+ public getLiveTimeline(): EventTimeline {
792
+ return this.getUnfilteredTimelineSet().getLiveTimeline();
793
+ }
794
+
795
+ /**
796
+ * The live event timeline for this room, with the oldest event at index 0.
797
+ *
798
+ * @deprecated Present for backwards compatibility.
799
+ * Use getLiveTimeline().getEvents() instead
800
+ */
801
+ public get timeline(): BriijEvent[] {
802
+ return this.getLiveTimeline().getEvents();
803
+ }
804
+
805
+ /**
806
+ * Get the timestamp of the last message in the room
807
+ *
808
+ * @returns the timestamp of the last message in the room
809
+ */
810
+ public getLastActiveTimestamp(): number {
811
+ const timeline = this.getLiveTimeline();
812
+ const events = timeline.getEvents();
813
+ if (events.length) {
814
+ const lastEvent = events[events.length - 1];
815
+ return lastEvent.getTs();
816
+ } else {
817
+ return Number.MIN_SAFE_INTEGER;
818
+ }
819
+ }
820
+
821
+ /**
822
+ * Returns the last live event of this room.
823
+ * "last" means latest timestamp.
824
+ * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.
825
+ * Unfortunately, this information is currently not available in the client.
826
+ * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.
827
+ * "live of this room" means from all live timelines: the room and the threads.
828
+ *
829
+ * @returns BriijEvent if there is a last event; else undefined.
830
+ */
831
+ public getLastLiveEvent(): BriijEvent | undefined {
832
+ const roomEvents = this.getLiveTimeline().getEvents();
833
+ const lastRoomEvent = roomEvents[roomEvents.length - 1] as BriijEvent | undefined;
834
+ const lastThread = this.getLastThread();
835
+
836
+ if (!lastThread) return lastRoomEvent;
837
+
838
+ const lastThreadEvent = lastThread.events[lastThread.events.length - 1];
839
+
840
+ return (lastRoomEvent?.getTs() ?? 0) > (lastThreadEvent?.getTs() ?? 0) ? lastRoomEvent : lastThreadEvent;
841
+ }
842
+
843
+ /**
844
+ * Returns the last thread of this room.
845
+ * "last" means latest timestamp of the last thread event.
846
+ * Instead of using timestamps, it would be better to do the comparison based on the order of the homeserver DAG.
847
+ * Unfortunately, this information is currently not available in the client.
848
+ * See {@link https://github.com/matrix-org/matrix-js-sdk/issues/3325}.
849
+ *
850
+ * @returns the thread with the most recent event in its live time line. undefined if there is no thread.
851
+ */
852
+ public getLastThread(): Thread | undefined {
853
+ return this.getThreads().reduce<Thread | undefined>((lastThread: Thread | undefined, thread: Thread) => {
854
+ if (!lastThread) return thread;
855
+
856
+ const threadEvent = thread.events[thread.events.length - 1];
857
+ const lastThreadEvent = lastThread.events[lastThread.events.length - 1];
858
+
859
+ if ((threadEvent?.getTs() ?? 0) >= (lastThreadEvent?.getTs() ?? 0)) {
860
+ // Last message of current thread is newer → new last thread.
861
+ // Equal also means newer, because it was added to the thread map later.
862
+ return thread;
863
+ }
864
+
865
+ return lastThread;
866
+ }, undefined);
867
+ }
868
+
869
+ /**
870
+ * @returns the membership type (join | leave | invite | knock) for the logged in user
871
+ */
872
+ public getMyMembership(): Membership {
873
+ return this.selfMembership ?? KnownMembership.Leave;
874
+ }
875
+
876
+ /**
877
+ * If this room is a DM we're invited to,
878
+ * try to find out who invited us
879
+ * @returns user id of the inviter
880
+ */
881
+ public getDMInviter(): string | undefined {
882
+ const me = this.getMember(this.myUserId);
883
+ if (me) {
884
+ return me.getDMInviter();
885
+ }
886
+
887
+ if (this.selfMembership === KnownMembership.Invite) {
888
+ // fall back to summary information
889
+ const memberCount = this.getInvitedAndJoinedMemberCount();
890
+ if (memberCount === 2) {
891
+ return this.heroes?.[0]?.userId;
892
+ }
893
+ }
894
+ }
895
+
896
+ /**
897
+ * Assuming this room is a DM room, tries to guess with which user.
898
+ * @returns user id of the other member (could be syncing user)
899
+ */
900
+ public guessDMUserId(): string {
901
+ const me = this.getMember(this.myUserId);
902
+ if (me) {
903
+ const inviterId = me.getDMInviter();
904
+ if (inviterId) {
905
+ return inviterId;
906
+ }
907
+ }
908
+ // Remember, we're assuming this room is a DM, so returning the first member we find should be fine
909
+ if (Array.isArray(this.heroes) && this.heroes.length) {
910
+ return this.heroes[0].userId;
911
+ }
912
+ const members = this.currentState.getMembers();
913
+ const anyMember = members.find((m) => m.userId !== this.myUserId);
914
+ if (anyMember) {
915
+ return anyMember.userId;
916
+ }
917
+ // it really seems like I'm the only user in the room
918
+ // so I probably created a room with just me in it
919
+ // and marked it as a DM. Ok then
920
+ return this.myUserId;
921
+ }
922
+
923
+ /**
924
+ * Gets the "functional members" in this room.
925
+ *
926
+ * Returns the list of userIDs from the `io.element.functional_members` event. Does not consider the
927
+ * current membership states of those users.
928
+ *
929
+ * @see https://github.com/element-hq/element-meta/blob/develop/spec/functional_members.md.
930
+ */
931
+ private getFunctionalMembers(): string[] {
932
+ const mFunctionalMembers = this.currentState.getStateEvents(UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name, "");
933
+ if (Array.isArray(mFunctionalMembers?.getContent().service_members)) {
934
+ return mFunctionalMembers!.getContent().service_members;
935
+ }
936
+ return [];
937
+ }
938
+
939
+ public getAvatarFallbackMember(): RoomMember | undefined {
940
+ const functionalMembers = this.getFunctionalMembers();
941
+
942
+ // Only generate a fallback avatar if the conversation is with a single specific other user (a "DM").
943
+ let nonFunctionalMemberCount = 0;
944
+ this.getMembers()!.forEach((m) => {
945
+ if (m.membership !== "join" && m.membership !== "invite") return;
946
+ if (functionalMembers.includes(m.userId)) return;
947
+ nonFunctionalMemberCount++;
948
+ });
949
+ if (nonFunctionalMemberCount > 2) return;
950
+
951
+ // Prefer the list of heroes, if present. It should only include the single other user in the DM.
952
+ const nonFunctionalHeroes = this.heroes?.filter((h) => !functionalMembers.includes(h.userId));
953
+ const hasHeroes = Array.isArray(nonFunctionalHeroes) && nonFunctionalHeroes.length;
954
+ if (hasHeroes) {
955
+ // use first hero that has a display name or avatar url, or whose user ID
956
+ // can be looked up as a member of the room
957
+ for (const hero of nonFunctionalHeroes) {
958
+ // If the hero was from a legacy sync (`/v3/sync`), we will need to look the user ID up in the room
959
+ // the display name and avatar URL will not be set.
960
+ if (!hero.fromMSC4186) {
961
+ // attempt to look up renderable fields from the m.room.member event if it exists
962
+ const member = this.getMember(hero.userId);
963
+ if (member) {
964
+ return member;
965
+ }
966
+ } else {
967
+ // use the Hero supplied values for the room member.
968
+ // TODO: It's unfortunate that this function, which clearly only cares about the
969
+ // avatar url, returns the entire RoomMember event. We need to fake an event
970
+ // to meet this API shape.
971
+ const heroMember = new RoomMember(this.roomId, hero.userId);
972
+ // set the display name and avatar url
973
+ heroMember.setMembershipEvent(
974
+ new BriijEvent({
975
+ // ensure it's unique even if we hit the same millisecond
976
+ event_id: "$" + this.roomId + hero.userId + new Date().getTime(),
977
+ type: EventType.RoomMember,
978
+ state_key: hero.userId,
979
+ content: {
980
+ displayname: hero.displayName,
981
+ avatar_url: hero.avatarUrl,
982
+ },
983
+ }),
984
+ );
985
+ return heroMember;
986
+ }
987
+ }
988
+ const availableMember = nonFunctionalHeroes
989
+ .map((hero) => {
990
+ return this.getMember(hero.userId);
991
+ })
992
+ .find((member) => !!member);
993
+ if (availableMember) {
994
+ return availableMember;
995
+ }
996
+ }
997
+
998
+ // Consider *all*, including previous, members, to generate the avatar for DMs where the other user left.
999
+ // Needed to generate a matching avatar for rooms named "Empty Room (was Alice)".
1000
+ const members = this.getMembers();
1001
+ const nonFunctionalMembers = members?.filter((m) => !functionalMembers.includes(m.userId));
1002
+ if (nonFunctionalMembers.length <= 2) {
1003
+ const availableMember = nonFunctionalMembers.find((m) => {
1004
+ return m.userId !== this.myUserId;
1005
+ });
1006
+ if (availableMember) {
1007
+ return availableMember;
1008
+ }
1009
+ }
1010
+
1011
+ // If all else failed, but the homeserver gave us heroes that previously could not be found in the room members,
1012
+ // trust and try falling back to a hero, creating a one-off member for it
1013
+ if (hasHeroes) {
1014
+ const availableUser = nonFunctionalHeroes
1015
+ .map((hero) => {
1016
+ return this.client.getUser(hero.userId);
1017
+ })
1018
+ .find((user) => !!user);
1019
+ if (availableUser) {
1020
+ const member = new RoomMember(this.roomId, availableUser.userId);
1021
+ member.user = availableUser;
1022
+ return member;
1023
+ }
1024
+ }
1025
+ }
1026
+
1027
+ /**
1028
+ * Sets the membership this room was received as during sync
1029
+ * @param membership - join | leave | invite
1030
+ */
1031
+ public updateMyMembership(membership: Membership): void {
1032
+ const prevMembership = this.selfMembership;
1033
+ this.selfMembership = membership;
1034
+ if (prevMembership !== membership) {
1035
+ if (membership === KnownMembership.Leave) {
1036
+ this.cleanupAfterLeaving();
1037
+ }
1038
+ this.emit(RoomEvent.MyMembership, this, membership, prevMembership);
1039
+ }
1040
+ }
1041
+
1042
+ private async loadMembersFromServer(): Promise<IStateEventWithRoomId[]> {
1043
+ const lastSyncToken = this.client.store.getSyncToken();
1044
+ const response = await this.client.members(
1045
+ this.roomId,
1046
+ undefined,
1047
+ KnownMembership.Leave,
1048
+ lastSyncToken ?? undefined,
1049
+ );
1050
+ return response.chunk;
1051
+ }
1052
+
1053
+ private async loadMembers(): Promise<{ memberEvents: BriijEvent[]; fromServer: boolean }> {
1054
+ // were the members loaded from the server?
1055
+ let fromServer = false;
1056
+ let rawMembersEvents = await this.client.store.getOutOfBandMembers(this.roomId);
1057
+ // If the room is encrypted, we always fetch members from the server at
1058
+ // least once, in case the latest state wasn't persisted properly. Note
1059
+ // that this function is only called once (unless loading the members
1060
+ // fails), since loadMembersIfNeeded always returns this.membersPromise
1061
+ // if set, which will be the result of the first (successful) call.
1062
+ if (rawMembersEvents === null || this.hasEncryptionStateEvent()) {
1063
+ fromServer = true;
1064
+ rawMembersEvents = await this.loadMembersFromServer();
1065
+ logger.log(`LL: got ${rawMembersEvents.length} ` + `members from server for room ${this.roomId}`);
1066
+ }
1067
+ const memberEvents = rawMembersEvents.filter(noUnsafeEventProps).map(this.client.getEventMapper());
1068
+ return { memberEvents, fromServer };
1069
+ }
1070
+
1071
+ /**
1072
+ * Check if loading of out-of-band-members has completed
1073
+ *
1074
+ * @returns true if the full membership list of this room has been loaded (including if lazy-loading is disabled).
1075
+ * False if the load is not started or is in progress.
1076
+ */
1077
+ public membersLoaded(): boolean {
1078
+ if (!this.opts.lazyLoadMembers) {
1079
+ return true;
1080
+ }
1081
+
1082
+ return this.currentState.outOfBandMembersReady();
1083
+ }
1084
+
1085
+ /**
1086
+ * Preloads the member list in case lazy loading
1087
+ * of memberships is in use. Can be called multiple times,
1088
+ * it will only preload once.
1089
+ * @returns when preloading is done and
1090
+ * accessing the members on the room will take
1091
+ * all members in the room into account
1092
+ */
1093
+ public loadMembersIfNeeded(): Promise<boolean> {
1094
+ if (this.membersPromise) {
1095
+ return this.membersPromise;
1096
+ }
1097
+
1098
+ // mark the state so that incoming messages while
1099
+ // the request is in flight get marked as superseding
1100
+ // the OOB members
1101
+ this.currentState.markOutOfBandMembersStarted();
1102
+
1103
+ const inMemoryUpdate = this.loadMembers()
1104
+ .then((result) => {
1105
+ this.currentState.setOutOfBandMembers(result.memberEvents);
1106
+ // recalculate the room name: it may have been based on members, so may have changed
1107
+ this.recalculate();
1108
+ return result.fromServer;
1109
+ })
1110
+ .catch((err) => {
1111
+ // allow retries on fail
1112
+ this.membersPromise = undefined;
1113
+ this.currentState.markOutOfBandMembersFailed();
1114
+ throw err;
1115
+ });
1116
+ // update members in storage, but don't wait for it
1117
+ inMemoryUpdate
1118
+ .then((fromServer) => {
1119
+ if (fromServer) {
1120
+ const oobMembers = this.currentState
1121
+ .getMembers()
1122
+ .filter((m) => m.isOutOfBand())
1123
+ .map((m) => m.events.member?.event as IStateEventWithRoomId);
1124
+ logger.log(`LL: telling store to write ${oobMembers.length}` + ` members for room ${this.roomId}`);
1125
+ const store = this.client.store;
1126
+ return (
1127
+ store
1128
+ .setOutOfBandMembers(this.roomId, oobMembers)
1129
+ // swallow any IDB error as we don't want to fail
1130
+ // because of this
1131
+ .catch((err) => {
1132
+ logger.log("LL: storing OOB room members failed, oh well", err);
1133
+ })
1134
+ );
1135
+ }
1136
+ })
1137
+ .catch((err) => {
1138
+ // as this is not awaited anywhere,
1139
+ // at least show the error in the console
1140
+ logger.error(err);
1141
+ });
1142
+
1143
+ this.membersPromise = inMemoryUpdate;
1144
+
1145
+ return this.membersPromise;
1146
+ }
1147
+
1148
+ /**
1149
+ * Removes the lazily loaded members from storage if needed
1150
+ */
1151
+ public async clearLoadedMembersIfNeeded(): Promise<void> {
1152
+ if (this.opts.lazyLoadMembers && this.membersPromise) {
1153
+ await this.loadMembersIfNeeded();
1154
+ await this.client.store.clearOutOfBandMembers(this.roomId);
1155
+ this.currentState.clearOutOfBandMembers();
1156
+ this.membersPromise = undefined;
1157
+ }
1158
+ }
1159
+
1160
+ /**
1161
+ * called when sync receives this room in the leave section
1162
+ * to do cleanup after leaving a room. Possibly called multiple times.
1163
+ */
1164
+ private cleanupAfterLeaving(): void {
1165
+ this.clearLoadedMembersIfNeeded().catch((err) => {
1166
+ logger.error(`error after clearing loaded members from ` + `room ${this.roomId} after leaving`);
1167
+ logger.log(err);
1168
+ });
1169
+ }
1170
+
1171
+ /**
1172
+ * Empty out the current live timeline and re-request it. This is used when
1173
+ * historical messages are imported into the room via MSC2716 `/batch_send`
1174
+ * because the client may already have that section of the timeline loaded.
1175
+ * We need to force the client to throw away their current timeline so that
1176
+ * when they back paginate over the area again with the historical messages
1177
+ * in between, it grabs the newly imported messages. We can listen for
1178
+ * `UNSTABLE_MSC2716_MARKER`, in order to tell when historical messages are ready
1179
+ * to be discovered in the room and the timeline needs a refresh. The SDK
1180
+ * emits a `RoomEvent.HistoryImportedWithinTimeline` event when we detect a
1181
+ * valid marker and can check the needs refresh status via
1182
+ * `room.getTimelineNeedsRefresh()`.
1183
+ */
1184
+ public async refreshLiveTimeline(): Promise<void> {
1185
+ const liveTimelineBefore = this.getLiveTimeline();
1186
+ const forwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.FORWARDS);
1187
+ const backwardPaginationToken = liveTimelineBefore.getPaginationToken(EventTimeline.BACKWARDS);
1188
+ const eventsBefore = liveTimelineBefore.getEvents();
1189
+ const mostRecentEventInTimeline = eventsBefore[eventsBefore.length - 1];
1190
+ logger.log(
1191
+ `[refreshLiveTimeline for ${this.roomId}] at ` +
1192
+ `mostRecentEventInTimeline=${mostRecentEventInTimeline && mostRecentEventInTimeline.getId()} ` +
1193
+ `liveTimelineBefore=${liveTimelineBefore.toString()} ` +
1194
+ `forwardPaginationToken=${forwardPaginationToken} ` +
1195
+ `backwardPaginationToken=${backwardPaginationToken}`,
1196
+ );
1197
+
1198
+ // Get the main TimelineSet
1199
+ const timelineSet = this.getUnfilteredTimelineSet();
1200
+
1201
+ let newTimeline: EventTimeline | null = null;
1202
+ // If there isn't any event in the timeline, let's go fetch the latest
1203
+ // event and construct a timeline from it.
1204
+ //
1205
+ // This should only really happen if the user ran into an error
1206
+ // with refreshing the timeline before which left them in a blank
1207
+ // timeline from `resetLiveTimeline`.
1208
+ if (!mostRecentEventInTimeline) {
1209
+ newTimeline = await this.client.getLatestTimeline(timelineSet);
1210
+ } else {
1211
+ // Empty out all of `this.timelineSets`. But we also need to keep the
1212
+ // same `timelineSet` references around so the React code updates
1213
+ // properly and doesn't ignore the room events we emit because it checks
1214
+ // that the `timelineSet` references are the same. We need the
1215
+ // `timelineSet` empty so that the `client.getEventTimeline(...)` call
1216
+ // later, will call `/context` and create a new timeline instead of
1217
+ // returning the same one.
1218
+ this.resetLiveTimeline(null, null);
1219
+
1220
+ // Make the UI timeline show the new blank live timeline we just
1221
+ // reset so that if the network fails below it's showing the
1222
+ // accurate state of what we're working with instead of the
1223
+ // disconnected one in the TimelineWindow which is just hanging
1224
+ // around by reference.
1225
+ this.emit(RoomEvent.TimelineRefresh, this, timelineSet);
1226
+
1227
+ // Use `client.getEventTimeline(...)` to construct a new timeline from a
1228
+ // `/context` response state and events for the most recent event before
1229
+ // we reset everything. The `timelineSet` we pass in needs to be empty
1230
+ // in order for this function to call `/context` and generate a new
1231
+ // timeline.
1232
+ newTimeline = await this.client.getEventTimeline(timelineSet, mostRecentEventInTimeline.getId()!);
1233
+ }
1234
+
1235
+ // If a racing `/sync` beat us to creating a new timeline, use that
1236
+ // instead because it's the latest in the room and any new messages in
1237
+ // the scrollback will include the history.
1238
+ const liveTimeline = timelineSet.getLiveTimeline();
1239
+ if (
1240
+ !liveTimeline ||
1241
+ (liveTimeline.getPaginationToken(Direction.Forward) === null &&
1242
+ liveTimeline.getPaginationToken(Direction.Backward) === null &&
1243
+ liveTimeline.getEvents().length === 0)
1244
+ ) {
1245
+ logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`);
1246
+ // Set the pagination token back to the live sync token (`null`) instead
1247
+ // of using the `/context` historical token (ex. `t12-13_0_0_0_0_0_0_0_0`)
1248
+ // so that it matches the next response from `/sync` and we can properly
1249
+ // continue the timeline.
1250
+ newTimeline!.setPaginationToken(forwardPaginationToken, EventTimeline.FORWARDS);
1251
+
1252
+ // Set our new fresh timeline as the live timeline to continue syncing
1253
+ // forwards and back paginating from.
1254
+ timelineSet.setLiveTimeline(newTimeline!);
1255
+ // Fixup `this.oldstate` so that `scrollback` has the pagination tokens
1256
+ // available
1257
+ this.fixUpLegacyTimelineFields();
1258
+ } else {
1259
+ logger.log(
1260
+ `[refreshLiveTimeline for ${this.roomId}] \`/sync\` or some other request beat us to creating a new ` +
1261
+ `live timeline after we reset it. We'll use that instead since any events in the scrollback from ` +
1262
+ `this timeline will include the history.`,
1263
+ );
1264
+ }
1265
+
1266
+ // The timeline has now been refreshed ✅
1267
+ this.setTimelineNeedsRefresh(false);
1268
+
1269
+ // Emit an event which clients can react to and re-load the timeline
1270
+ // from the SDK
1271
+ this.emit(RoomEvent.TimelineRefresh, this, timelineSet);
1272
+ }
1273
+
1274
+ /**
1275
+ * Reset the live timeline of all timelineSets, and start new ones.
1276
+ *
1277
+ * <p>This is used when /sync returns a 'limited' timeline.
1278
+ *
1279
+ * @param backPaginationToken - token for back-paginating the new timeline
1280
+ * @param forwardPaginationToken - token for forward-paginating the old live timeline,
1281
+ * if absent or null, all timelines are reset, removing old ones (including the previous live
1282
+ * timeline which would otherwise be unable to paginate forwards without this token).
1283
+ * Removing just the old live timeline whilst preserving previous ones is not supported.
1284
+ */
1285
+ public resetLiveTimeline(backPaginationToken?: string | null, forwardPaginationToken?: string | null): void {
1286
+ for (const timelineSet of this.timelineSets) {
1287
+ timelineSet.resetLiveTimeline(backPaginationToken ?? undefined, forwardPaginationToken ?? undefined);
1288
+ }
1289
+ for (const thread of this.threads.values()) {
1290
+ thread.resetLiveTimeline(backPaginationToken, forwardPaginationToken);
1291
+ }
1292
+
1293
+ this.fixUpLegacyTimelineFields();
1294
+ }
1295
+
1296
+ /**
1297
+ * Fix up this.timeline, this.oldState and this.currentState
1298
+ *
1299
+ * @internal
1300
+ */
1301
+ private fixUpLegacyTimelineFields(): void {
1302
+ const previousOldState = this.oldState;
1303
+ const previousCurrentState = this.currentState;
1304
+
1305
+ // maintain this.oldState and this.currentState as references to the
1306
+ // state at the start and end of that timeline. These are more
1307
+ // for backwards-compatibility than anything else.
1308
+ this.oldState = this.getLiveTimeline().getState(EventTimeline.BACKWARDS)!;
1309
+ this.currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS)!;
1310
+
1311
+ // Let people know to register new listeners for the new state
1312
+ // references. The reference won't necessarily change every time so only
1313
+ // emit when we see a change.
1314
+ if (previousOldState !== this.oldState) {
1315
+ this.emit(RoomEvent.OldStateUpdated, this, previousOldState, this.oldState);
1316
+ }
1317
+
1318
+ if (previousCurrentState !== this.currentState) {
1319
+ this.emit(RoomEvent.CurrentStateUpdated, this, previousCurrentState, this.currentState);
1320
+
1321
+ // Re-emit various events on the current room state
1322
+ // TODO: If currentState really only exists for backwards
1323
+ // compatibility, shouldn't we be doing this some other way?
1324
+ this.reEmitter.stopReEmitting(previousCurrentState, [
1325
+ RoomStateEvent.Events,
1326
+ RoomStateEvent.Members,
1327
+ RoomStateEvent.NewMember,
1328
+ RoomStateEvent.Update,
1329
+ RoomStateEvent.Marker,
1330
+ BeaconEvent.New,
1331
+ BeaconEvent.Update,
1332
+ BeaconEvent.Destroy,
1333
+ BeaconEvent.LivenessChange,
1334
+ ]);
1335
+ this.reEmitter.reEmit(this.currentState, [
1336
+ RoomStateEvent.Events,
1337
+ RoomStateEvent.Members,
1338
+ RoomStateEvent.NewMember,
1339
+ RoomStateEvent.Update,
1340
+ RoomStateEvent.Marker,
1341
+ BeaconEvent.New,
1342
+ BeaconEvent.Update,
1343
+ BeaconEvent.Destroy,
1344
+ BeaconEvent.LivenessChange,
1345
+ ]);
1346
+ }
1347
+ }
1348
+
1349
+ private onReceipt(event: BriijEvent): void {
1350
+ if (this.hasEncryptionStateEvent()) {
1351
+ this.clearNotificationsOnReceipt(event);
1352
+ }
1353
+ }
1354
+
1355
+ private clearNotificationsOnReceipt(event: BriijEvent): void {
1356
+ // Like above, we have to listen for read receipts from ourselves in order to
1357
+ // correctly handle notification counts on encrypted rooms.
1358
+ // This fixes https://github.com/vector-im/element-web/issues/9421
1359
+
1360
+ // Figure out if we've read something or if it's just informational
1361
+ // We need to work out what threads we've just recieved receipts for, so we
1362
+ // know which ones to update. If we've received an unthreaded receipt, we'll
1363
+ // need to update all threads.
1364
+ let threadIds: string[] = [];
1365
+ let hasUnthreadedReceipt = false;
1366
+
1367
+ const content = event.getContent();
1368
+
1369
+ for (const receiptGroup of Object.values(content)) {
1370
+ for (const [receiptType, userReceipt] of Object.entries(receiptGroup)) {
1371
+ if (!utils.isSupportedReceiptType(receiptType)) continue;
1372
+ if (!userReceipt) continue;
1373
+
1374
+ for (const [userId, singleReceipt] of Object.entries(userReceipt)) {
1375
+ if (!singleReceipt || typeof singleReceipt !== "object") continue;
1376
+ const typedSingleReceipt = singleReceipt as Record<string, any>;
1377
+ if (userId !== this.client.getUserId()) continue;
1378
+ if (typedSingleReceipt.thread_id === undefined) {
1379
+ hasUnthreadedReceipt = true;
1380
+ } else if (typeof typedSingleReceipt.thread_id === "string") {
1381
+ threadIds.push(typedSingleReceipt.thread_id);
1382
+ }
1383
+ }
1384
+ }
1385
+ }
1386
+
1387
+ if (hasUnthreadedReceipt) {
1388
+ // If we have an unthreaded receipt, we need to update any threads that have a notification
1389
+ // in them (because we know the receipt can't go backwards so we don't need to check any with
1390
+ // no notifications: the number can only decrease from a receipt).
1391
+ threadIds = this.getThreads()
1392
+ .filter(
1393
+ (thread) =>
1394
+ this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0 ||
1395
+ this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Highlight) > 0,
1396
+ )
1397
+ .map((thread) => thread.id);
1398
+ threadIds.push("main");
1399
+ }
1400
+
1401
+ for (const threadId of threadIds) {
1402
+ // Work backwards to determine how many events are unread. We also set
1403
+ // a limit for how back we'll look to avoid spinning CPU for too long.
1404
+ // If we hit the limit, we assume the count is unchanged.
1405
+ const maxHistory = 20;
1406
+ const timeline = threadId === "main" ? this.getLiveTimeline() : this.getThread(threadId)?.liveTimeline;
1407
+
1408
+ if (!timeline) {
1409
+ logger.warn(`Couldn't find timeline for thread ID ${threadId} in room ${this.roomId}`);
1410
+ continue;
1411
+ }
1412
+
1413
+ const events = timeline.getEvents();
1414
+
1415
+ let highlightCount = 0;
1416
+
1417
+ for (let i = events.length - 1; i >= 0; i--) {
1418
+ if (i === events.length - maxHistory) return; // limit reached
1419
+
1420
+ const event = events[i];
1421
+
1422
+ if (this.hasUserReadEvent(this.client.getUserId()!, event.getId()!)) {
1423
+ // If the user has read the event, then the counting is done.
1424
+ break;
1425
+ }
1426
+
1427
+ const pushActions = this.client.getPushActionsForEvent(event);
1428
+ highlightCount += pushActions?.tweaks?.highlight ? 1 : 0;
1429
+ }
1430
+
1431
+ // Note: we don't need to handle 'total' notifications because the counts
1432
+ // will come from the server.
1433
+ if (threadId === "main") {
1434
+ this.setUnreadNotificationCount(NotificationCountType.Highlight, highlightCount);
1435
+ } else {
1436
+ this.setThreadUnreadNotificationCount(threadId, NotificationCountType.Highlight, highlightCount);
1437
+ }
1438
+ }
1439
+ }
1440
+
1441
+ /**
1442
+ * Return the timeline sets for this room.
1443
+ * @returns array of timeline sets for this room
1444
+ */
1445
+ public getTimelineSets(): EventTimelineSet[] {
1446
+ return this.timelineSets;
1447
+ }
1448
+
1449
+ /**
1450
+ * Helper to return the main unfiltered timeline set for this room
1451
+ * @returns room's unfiltered timeline set
1452
+ */
1453
+ public getUnfilteredTimelineSet(): EventTimelineSet {
1454
+ return this.timelineSets[0];
1455
+ }
1456
+
1457
+ /**
1458
+ * Get the timeline which contains the given event from the unfiltered set, if any
1459
+ *
1460
+ * @param eventId - event ID to look for
1461
+ * @returns timeline containing
1462
+ * the given event, or null if unknown
1463
+ */
1464
+ public getTimelineForEvent(eventId: string): EventTimeline | null {
1465
+ const event = this.findEventById(eventId);
1466
+ const thread = this.findThreadForEvent(event);
1467
+ if (thread) {
1468
+ return thread.timelineSet.getTimelineForEvent(eventId);
1469
+ } else {
1470
+ return this.getUnfilteredTimelineSet().getTimelineForEvent(eventId);
1471
+ }
1472
+ }
1473
+
1474
+ /**
1475
+ * Add a new timeline to this room's unfiltered timeline set
1476
+ *
1477
+ * @returns newly-created timeline
1478
+ */
1479
+ public addTimeline(): EventTimeline {
1480
+ return this.getUnfilteredTimelineSet().addTimeline();
1481
+ }
1482
+
1483
+ /**
1484
+ * Whether the timeline needs to be refreshed in order to pull in new
1485
+ * historical messages that were imported.
1486
+ * @param value - The value to set
1487
+ */
1488
+ public setTimelineNeedsRefresh(value: boolean): void {
1489
+ this.timelineNeedsRefresh = value;
1490
+ }
1491
+
1492
+ /**
1493
+ * Whether the timeline needs to be refreshed in order to pull in new
1494
+ * historical messages that were imported.
1495
+ * @returns .
1496
+ */
1497
+ public getTimelineNeedsRefresh(): boolean {
1498
+ return this.timelineNeedsRefresh;
1499
+ }
1500
+
1501
+ /**
1502
+ * Get an event which is stored in our unfiltered timeline set, or in a thread
1503
+ *
1504
+ * @param eventId - event ID to look for
1505
+ * @returns the given event, or undefined if unknown
1506
+ */
1507
+ public findEventById(eventId: string): BriijEvent | undefined {
1508
+ let event = this.getUnfilteredTimelineSet().findEventById(eventId);
1509
+
1510
+ if (!event) {
1511
+ const threads = this.getThreads();
1512
+ for (let i = 0; i < threads.length; i++) {
1513
+ const thread = threads[i];
1514
+ event = thread.findEventById(eventId);
1515
+ if (event) {
1516
+ return event;
1517
+ }
1518
+ }
1519
+ }
1520
+
1521
+ return event;
1522
+ }
1523
+
1524
+ /**
1525
+ * Get one of the notification counts for this room
1526
+ * @param type - The type of notification count to get. default: 'total'
1527
+ * @returns The notification count, or undefined if there is no count
1528
+ * for this type.
1529
+ */
1530
+ public getUnreadNotificationCount(type = NotificationCountType.Total): number {
1531
+ let count = this.getRoomUnreadNotificationCount(type);
1532
+ for (const threadNotification of this.threadNotifications.values()) {
1533
+ count += threadNotification[type] ?? 0;
1534
+ }
1535
+ return count;
1536
+ }
1537
+
1538
+ /**
1539
+ * Get the notification for the event context (room or thread timeline)
1540
+ */
1541
+ public getUnreadCountForEventContext(type = NotificationCountType.Total, event: BriijEvent): number {
1542
+ const isThreadEvent = !!event.threadRootId && !event.isThreadRoot;
1543
+
1544
+ return (
1545
+ (isThreadEvent
1546
+ ? this.getThreadUnreadNotificationCount(event.threadRootId, type)
1547
+ : this.getRoomUnreadNotificationCount(type)) ?? 0
1548
+ );
1549
+ }
1550
+
1551
+ /**
1552
+ * Get one of the notification counts for this room
1553
+ * @param type - The type of notification count to get. default: 'total'
1554
+ * @returns The notification count, or undefined if there is no count
1555
+ * for this type.
1556
+ */
1557
+ public getRoomUnreadNotificationCount(type = NotificationCountType.Total): number {
1558
+ return this.notificationCounts[type] ?? 0;
1559
+ }
1560
+
1561
+ /**
1562
+ * Get one of the notification counts for a thread
1563
+ * @param threadId - the root event ID
1564
+ * @param type - The type of notification count to get. default: 'total'
1565
+ * @returns The notification count, or undefined if there is no count
1566
+ * for this type.
1567
+ */
1568
+ public getThreadUnreadNotificationCount(threadId: string, type = NotificationCountType.Total): number {
1569
+ return this.threadNotifications.get(threadId)?.[type] ?? 0;
1570
+ }
1571
+
1572
+ /**
1573
+ * Checks if the current room has unread thread notifications
1574
+ * @returns
1575
+ */
1576
+ public hasThreadUnreadNotification(): boolean {
1577
+ for (const notification of this.threadNotifications.values()) {
1578
+ if ((notification.highlight ?? 0) > 0 || (notification.total ?? 0) > 0) {
1579
+ return true;
1580
+ }
1581
+ }
1582
+ return false;
1583
+ }
1584
+
1585
+ /**
1586
+ * Swet one of the notification count for a thread
1587
+ * @param threadId - the root event ID
1588
+ * @param type - The type of notification count to get. default: 'total'
1589
+ * @returns
1590
+ */
1591
+ public setThreadUnreadNotificationCount(threadId: string, type: NotificationCountType, count: number): void {
1592
+ const notification: NotificationCount = {
1593
+ highlight: this.threadNotifications.get(threadId)?.highlight,
1594
+ total: this.threadNotifications.get(threadId)?.total,
1595
+ ...{
1596
+ [type]: count,
1597
+ },
1598
+ };
1599
+
1600
+ this.threadNotifications.set(threadId, notification);
1601
+
1602
+ this.emit(RoomEvent.UnreadNotifications, notification, threadId);
1603
+ }
1604
+
1605
+ /**
1606
+ * @returns the notification count type for all the threads in the room
1607
+ */
1608
+ public get threadsAggregateNotificationType(): NotificationCountType | null {
1609
+ let type: NotificationCountType | null = null;
1610
+ for (const threadNotification of this.threadNotifications.values()) {
1611
+ if ((threadNotification.highlight ?? 0) > 0) {
1612
+ return NotificationCountType.Highlight;
1613
+ } else if ((threadNotification.total ?? 0) > 0 && !type) {
1614
+ type = NotificationCountType.Total;
1615
+ }
1616
+ }
1617
+ return type;
1618
+ }
1619
+
1620
+ /**
1621
+ * Resets the total thread notifications for all threads in this room to zero,
1622
+ * excluding any threads whose IDs are given in `exceptThreadIds`.
1623
+ *
1624
+ * If the room is not encrypted, also resets the highlight notification count to zero
1625
+ * for the same set of threads.
1626
+ *
1627
+ * This is intended for use from the sync code since we calculate highlight notification
1628
+ * counts locally from decrypted messages. We want to partially trust the total from the
1629
+ * server such that we clear notifications when read receipts arrive. The weird name is
1630
+ * intended to reflect this. You probably do not want to use this.
1631
+ *
1632
+ * @param exceptThreadIds - The thread IDs to exclude from the reset.
1633
+ */
1634
+ public resetThreadUnreadNotificationCountFromSync(exceptThreadIds: string[] = []): void {
1635
+ const isEncrypted = this.hasEncryptionStateEvent();
1636
+
1637
+ for (const [threadId, notifs] of this.threadNotifications) {
1638
+ if (!exceptThreadIds.includes(threadId)) {
1639
+ notifs.total = 0;
1640
+ if (!isEncrypted) {
1641
+ notifs.highlight = 0;
1642
+ }
1643
+ }
1644
+ }
1645
+
1646
+ this.emit(RoomEvent.UnreadNotifications);
1647
+ }
1648
+
1649
+ /**
1650
+ * Set the bump stamp for this room. This can be used for sorting rooms when the timeline
1651
+ * entries are unknown. Used in MSC4186: Simplified Sliding Sync.
1652
+ * @param bumpStamp The bump_stamp value from the server
1653
+ */
1654
+ public setBumpStamp(bumpStamp: number): void {
1655
+ this.bumpStamp = bumpStamp;
1656
+ }
1657
+
1658
+ /**
1659
+ * Get the bump stamp for this room. This can be used for sorting rooms when the timeline
1660
+ * entries are unknown. Used in MSC4186: Simplified Sliding Sync.
1661
+ * @returns The bump stamp for the room, if it exists.
1662
+ */
1663
+ public getBumpStamp(): number | undefined {
1664
+ return this.bumpStamp;
1665
+ }
1666
+
1667
+ /**
1668
+ * Set one of the notification counts for this room
1669
+ * @param type - The type of notification count to set.
1670
+ * @param count - The new count
1671
+ */
1672
+ public setUnreadNotificationCount(type: NotificationCountType, count: number): void {
1673
+ this.notificationCounts[type] = count;
1674
+ this.emit(RoomEvent.UnreadNotifications, this.notificationCounts);
1675
+ }
1676
+
1677
+ public setUnread(type: NotificationCountType, count: number): void {
1678
+ return this.setUnreadNotificationCount(type, count);
1679
+ }
1680
+
1681
+ /**
1682
+ * Takes a legacy room summary (/v3/sync as opposed to MSC4186) and updates the room with it.
1683
+ *
1684
+ * @param summary - The room summary to update the room with
1685
+ */
1686
+ public setSummary(summary: IRoomSummary): void {
1687
+ const heroes = summary["m.heroes"]?.map((h) => ({ userId: h, fromMSC4186: false }));
1688
+ const joinedCount = summary["m.joined_member_count"];
1689
+ const invitedCount = summary["m.invited_member_count"];
1690
+ if (Number.isInteger(joinedCount)) {
1691
+ this.currentState.setJoinedMemberCount(joinedCount!);
1692
+ }
1693
+ if (Number.isInteger(invitedCount)) {
1694
+ this.currentState.setInvitedMemberCount(invitedCount!);
1695
+ }
1696
+ if (Array.isArray(heroes)) {
1697
+ // filter out ourselves just in case
1698
+ this.heroes = heroes.filter((h) => {
1699
+ return h.userId != this.myUserId;
1700
+ });
1701
+ }
1702
+
1703
+ this.emit(RoomEvent.Summary, summary);
1704
+ }
1705
+
1706
+ /**
1707
+ * Takes information from the MSC4186 room summary and updates the room with it.
1708
+ *
1709
+ * @param heroes - The room's hero members
1710
+ * @param joinedCount - The number of joined members
1711
+ * @param invitedCount - The number of invited members
1712
+ */
1713
+ public setMSC4186SummaryData(
1714
+ heroes: MSC4186Hero[] | undefined,
1715
+ joinedCount: number | undefined,
1716
+ invitedCount: number | undefined,
1717
+ ): void {
1718
+ if (heroes) {
1719
+ this.heroes = heroes
1720
+ .filter((h) => h.user_id !== this.myUserId)
1721
+ .map((h) => ({
1722
+ userId: h.user_id,
1723
+ displayName: h.displayname,
1724
+ avatarUrl: h.avatar_url,
1725
+ fromMSC4186: true,
1726
+ }));
1727
+ }
1728
+ if (joinedCount !== undefined && Number.isInteger(joinedCount)) {
1729
+ this.currentState.setJoinedMemberCount(joinedCount);
1730
+ }
1731
+ if (invitedCount !== undefined && Number.isInteger(invitedCount)) {
1732
+ this.currentState.setInvitedMemberCount(invitedCount);
1733
+ }
1734
+
1735
+ // Construct a summary object to emit as the event wants the info in a single object
1736
+ // more like old-style (/v3/sync) summaries.
1737
+ this.emit(RoomEvent.Summary, {
1738
+ "m.heroes": this.heroes ? this.heroes.map((h) => h.userId) : [],
1739
+ "m.joined_member_count": joinedCount,
1740
+ "m.invited_member_count": invitedCount,
1741
+ });
1742
+ }
1743
+
1744
+ /**
1745
+ * Whether to send encrypted messages to devices within this room.
1746
+ * @param value - true to blacklist unverified devices, null
1747
+ * to use the global value for this room.
1748
+ */
1749
+ public setBlacklistUnverifiedDevices(value: boolean): void {
1750
+ this.blacklistUnverifiedDevices = value;
1751
+ }
1752
+
1753
+ /**
1754
+ * Whether to send encrypted messages to devices within this room.
1755
+ * @returns true if blacklisting unverified devices, null
1756
+ * if the global value should be used for this room.
1757
+ */
1758
+ public getBlacklistUnverifiedDevices(): boolean | null {
1759
+ if (this.blacklistUnverifiedDevices === undefined) return null;
1760
+ return this.blacklistUnverifiedDevices;
1761
+ }
1762
+
1763
+ /**
1764
+ * Get the avatar URL for a room if one was set.
1765
+ * @param baseUrl - The homeserver base URL. See
1766
+ * {@link BriijClient#getHomeserverUrl}.
1767
+ * @param width - The desired width of the thumbnail.
1768
+ * @param height - The desired height of the thumbnail.
1769
+ * @param resizeMethod - The thumbnail resize method to use, either
1770
+ * "crop" or "scale".
1771
+ * @param allowDefault - True to allow an identicon for this room if an
1772
+ * avatar URL wasn't explicitly set. Default: true. (Deprecated)
1773
+ * @param useAuthentication - (optional) If true, the caller supports authenticated
1774
+ * media and wants an authentication-required URL. Note that server support for
1775
+ * authenticated media will not be checked - it is the caller's responsibility
1776
+ * to do so before calling this function. Note also that useAuthentication
1777
+ * implies allowRedirects. Defaults to false (unauthenticated endpoints).
1778
+ * @returns the avatar URL or null.
1779
+ */
1780
+ public getAvatarUrl(
1781
+ baseUrl: string,
1782
+ width: number,
1783
+ height: number,
1784
+ resizeMethod: ResizeMethod,
1785
+ allowDefault = true,
1786
+ useAuthentication: boolean = false,
1787
+ ): string | null {
1788
+ const mainUrl = this.getMxcAvatarUrl();
1789
+ if (!mainUrl && !allowDefault) {
1790
+ return null;
1791
+ }
1792
+
1793
+ if (mainUrl) {
1794
+ return getHttpUriForMxc(
1795
+ baseUrl,
1796
+ mainUrl,
1797
+ width,
1798
+ height,
1799
+ resizeMethod,
1800
+ undefined,
1801
+ undefined,
1802
+ useAuthentication,
1803
+ );
1804
+ }
1805
+
1806
+ return null;
1807
+ }
1808
+
1809
+ /**
1810
+ * Get the mxc avatar url for the room, if one was set.
1811
+ * @returns the mxc avatar url or falsy
1812
+ */
1813
+ public getMxcAvatarUrl(): string | null {
1814
+ const url = this.currentState.getStateEvents(EventType.RoomAvatar, "")?.getContent().url;
1815
+ return url && typeof url === "string" ? url : null;
1816
+ }
1817
+
1818
+ /**
1819
+ * Get this room's canonical alias
1820
+ * The alias returned by this function may not necessarily
1821
+ * still point to this room.
1822
+ * @returns The room's canonical alias, or null if there is none
1823
+ */
1824
+ public getCanonicalAlias(): string | null {
1825
+ const canonicalAlias = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, "")?.getContent().alias;
1826
+ return canonicalAlias && typeof canonicalAlias === "string" ? canonicalAlias : null;
1827
+ }
1828
+
1829
+ /**
1830
+ * Get this room's alternative aliases
1831
+ * @returns The room's alternative aliases, or an empty array
1832
+ */
1833
+ public getAltAliases(): string[] {
1834
+ const altAliases = this.currentState.getStateEvents(EventType.RoomCanonicalAlias, "")?.getContent().alt_aliases;
1835
+ if (Array.isArray(altAliases)) {
1836
+ return altAliases.filter((alias) => typeof alias === "string");
1837
+ }
1838
+ return [];
1839
+ }
1840
+
1841
+ /**
1842
+ * Add events to a timeline
1843
+ *
1844
+ * <p>Will fire "Room.timeline" for each event added.
1845
+ *
1846
+ * @param events - A list of events to add.
1847
+ *
1848
+ * @param toStartOfTimeline - True to add these events to the start
1849
+ * (oldest) instead of the end (newest) of the timeline. If true, the oldest
1850
+ * event will be the <b>last</b> element of 'events'.
1851
+ *
1852
+ * @param timeline - timeline to
1853
+ * add events to.
1854
+ *
1855
+ * @param paginationToken - token for the next batch of events
1856
+ *
1857
+ * @remarks
1858
+ * Fires {@link RoomEvent.Timeline}
1859
+ */
1860
+ public addEventsToTimeline(
1861
+ events: BriijEvent[],
1862
+ toStartOfTimeline: boolean,
1863
+ addToState: boolean,
1864
+ timeline: EventTimeline,
1865
+ paginationToken?: string,
1866
+ ): void {
1867
+ timeline.getTimelineSet().addEventsToTimeline(events, toStartOfTimeline, addToState, timeline, paginationToken);
1868
+ }
1869
+
1870
+ /**
1871
+ * Get the instance of the thread associated with the current event
1872
+ * @param eventId - the ID of the current event
1873
+ * @returns a thread instance if known
1874
+ */
1875
+ public getThread(eventId: string): Thread | null {
1876
+ return this.threads.get(eventId) ?? null;
1877
+ }
1878
+
1879
+ /**
1880
+ * Get all the known threads in the room
1881
+ */
1882
+ public getThreads(): Thread[] {
1883
+ return Array.from(this.threads.values());
1884
+ }
1885
+
1886
+ /**
1887
+ * Get a member from the current room state.
1888
+ * @param userId - The user ID of the member.
1889
+ * @returns The member or `null`.
1890
+ */
1891
+ public getMember(userId: string): RoomMember | null {
1892
+ return this.currentState.getMember(userId);
1893
+ }
1894
+
1895
+ /**
1896
+ * Get all currently loaded members from the current
1897
+ * room state.
1898
+ * @returns Room members
1899
+ */
1900
+ public getMembers(): RoomMember[] {
1901
+ return this.currentState.getMembers();
1902
+ }
1903
+
1904
+ /**
1905
+ * Get a list of members whose membership state is "join".
1906
+ * @returns A list of currently joined members.
1907
+ */
1908
+ public getJoinedMembers(): RoomMember[] {
1909
+ return this.getMembersWithMembership(KnownMembership.Join);
1910
+ }
1911
+
1912
+ /**
1913
+ * Returns the number of joined members in this room
1914
+ * This method caches the result.
1915
+ * This is a wrapper around the method of the same name in roomState, returning
1916
+ * its result for the room's current state.
1917
+ * @returns The number of members in this room whose membership is 'join'
1918
+ */
1919
+ public getJoinedMemberCount(): number {
1920
+ return this.currentState.getJoinedMemberCount();
1921
+ }
1922
+
1923
+ /**
1924
+ * Returns the number of invited members in this room
1925
+ * @returns The number of members in this room whose membership is 'invite'
1926
+ */
1927
+ public getInvitedMemberCount(): number {
1928
+ return this.currentState.getInvitedMemberCount();
1929
+ }
1930
+
1931
+ /**
1932
+ * Returns the number of invited + joined members in this room
1933
+ * @returns The number of members in this room whose membership is 'invite' or 'join'
1934
+ */
1935
+ public getInvitedAndJoinedMemberCount(): number {
1936
+ return this.getInvitedMemberCount() + this.getJoinedMemberCount();
1937
+ }
1938
+
1939
+ /**
1940
+ * Get a list of members with given membership state.
1941
+ * @param membership - The membership state.
1942
+ * @returns A list of members with the given membership state.
1943
+ */
1944
+ public getMembersWithMembership(membership: Membership): RoomMember[] {
1945
+ return this.currentState.getMembers().filter(function (m) {
1946
+ return m.membership === membership;
1947
+ });
1948
+ }
1949
+
1950
+ /**
1951
+ * Get a list of members we should be encrypting for in this room
1952
+ * @returns A list of members who
1953
+ * we should encrypt messages for in this room.
1954
+ */
1955
+ public async getEncryptionTargetMembers(): Promise<RoomMember[]> {
1956
+ await this.loadMembersIfNeeded();
1957
+ let members = this.getMembersWithMembership(KnownMembership.Join);
1958
+ if (this.shouldEncryptForInvitedMembers()) {
1959
+ members = members.concat(this.getMembersWithMembership(KnownMembership.Invite));
1960
+ }
1961
+ return members;
1962
+ }
1963
+
1964
+ /**
1965
+ * Determine whether we should encrypt messages for invited users in this room
1966
+ * @returns if we should encrypt messages for invited users
1967
+ */
1968
+ public shouldEncryptForInvitedMembers(): boolean {
1969
+ const ev = this.currentState.getStateEvents(EventType.RoomHistoryVisibility, "");
1970
+ return ev?.getContent()?.history_visibility !== "joined";
1971
+ }
1972
+
1973
+ /**
1974
+ * Get the default room name (i.e. what a given user would see if the
1975
+ * room had no m.room.name)
1976
+ * @param userId - The userId from whose perspective we want
1977
+ * to calculate the default name
1978
+ * @returns The default room name
1979
+ */
1980
+ public getDefaultRoomName(userId: string): string {
1981
+ return this.calculateRoomName(userId, true);
1982
+ }
1983
+
1984
+ /**
1985
+ * Check if the given user_id has the given membership state.
1986
+ * @param userId - The user ID to check.
1987
+ * @param membership - The membership e.g. `'join'`
1988
+ * @returns True if this user_id has the given membership state.
1989
+ */
1990
+ public hasMembershipState(userId: string, membership: Membership): boolean {
1991
+ const member = this.getMember(userId);
1992
+ if (!member) {
1993
+ return false;
1994
+ }
1995
+ return member.membership === membership;
1996
+ }
1997
+
1998
+ /**
1999
+ * Add a timelineSet for this room with the given filter
2000
+ * @param filter - The filter to be applied to this timelineSet
2001
+ * @param opts - Configuration options
2002
+ * @returns The timelineSet
2003
+ */
2004
+ public getOrCreateFilteredTimelineSet(
2005
+ filter: Filter,
2006
+ { prepopulateTimeline = true, useSyncEvents = true, pendingEvents = true }: ICreateFilterOpts = {},
2007
+ ): EventTimelineSet {
2008
+ if (this.filteredTimelineSets[filter.filterId!]) {
2009
+ return this.filteredTimelineSets[filter.filterId!];
2010
+ }
2011
+ const opts = Object.assign({ filter, pendingEvents }, this.opts);
2012
+ const timelineSet = new EventTimelineSet(this, opts);
2013
+ this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);
2014
+ if (useSyncEvents) {
2015
+ this.filteredTimelineSets[filter.filterId!] = timelineSet;
2016
+ this.timelineSets.push(timelineSet);
2017
+ }
2018
+
2019
+ const unfilteredLiveTimeline = this.getLiveTimeline();
2020
+ // Not all filter are possible to replicate client-side only
2021
+ // When that's the case we do not want to prepopulate from the live timeline
2022
+ // as we would get incorrect results compared to what the server would send back
2023
+ if (prepopulateTimeline) {
2024
+ // populate up the new timelineSet with filtered events from our live
2025
+ // unfiltered timeline.
2026
+ //
2027
+ // XXX: This is risky as our timeline
2028
+ // may have grown huge and so take a long time to filter.
2029
+ // see https://github.com/vector-im/vector-web/issues/2109
2030
+
2031
+ unfilteredLiveTimeline.getEvents().forEach(function (event) {
2032
+ timelineSet.addLiveEvent(event, { addToState: false }); // Filtered timeline sets should not track state
2033
+ });
2034
+
2035
+ // find the earliest unfiltered timeline
2036
+ let timeline = unfilteredLiveTimeline;
2037
+ while (timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)) {
2038
+ timeline = timeline.getNeighbouringTimeline(EventTimeline.BACKWARDS)!;
2039
+ }
2040
+
2041
+ timelineSet
2042
+ .getLiveTimeline()
2043
+ .setPaginationToken(timeline.getPaginationToken(EventTimeline.BACKWARDS), EventTimeline.BACKWARDS);
2044
+ } else if (useSyncEvents) {
2045
+ const livePaginationToken = unfilteredLiveTimeline.getPaginationToken(Direction.Forward);
2046
+ timelineSet.getLiveTimeline().setPaginationToken(livePaginationToken, Direction.Backward);
2047
+ }
2048
+
2049
+ // alternatively, we could try to do something like this to try and re-paginate
2050
+ // in the filtered events from nothing, but Mark says it's an abuse of the API
2051
+ // to do so:
2052
+ //
2053
+ // timelineSet.resetLiveTimeline(
2054
+ // unfilteredLiveTimeline.getPaginationToken(EventTimeline.FORWARDS)
2055
+ // );
2056
+
2057
+ return timelineSet;
2058
+ }
2059
+
2060
+ private async getThreadListFilter(filterType = ThreadFilterType.All): Promise<Filter> {
2061
+ const myUserId = this.client.getUserId()!;
2062
+ const filter = new Filter(myUserId);
2063
+
2064
+ const definition: IFilterDefinition = {
2065
+ room: {
2066
+ timeline: {
2067
+ [FILTER_RELATED_BY_REL_TYPES.name]: [THREAD_RELATION_TYPE.name],
2068
+ },
2069
+ },
2070
+ };
2071
+
2072
+ if (filterType === ThreadFilterType.My) {
2073
+ definition!.room!.timeline![FILTER_RELATED_BY_SENDERS.name] = [myUserId];
2074
+ }
2075
+
2076
+ filter.setDefinition(definition);
2077
+ const filterId = await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${filterType}`, filter);
2078
+
2079
+ filter.filterId = filterId;
2080
+
2081
+ return filter;
2082
+ }
2083
+
2084
+ private async createThreadTimelineSet(filterType?: ThreadFilterType): Promise<EventTimelineSet> {
2085
+ let timelineSet: EventTimelineSet;
2086
+ if (Thread.hasServerSideListSupport) {
2087
+ timelineSet = new EventTimelineSet(
2088
+ this,
2089
+ {
2090
+ ...this.opts,
2091
+ pendingEvents: false,
2092
+ },
2093
+ undefined,
2094
+ undefined,
2095
+ filterType ?? ThreadFilterType.All,
2096
+ );
2097
+ this.reEmitter.reEmit(timelineSet, [RoomEvent.Timeline, RoomEvent.TimelineReset]);
2098
+ } else if (Thread.hasServerSideSupport) {
2099
+ const filter = await this.getThreadListFilter(filterType);
2100
+
2101
+ timelineSet = this.getOrCreateFilteredTimelineSet(filter, {
2102
+ prepopulateTimeline: false,
2103
+ useSyncEvents: false,
2104
+ pendingEvents: false,
2105
+ });
2106
+ } else {
2107
+ timelineSet = new EventTimelineSet(this, {
2108
+ pendingEvents: false,
2109
+ });
2110
+
2111
+ Array.from(this.threads).forEach(([, thread]) => {
2112
+ if (thread.length === 0) return;
2113
+ const currentUserParticipated = thread.timeline.some((event) => {
2114
+ return event.getSender() === this.client.getUserId();
2115
+ });
2116
+ if (filterType !== ThreadFilterType.My || currentUserParticipated) {
2117
+ timelineSet.getLiveTimeline().addEvent(thread.rootEvent!, {
2118
+ toStartOfTimeline: false,
2119
+ addToState: false,
2120
+ });
2121
+ }
2122
+ });
2123
+ }
2124
+
2125
+ return timelineSet;
2126
+ }
2127
+
2128
+ private threadsReady = false;
2129
+
2130
+ /**
2131
+ * Takes the given thread root events and creates threads for them.
2132
+ */
2133
+ public processThreadRoots(events: BriijEvent[], toStartOfTimeline: boolean): void {
2134
+ if (!this.client.supportsThreads()) return;
2135
+ for (const rootEvent of events) {
2136
+ EventTimeline.setEventMetadata(rootEvent, this.currentState, toStartOfTimeline);
2137
+ if (!this.getThread(rootEvent.getId()!)) {
2138
+ this.createThread(rootEvent.getId()!, rootEvent, [], toStartOfTimeline);
2139
+ }
2140
+ }
2141
+ }
2142
+
2143
+ /**
2144
+ * Fetch the bare minimum of room threads required for the thread list to work reliably.
2145
+ * With server support that means fetching one page.
2146
+ * Without server support that means fetching as much at once as the server allows us to.
2147
+ */
2148
+ public async fetchRoomThreads(): Promise<void> {
2149
+ if (this.threadsReady || !this.client.supportsThreads()) {
2150
+ return;
2151
+ }
2152
+
2153
+ if (Thread.hasServerSideListSupport) {
2154
+ await Promise.all([
2155
+ this.fetchRoomThreadList(ThreadFilterType.All),
2156
+ this.fetchRoomThreadList(ThreadFilterType.My),
2157
+ ]);
2158
+ } else {
2159
+ const allThreadsFilter = await this.getThreadListFilter();
2160
+
2161
+ const { chunk: events } = await this.client.createMessagesRequest(
2162
+ this.roomId,
2163
+ "",
2164
+ Number.MAX_SAFE_INTEGER,
2165
+ Direction.Backward,
2166
+ allThreadsFilter,
2167
+ );
2168
+
2169
+ if (!events.length) return;
2170
+
2171
+ // Sorted by last_reply origin_server_ts
2172
+ const threadRoots = events.map(this.client.getEventMapper()).sort((eventA, eventB) => {
2173
+ /**
2174
+ * `origin_server_ts` in a decentralised world is far from ideal
2175
+ * but for lack of any better, we will have to use this
2176
+ * Long term the sorting should be handled by homeservers and this
2177
+ * is only meant as a short term patch
2178
+ */
2179
+ const threadAMetadata = eventA.getServerAggregatedRelation<IThreadBundledRelationship>(
2180
+ THREAD_RELATION_TYPE.name,
2181
+ )!;
2182
+ const threadBMetadata = eventB.getServerAggregatedRelation<IThreadBundledRelationship>(
2183
+ THREAD_RELATION_TYPE.name,
2184
+ )!;
2185
+ return threadAMetadata.latest_event.origin_server_ts - threadBMetadata.latest_event.origin_server_ts;
2186
+ });
2187
+
2188
+ let latestMyThreadsRootEvent: BriijEvent | undefined;
2189
+ const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);
2190
+ for (const rootEvent of threadRoots) {
2191
+ const opts = {
2192
+ duplicateStrategy: DuplicateStrategy.Ignore,
2193
+ fromCache: false,
2194
+ addToState: false,
2195
+ roomState,
2196
+ };
2197
+ this.threadsTimelineSets[0]?.addLiveEvent(rootEvent, opts);
2198
+
2199
+ const threadRelationship = rootEvent.getServerAggregatedRelation<IThreadBundledRelationship>(
2200
+ THREAD_RELATION_TYPE.name,
2201
+ );
2202
+ if (threadRelationship?.current_user_participated) {
2203
+ this.threadsTimelineSets[1]?.addLiveEvent(rootEvent, opts);
2204
+ latestMyThreadsRootEvent = rootEvent;
2205
+ }
2206
+ }
2207
+
2208
+ this.processThreadRoots(threadRoots, true);
2209
+
2210
+ this.client.decryptEventIfNeeded(threadRoots[threadRoots.length - 1]);
2211
+ if (latestMyThreadsRootEvent) {
2212
+ this.client.decryptEventIfNeeded(latestMyThreadsRootEvent);
2213
+ }
2214
+ }
2215
+
2216
+ this.on(ThreadEvent.NewReply, this.onThreadReply);
2217
+ this.on(ThreadEvent.Update, this.onThreadUpdate);
2218
+ this.on(ThreadEvent.Delete, this.onThreadDelete);
2219
+ this.threadsReady = true;
2220
+ }
2221
+
2222
+ /**
2223
+ * Process a list of poll events.
2224
+ *
2225
+ * @param events - List of events
2226
+ */
2227
+ public async processPollEvents(events: BriijEvent[]): Promise<void> {
2228
+ for (const event of events) {
2229
+ try {
2230
+ // Continue if the event is a clear text, non-poll event.
2231
+ if (!event.isEncrypted() && !isPollEvent(event)) continue;
2232
+
2233
+ /**
2234
+ * Try to decrypt the event. Promise resolution does not guarantee a successful decryption.
2235
+ * Retry is handled in {@link processPollEvent}.
2236
+ */
2237
+ await this.client.decryptEventIfNeeded(event);
2238
+ this.processPollEvent(event);
2239
+ } catch (err) {
2240
+ logger.warn("Error processing poll event", event.getId(), err);
2241
+ }
2242
+ }
2243
+ }
2244
+
2245
+ /**
2246
+ * Processes poll events:
2247
+ * If the event has a decryption failure, it will listen for decryption and tries again.
2248
+ * If it is a poll start event (`m.poll.start`),
2249
+ * it creates and stores a Poll model and emits a PollEvent.New event.
2250
+ * If the event is related to a poll, it will add it to the poll.
2251
+ * Noop for other cases.
2252
+ *
2253
+ * @param event - Event that could be a poll event
2254
+ */
2255
+ private async processPollEvent(event: BriijEvent): Promise<void> {
2256
+ if (event.isDecryptionFailure()) {
2257
+ event.once(BriijEventEvent.Decrypted, (maybeDecryptedEvent: BriijEvent) => {
2258
+ this.processPollEvent(maybeDecryptedEvent);
2259
+ });
2260
+ return;
2261
+ }
2262
+
2263
+ if (M_POLL_START.matches(event.getType())) {
2264
+ try {
2265
+ const poll = new Poll(event, this.client, this);
2266
+ this.polls.set(event.getId()!, poll);
2267
+ this.emit(PollEvent.New, poll);
2268
+
2269
+ // remove the poll when redacted
2270
+ event.once(BriijEventEvent.BeforeRedaction, (redactedEvent: BriijEvent) => {
2271
+ this.polls.delete(redactedEvent.getId()!);
2272
+ });
2273
+ } catch {}
2274
+ // poll creation can fail for malformed poll start events
2275
+ return;
2276
+ }
2277
+
2278
+ const relationEventId = event.relationEventId;
2279
+
2280
+ if (relationEventId && this.polls.has(relationEventId)) {
2281
+ const poll = this.polls.get(relationEventId);
2282
+ poll?.onNewRelation(event);
2283
+ }
2284
+ }
2285
+
2286
+ /**
2287
+ * Fetch a single page of threadlist messages for the specific thread filter
2288
+ * @internal
2289
+ */
2290
+ private async fetchRoomThreadList(filter?: ThreadFilterType): Promise<void> {
2291
+ if (!this.client.supportsThreads()) return;
2292
+ if (this.threadsTimelineSets.length === 0) return;
2293
+
2294
+ const timelineSet = filter === ThreadFilterType.My ? this.threadsTimelineSets[1] : this.threadsTimelineSets[0];
2295
+
2296
+ const { chunk: events, end } = await this.client.createThreadListMessagesRequest(
2297
+ this.roomId,
2298
+ null,
2299
+ undefined,
2300
+ Direction.Backward,
2301
+ timelineSet.threadListType,
2302
+ timelineSet.getFilter(),
2303
+ );
2304
+
2305
+ timelineSet.getLiveTimeline().setPaginationToken(end ?? null, Direction.Backward);
2306
+
2307
+ if (!events.length) return;
2308
+
2309
+ const matrixEvents = events.map(this.client.getEventMapper());
2310
+ this.processThreadRoots(matrixEvents, true);
2311
+ const roomState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);
2312
+ for (const rootEvent of matrixEvents) {
2313
+ timelineSet.addLiveEvent(rootEvent, {
2314
+ duplicateStrategy: DuplicateStrategy.Replace,
2315
+ fromCache: false,
2316
+ roomState,
2317
+ addToState: false,
2318
+ });
2319
+ }
2320
+ }
2321
+
2322
+ private onThreadUpdate(thread: Thread): void {
2323
+ this.updateThreadRootEvents(thread, false, false);
2324
+ }
2325
+
2326
+ private onThreadReply(thread: Thread): void {
2327
+ this.updateThreadRootEvents(thread, false, true);
2328
+ }
2329
+
2330
+ private onThreadDelete(thread: Thread): void {
2331
+ this.threads.delete(thread.id);
2332
+
2333
+ const timeline = this.getTimelineForEvent(thread.id);
2334
+ const roomEvent = timeline?.getEvents()?.find((it) => it.getId() === thread.id);
2335
+ if (roomEvent) {
2336
+ thread.clearEventMetadata(roomEvent);
2337
+ } else {
2338
+ logger.debug("onThreadDelete: Could not find root event in room timeline");
2339
+ }
2340
+ for (const timelineSet of this.threadsTimelineSets) {
2341
+ timelineSet.removeEvent(thread.id);
2342
+ }
2343
+ }
2344
+
2345
+ /**
2346
+ * Forget the timelineSet for this room with the given filter
2347
+ *
2348
+ * @param filter - the filter whose timelineSet is to be forgotten
2349
+ */
2350
+ public removeFilteredTimelineSet(filter: Filter): void {
2351
+ const timelineSet = this.filteredTimelineSets[filter.filterId!];
2352
+ delete this.filteredTimelineSets[filter.filterId!];
2353
+ const i = this.timelineSets.indexOf(timelineSet);
2354
+ if (i > -1) {
2355
+ this.timelineSets.splice(i, 1);
2356
+ }
2357
+ }
2358
+
2359
+ /**
2360
+ * Determine which timeline(s) a given event should live in
2361
+ * Thread roots live in both the main timeline and their corresponding thread timeline
2362
+ * Relations, redactions, replies to thread relation events live only in the thread timeline
2363
+ * Relations (other than m.thread), redactions, replies to a thread root live only in the main timeline
2364
+ * Relations, redactions, replies where the parent cannot be found live in no timelines but should be aggregated regardless.
2365
+ * Otherwise, the event lives in the main timeline only.
2366
+ *
2367
+ * Note: when a redaction is applied, the redacted event, events relating
2368
+ * to it, and the redaction event itself, will all move to the main thread.
2369
+ * This method classifies them as inside the thread of the redacted event.
2370
+ * They are moved later as part of makeRedacted.
2371
+ * This will change if MSC3389 is merged.
2372
+ */
2373
+ public eventShouldLiveIn(
2374
+ event: BriijEvent,
2375
+ events?: BriijEvent[],
2376
+ roots?: Set<string>,
2377
+ ): {
2378
+ shouldLiveInRoom: boolean;
2379
+ shouldLiveInThread: boolean;
2380
+ threadId?: string;
2381
+ } {
2382
+ if (!this.client?.supportsThreads()) {
2383
+ return {
2384
+ shouldLiveInRoom: true,
2385
+ shouldLiveInThread: false,
2386
+ };
2387
+ }
2388
+
2389
+ // A thread root is the only event shown in both timelines
2390
+ if (event.isThreadRoot || roots?.has(event.getId()!)) {
2391
+ return {
2392
+ shouldLiveInRoom: true,
2393
+ shouldLiveInThread: true,
2394
+ threadId: event.getId(),
2395
+ };
2396
+ }
2397
+
2398
+ const isThreadRelation = event.isRelation(THREAD_RELATION_TYPE.name);
2399
+ const parentEventId = event.getAssociatedId();
2400
+ const threadRootId = event.threadRootId;
2401
+
2402
+ // Where the parent is the thread root and this is a non-thread relation this should live only in the main timeline
2403
+ if (!!parentEventId && !isThreadRelation && (threadRootId === parentEventId || roots?.has(parentEventId!))) {
2404
+ return {
2405
+ shouldLiveInRoom: true,
2406
+ shouldLiveInThread: false,
2407
+ };
2408
+ }
2409
+
2410
+ let parentEvent: BriijEvent | undefined;
2411
+ if (parentEventId) {
2412
+ parentEvent = this.findEventById(parentEventId) ?? events?.find((e) => e.getId() === parentEventId);
2413
+ }
2414
+
2415
+ // Treat non-thread-relations, redactions, and replies as extensions of their parents so evaluate parentEvent instead
2416
+ if (parentEvent && !isThreadRelation) {
2417
+ return this.eventShouldLiveIn(parentEvent, events, roots);
2418
+ }
2419
+
2420
+ // A thread relation (1st and 2nd order) is always only shown in a thread
2421
+ if (threadRootId != undefined) {
2422
+ return {
2423
+ shouldLiveInRoom: false,
2424
+ shouldLiveInThread: true,
2425
+ threadId: threadRootId,
2426
+ };
2427
+ }
2428
+
2429
+ // Due to replies not being typical relations and being used as fallbacks for threads relations
2430
+ // If we bypass the if case above then we know we are not a thread, so if we are still a reply
2431
+ // then we know that we must be in the main timeline. Same goes if we have no associated parent event.
2432
+ if (!parentEventId || !!event.replyEventId) {
2433
+ return {
2434
+ shouldLiveInRoom: true,
2435
+ shouldLiveInThread: false,
2436
+ };
2437
+ }
2438
+
2439
+ // We've exhausted all scenarios,
2440
+ // we cannot assume that it lives in the main timeline as this may be a relation for an unknown thread
2441
+ // adding the event in the wrong timeline causes stuck notifications and can break ability to send read receipts
2442
+ return {
2443
+ shouldLiveInRoom: false,
2444
+ shouldLiveInThread: false,
2445
+ };
2446
+ }
2447
+
2448
+ public findThreadForEvent(event?: BriijEvent): Thread | null {
2449
+ if (!event) return null;
2450
+
2451
+ const { threadId } = this.eventShouldLiveIn(event);
2452
+ return threadId ? this.getThread(threadId) : null;
2453
+ }
2454
+
2455
+ private addThreadedEvents(threadId: string, events: BriijEvent[], toStartOfTimeline = false): void {
2456
+ const thread = this.getThread(threadId);
2457
+ if (thread) {
2458
+ thread.addEvents(events, toStartOfTimeline);
2459
+ } else {
2460
+ const rootEvent = this.findEventById(threadId) ?? events.find((e) => e.getId() === threadId);
2461
+ this.createThread(threadId, rootEvent, events, toStartOfTimeline);
2462
+ }
2463
+ }
2464
+
2465
+ /**
2466
+ * Adds events to a thread's timeline. Will fire "Thread.update"
2467
+ */
2468
+ public processThreadedEvents(events: BriijEvent[], toStartOfTimeline: boolean): void {
2469
+ events.forEach(this.tryApplyRedaction);
2470
+
2471
+ const eventsByThread: { [threadId: string]: BriijEvent[] } = {};
2472
+ for (const event of events) {
2473
+ const { threadId, shouldLiveInThread } = this.eventShouldLiveIn(event);
2474
+ if (shouldLiveInThread && !eventsByThread[threadId!]) {
2475
+ eventsByThread[threadId!] = [];
2476
+ }
2477
+ eventsByThread[threadId!]?.push(event);
2478
+ }
2479
+
2480
+ Object.entries(eventsByThread).map(([threadId, threadEvents]) =>
2481
+ this.addThreadedEvents(threadId, threadEvents, toStartOfTimeline),
2482
+ );
2483
+ }
2484
+
2485
+ private updateThreadRootEvents = (thread: Thread, toStartOfTimeline: boolean, recreateEvent: boolean): void => {
2486
+ if (thread.length) {
2487
+ this.updateThreadRootEvent(this.threadsTimelineSets?.[0], thread, toStartOfTimeline, recreateEvent);
2488
+ if (thread.hasCurrentUserParticipated) {
2489
+ this.updateThreadRootEvent(this.threadsTimelineSets?.[1], thread, toStartOfTimeline, recreateEvent);
2490
+ }
2491
+ }
2492
+ };
2493
+
2494
+ private updateThreadRootEvent = (
2495
+ timelineSet: EventTimelineSet | undefined,
2496
+ thread: Thread,
2497
+ toStartOfTimeline: boolean,
2498
+ recreateEvent: boolean,
2499
+ ): void => {
2500
+ if (timelineSet && thread.rootEvent) {
2501
+ if (recreateEvent) {
2502
+ timelineSet.removeEvent(thread.id);
2503
+ }
2504
+ if (Thread.hasServerSideSupport) {
2505
+ timelineSet.addLiveEvent(thread.rootEvent, {
2506
+ duplicateStrategy: DuplicateStrategy.Replace,
2507
+ fromCache: false,
2508
+ roomState: this.currentState,
2509
+ addToState: false,
2510
+ });
2511
+ } else {
2512
+ timelineSet.addEventToTimeline(thread.rootEvent, timelineSet.getLiveTimeline(), {
2513
+ toStartOfTimeline,
2514
+ addToState: false,
2515
+ });
2516
+ }
2517
+ }
2518
+ };
2519
+
2520
+ public createThread(
2521
+ threadId: string,
2522
+ rootEvent: BriijEvent | undefined,
2523
+ events: BriijEvent[] = [],
2524
+ toStartOfTimeline: boolean,
2525
+ ): Thread {
2526
+ if (this.threads.has(threadId)) {
2527
+ return this.threads.get(threadId)!;
2528
+ }
2529
+
2530
+ if (rootEvent) {
2531
+ const relatedEvents = this.relations.getAllChildEventsForEvent(rootEvent.getId()!);
2532
+ if (relatedEvents?.length) {
2533
+ // Include all relations of the root event, given it'll be visible in both timelines,
2534
+ // except `m.replace` as that will already be applied atop the event using `BriijEvent::makeReplaced`
2535
+ events = events.concat(relatedEvents.filter((e) => !e.isRelation(RelationType.Replace)));
2536
+ }
2537
+ }
2538
+
2539
+ const thread = new Thread(threadId, rootEvent, {
2540
+ room: this,
2541
+ client: this.client,
2542
+ pendingEventOrdering: this.opts.pendingEventOrdering,
2543
+ receipts: this.cachedThreadReadReceipts.get(threadId) ?? [],
2544
+ });
2545
+
2546
+ // Add the re-emitter before we start adding events to the thread so we don't miss events
2547
+ this.reEmitter.reEmit(thread, [
2548
+ ThreadEvent.Delete,
2549
+ ThreadEvent.Update,
2550
+ ThreadEvent.NewReply,
2551
+ RoomEvent.Timeline,
2552
+ RoomEvent.TimelineReset,
2553
+ ]);
2554
+
2555
+ // All read receipts should now come down from sync, we do not need to keep
2556
+ // a reference to the cached receipts anymore.
2557
+ this.cachedThreadReadReceipts.delete(threadId);
2558
+
2559
+ // If we managed to create a thread and figure out its `id` then we can use it
2560
+ // This has to happen before thread.addEvents, because that adds events to the eventtimeline, and the
2561
+ // eventtimeline sometimes looks up thread information via the room.
2562
+ this.threads.set(thread.id, thread);
2563
+
2564
+ // This is necessary to be able to jump to events in threads:
2565
+ // If we jump to an event in a thread where neither the event, nor the root,
2566
+ // nor any thread event are loaded yet, we'll load the event as well as the thread root, create the thread,
2567
+ // and pass the event through this.
2568
+ thread.addEvents(events, false);
2569
+
2570
+ // We need to update the thread root events, but the thread may not be ready yet.
2571
+ // If it isn't, it will fire ThreadEvent.Update when it is and we'll call updateThreadRootEvents then.
2572
+ if (this.threadsReady && thread.initialEventsFetched) {
2573
+ this.updateThreadRootEvents(thread, toStartOfTimeline, false);
2574
+ }
2575
+ this.emit(ThreadEvent.New, thread, toStartOfTimeline);
2576
+
2577
+ return thread;
2578
+ }
2579
+
2580
+ /**
2581
+ * Applies an event as a redaction of another event, regardless of whether the redacting
2582
+ * event is actually a redaction.
2583
+ *
2584
+ * Callers should use tryApplyRedaction instead.
2585
+ *
2586
+ * @param redactionEvent The event which redacts an event.
2587
+ * @param redactedEvent The event being redacted.
2588
+ * @private
2589
+ */
2590
+ private applyEventAsRedaction(redactionEvent: BriijEvent, redactedEvent: BriijEvent): void {
2591
+ const threadRootId = redactedEvent.threadRootId;
2592
+ redactedEvent.makeRedacted(redactionEvent, this);
2593
+
2594
+ // If this is in the current state, replace it with the redacted version
2595
+ if (redactedEvent.isState()) {
2596
+ const currentStateEvent = this.currentState.getStateEvents(
2597
+ redactedEvent.getType(),
2598
+ redactedEvent.getStateKey()!,
2599
+ );
2600
+ if (currentStateEvent?.getId() === redactedEvent.getId()) {
2601
+ this.currentState.setStateEvents([redactedEvent]);
2602
+ }
2603
+ }
2604
+
2605
+ this.emit(RoomEvent.Redaction, redactionEvent, this, threadRootId);
2606
+
2607
+ // TODO: we stash user displaynames (among other things) in
2608
+ // RoomMember objects which are then attached to other events
2609
+ // (in the sender and target fields). We should get those
2610
+ // RoomMember objects to update themselves when the events that
2611
+ // they are based on are changed.
2612
+
2613
+ // Remove any visibility change on this event.
2614
+ this.visibilityEvents.delete(redactedEvent.getId()!);
2615
+
2616
+ // If this event is a visibility change event, remove it from the
2617
+ // list of visibility changes and update any event affected by it.
2618
+ if (redactedEvent.isVisibilityEvent()) {
2619
+ this.redactVisibilityChangeEvent(redactionEvent);
2620
+ }
2621
+ }
2622
+
2623
+ private tryApplyRedaction = (event: BriijEvent): void => {
2624
+ // FIXME: apply redactions to notification list
2625
+
2626
+ // NB: We continue to add the redaction event to the timeline at the
2627
+ // end of this function so clients can say "so and so redacted an event"
2628
+ // if they wish to. Also this may be needed to trigger an update.
2629
+
2630
+ if (event.isRedaction()) {
2631
+ const redactId = event.event.redacts;
2632
+
2633
+ // if we know about this event, redact its contents now.
2634
+ const redactedEvent = redactId ? this.findEventById(redactId) : undefined;
2635
+ if (redactId) {
2636
+ try {
2637
+ this.stickyEvents.handleRedaction(redactedEvent || redactId);
2638
+ } catch (ex) {
2639
+ // Non-critical failure, but we should warn.
2640
+ logger.error("Failed to handle redaction for sticky event", ex);
2641
+ }
2642
+ }
2643
+ if (redactedEvent) {
2644
+ this.applyEventAsRedaction(event, redactedEvent);
2645
+ }
2646
+ } else if (event.getType() === EventType.RoomMember) {
2647
+ const membership = event.getContent()["membership"];
2648
+ if (
2649
+ membership !== KnownMembership.Ban &&
2650
+ !(membership === KnownMembership.Leave && event.getStateKey() !== event.getSender())
2651
+ ) {
2652
+ // Not a ban or kick, therefore not a membership event we care about here.
2653
+ return;
2654
+ }
2655
+ const redactEvents = event.getContent()["org.matrix.msc4293.redact_events"];
2656
+ if (redactEvents !== true) {
2657
+ // Invalid or not set - nothing to redact.
2658
+ return;
2659
+ }
2660
+ const state = this.getLiveTimeline().getState(Direction.Forward)!;
2661
+ if (!state.maySendRedactionForEvent(event, event.getSender()!)) {
2662
+ // If the sender can't redact the membership event, then they won't be able to
2663
+ // redact any of the target's events either, so skip.
2664
+ return;
2665
+ }
2666
+
2667
+ // The redaction is possible, so let's find all the events and apply it.
2668
+ const events = this.getTimelineSets()
2669
+ .map((s) => s.getTimelines())
2670
+ .reduce((p, c) => {
2671
+ p.push(...c);
2672
+ return p;
2673
+ }, [])
2674
+ .map((t) => t.getEvents().filter((e) => e.getSender() === event.getStateKey()))
2675
+ .reduce((p, c) => {
2676
+ p.push(...c);
2677
+ return c;
2678
+ }, []);
2679
+ for (const toRedact of events) {
2680
+ this.applyEventAsRedaction(event, toRedact);
2681
+ }
2682
+ }
2683
+ };
2684
+
2685
+ private processLiveEvent(event: BriijEvent): void {
2686
+ this.tryApplyRedaction(event);
2687
+
2688
+ // Implement MSC3531: hiding messages.
2689
+ if (event.isVisibilityEvent()) {
2690
+ // This event changes the visibility of another event, record
2691
+ // the visibility change, inform clients if necessary.
2692
+ this.applyNewVisibilityEvent(event);
2693
+ }
2694
+ // If any pending visibility change is waiting for this (older) event,
2695
+ this.applyPendingVisibilityEvents(event);
2696
+
2697
+ // Sliding Sync modifications:
2698
+ // The proxy cannot guarantee every sent event will have a transaction_id field, so we need
2699
+ // to check the event ID against the list of pending events if there is no transaction ID
2700
+ // field. Only do this for events sent by us though as it's potentially expensive to loop
2701
+ // the pending events map.
2702
+ const txnId = event.getUnsigned().transaction_id;
2703
+ if (!txnId && event.getSender() === this.myUserId) {
2704
+ // check the txn map for a matching event ID
2705
+ for (const [tid, localEvent] of this.txnToEvent) {
2706
+ if (localEvent.getId() === event.getId()) {
2707
+ logger.debug("processLiveEvent: found sent event without txn ID: ", tid, event.getId());
2708
+ // update the unsigned field so we can re-use the same codepaths
2709
+ const unsigned = event.getUnsigned();
2710
+ unsigned.transaction_id = tid;
2711
+ event.setUnsigned(unsigned);
2712
+ break;
2713
+ }
2714
+ }
2715
+ }
2716
+ }
2717
+
2718
+ /**
2719
+ * Add an event to the end of this room's live timelines. Will fire
2720
+ * "Room.timeline".
2721
+ *
2722
+ * @param event - Event to be added
2723
+ * @param addLiveEventOptions - addLiveEvent options
2724
+ * @internal
2725
+ *
2726
+ * @remarks
2727
+ * Fires {@link RoomEvent.Timeline}
2728
+ */
2729
+ private addLiveEvent(event: BriijEvent, addLiveEventOptions: IAddLiveEventOptions): void {
2730
+ const { duplicateStrategy, timelineWasEmpty, fromCache, addToState } = addLiveEventOptions;
2731
+
2732
+ // add to our timeline sets
2733
+ for (const timelineSet of this.timelineSets) {
2734
+ timelineSet.addLiveEvent(event, {
2735
+ duplicateStrategy,
2736
+ fromCache,
2737
+ timelineWasEmpty,
2738
+ addToState,
2739
+ });
2740
+ }
2741
+
2742
+ // synthesize and inject implicit read receipts
2743
+ // Done after adding the event because otherwise the app would get a read receipt
2744
+ // pointing to an event that wasn't yet in the timeline
2745
+ // Don't synthesize RR for m.room.redaction as this causes the RR to go missing.
2746
+ if (event.sender && event.getType() !== EventType.RoomRedaction) {
2747
+ this.addReceipt(synthesizeReceipt(event.sender.userId, event, ReceiptType.Read), true);
2748
+
2749
+ // Any live events from a user could be taken as implicit
2750
+ // presence information: evidence that they are currently active.
2751
+ // ...except in a world where we use 'user.currentlyActive' to reduce
2752
+ // presence spam, this isn't very useful - we'll get a transition when
2753
+ // they are no longer currently active anyway. So don't bother to
2754
+ // reset the lastActiveAgo and lastPresenceTs from the RoomState's user.
2755
+ }
2756
+ }
2757
+
2758
+ /**
2759
+ * Add a pending outgoing event to this room.
2760
+ *
2761
+ * <p>The event is added to either the pendingEventList, or the live timeline,
2762
+ * depending on the setting of opts.pendingEventOrdering.
2763
+ *
2764
+ * <p>This is an internal method, intended for use by BriijClient.
2765
+ *
2766
+ * @param event - The event to add.
2767
+ *
2768
+ * @param txnId - Transaction id for this outgoing event
2769
+ *
2770
+ * @throws if the event doesn't have status SENDING, or we aren't given a
2771
+ * unique transaction id.
2772
+ *
2773
+ * @remarks
2774
+ * Fires {@link RoomEvent.LocalEchoUpdated}
2775
+ */
2776
+ public addPendingEvent(event: BriijEvent, txnId: string): void {
2777
+ if (event.status !== EventStatus.SENDING && event.status !== EventStatus.NOT_SENT) {
2778
+ throw new Error("addPendingEvent called on an event with status " + event.status);
2779
+ }
2780
+
2781
+ if (this.txnToEvent.get(txnId)) {
2782
+ throw new Error("addPendingEvent called on an event with known txnId " + txnId);
2783
+ }
2784
+
2785
+ // call setEventMetadata to set up event.sender etc
2786
+ // as event is shared over all timelineSets, we set up its metadata based
2787
+ // on the unfiltered timelineSet.
2788
+ EventTimeline.setEventMetadata(event, this.getLiveTimeline().getState(EventTimeline.FORWARDS)!, false);
2789
+
2790
+ this.txnToEvent.set(txnId, event);
2791
+ if (this.pendingEventList) {
2792
+ if (this.pendingEventList.some((e) => e.status === EventStatus.NOT_SENT)) {
2793
+ logger.warn("Setting event as NOT_SENT due to messages in the same state");
2794
+ event.setStatus(EventStatus.NOT_SENT);
2795
+ }
2796
+ this.pendingEventList.push(event);
2797
+ this.savePendingEvents();
2798
+ if (event.isRelation()) {
2799
+ // For pending events, add them to the relations collection immediately.
2800
+ // (The alternate case below already covers this as part of adding to
2801
+ // the timeline set.)
2802
+ this.aggregateNonLiveRelation(event);
2803
+ }
2804
+
2805
+ if (event.isRedaction()) {
2806
+ const redactId = event.event.redacts;
2807
+ let redactedEvent = this.pendingEventList.find((e) => e.getId() === redactId);
2808
+ if (!redactedEvent && redactId) {
2809
+ redactedEvent = this.findEventById(redactId);
2810
+ }
2811
+ if (redactedEvent) {
2812
+ redactedEvent.markLocallyRedacted(event);
2813
+ this.emit(RoomEvent.Redaction, event, this, redactedEvent.threadRootId);
2814
+ }
2815
+ }
2816
+ } else {
2817
+ for (const timelineSet of this.timelineSets) {
2818
+ if (timelineSet.getFilter()) {
2819
+ if (timelineSet.getFilter()!.filterRoomTimeline([event]).length) {
2820
+ timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {
2821
+ toStartOfTimeline: false,
2822
+ addToState: false, // We don't support localEcho of state events yet
2823
+ });
2824
+ }
2825
+ } else {
2826
+ timelineSet.addEventToTimeline(event, timelineSet.getLiveTimeline(), {
2827
+ toStartOfTimeline: false,
2828
+ addToState: false, // We don't support localEcho of state events yet
2829
+ });
2830
+ }
2831
+ }
2832
+ }
2833
+
2834
+ this.emit(RoomEvent.LocalEchoUpdated, event, this);
2835
+ }
2836
+
2837
+ /**
2838
+ * Persists all pending events to local storage
2839
+ *
2840
+ * If the current room is encrypted only encrypted events will be persisted
2841
+ * all messages that are not yet encrypted will be discarded
2842
+ *
2843
+ * This is because the flow of EVENT_STATUS transition is
2844
+ * `queued => sending => encrypting => sending => sent`
2845
+ *
2846
+ * Steps 3 and 4 are skipped for unencrypted room.
2847
+ * It is better to discard an unencrypted message rather than persisting
2848
+ * it locally for everyone to read
2849
+ */
2850
+ private savePendingEvents(): void {
2851
+ if (this.pendingEventList) {
2852
+ const pendingEvents = this.pendingEventList
2853
+ .map((event) => {
2854
+ return {
2855
+ ...event.event,
2856
+ txn_id: event.getTxnId(),
2857
+ };
2858
+ })
2859
+ .filter((event) => {
2860
+ // Filter out the unencrypted messages if the room is encrypted
2861
+ const isEventEncrypted = event.type === EventType.RoomMessageEncrypted;
2862
+ const isRoomEncrypted = this.hasEncryptionStateEvent();
2863
+ return isEventEncrypted || !isRoomEncrypted;
2864
+ });
2865
+
2866
+ this.client.store.setPendingEvents(this.roomId, pendingEvents);
2867
+ }
2868
+ }
2869
+
2870
+ /**
2871
+ * Used to aggregate the local echo for a relation, and also
2872
+ * for re-applying a relation after it's redaction has been cancelled,
2873
+ * as the local echo for the redaction of the relation would have
2874
+ * un-aggregated the relation. Note that this is different from regular messages,
2875
+ * which are just kept detached for their local echo.
2876
+ *
2877
+ * Also note that live events are aggregated in the live EventTimelineSet.
2878
+ * @param event - the relation event that needs to be aggregated.
2879
+ */
2880
+ private aggregateNonLiveRelation(event: BriijEvent): void {
2881
+ this.relations.aggregateChildEvent(event);
2882
+ }
2883
+
2884
+ public getEventForTxnId(txnId: string): BriijEvent | undefined {
2885
+ return this.txnToEvent.get(txnId);
2886
+ }
2887
+
2888
+ /**
2889
+ * Deal with the echo of a message we sent.
2890
+ *
2891
+ * <p>We move the event to the live timeline if it isn't there already, and
2892
+ * update it.
2893
+ *
2894
+ * @param remoteEvent - The event received from
2895
+ * /sync
2896
+ * @param localEvent - The local echo, which
2897
+ * should be either in the pendingEventList or the timeline.
2898
+ *
2899
+ * @internal
2900
+ *
2901
+ * @remarks
2902
+ * Fires {@link RoomEvent.LocalEchoUpdated}
2903
+ */
2904
+ public handleRemoteEcho(remoteEvent: BriijEvent, localEvent: BriijEvent): void {
2905
+ const oldEventId = localEvent.getId()!;
2906
+ const newEventId = remoteEvent.getId()!;
2907
+ const oldStatus = localEvent.status;
2908
+
2909
+ logger.debug(`Got remote echo for event ${oldEventId} -> ${newEventId} old status ${oldStatus}`);
2910
+
2911
+ // no longer pending
2912
+ this.txnToEvent.delete(remoteEvent.getUnsigned().transaction_id!);
2913
+
2914
+ // if it's in the pending list, remove it
2915
+ if (this.pendingEventList) {
2916
+ this.removePendingEvent(oldEventId);
2917
+ }
2918
+
2919
+ // replace the event source (this will preserve the plaintext payload if
2920
+ // any, which is good, because we don't want to try decoding it again).
2921
+ localEvent.handleRemoteEcho(remoteEvent.event);
2922
+
2923
+ const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(remoteEvent);
2924
+ const thread = threadId ? this.getThread(threadId) : null;
2925
+ thread?.setEventMetadata(localEvent);
2926
+ thread?.timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);
2927
+
2928
+ if (shouldLiveInRoom) {
2929
+ for (const timelineSet of this.timelineSets) {
2930
+ // if it's already in the timeline, update the timeline map. If it's not, add it.
2931
+ timelineSet.handleRemoteEcho(localEvent, oldEventId, newEventId);
2932
+ }
2933
+ }
2934
+
2935
+ this.emit(RoomEvent.LocalEchoUpdated, localEvent, this, oldEventId, oldStatus);
2936
+ }
2937
+
2938
+ /**
2939
+ * Update the status / event id on a pending event, to reflect its transmission
2940
+ * progress.
2941
+ *
2942
+ * <p>This is an internal method.
2943
+ *
2944
+ * @param event - local echo event
2945
+ * @param newStatus - status to assign
2946
+ * @param newEventId - new event id to assign. Ignored unless newStatus == EventStatus.SENT.
2947
+ *
2948
+ * @remarks
2949
+ * Fires {@link RoomEvent.LocalEchoUpdated}
2950
+ */
2951
+ public updatePendingEvent(event: BriijEvent, newStatus: EventStatus, newEventId?: string): void {
2952
+ logger.log(
2953
+ `setting pendingEvent status to ${newStatus} in ${event.getRoomId()} ` +
2954
+ `event ID ${event.getId()} -> ${newEventId}`,
2955
+ );
2956
+
2957
+ // if the message was sent, we expect an event id
2958
+ if (newStatus == EventStatus.SENT && !newEventId) {
2959
+ throw new Error("updatePendingEvent called with status=SENT, but no new event id");
2960
+ }
2961
+
2962
+ // SENT races against /sync, so we have to special-case it.
2963
+ if (newStatus == EventStatus.SENT) {
2964
+ const timeline = this.getTimelineForEvent(newEventId!);
2965
+ if (timeline) {
2966
+ // we've already received the event via the event stream.
2967
+ // nothing more to do here, assuming the transaction ID was correctly matched.
2968
+ // Let's check that.
2969
+ const remoteEvent = this.findEventById(newEventId!);
2970
+ const remoteTxnId = remoteEvent?.getUnsigned().transaction_id;
2971
+ if (!remoteTxnId && remoteEvent) {
2972
+ // This code path is mostly relevant for the Sliding Sync proxy.
2973
+ // The remote event did not contain a transaction ID, so we did not handle
2974
+ // the remote echo yet. Handle it now.
2975
+ const unsigned = remoteEvent.getUnsigned();
2976
+ unsigned.transaction_id = event.getTxnId();
2977
+ remoteEvent.setUnsigned(unsigned);
2978
+ // the remote event is _already_ in the timeline, so we need to remove it so
2979
+ // we can convert the local event into the final event.
2980
+ this.removeEvent(remoteEvent.getId()!);
2981
+ this.handleRemoteEcho(remoteEvent, event);
2982
+ }
2983
+ return;
2984
+ }
2985
+ }
2986
+
2987
+ const oldStatus = event.status;
2988
+ const oldEventId = event.getId()!;
2989
+
2990
+ if (!oldStatus) {
2991
+ throw new Error("updatePendingEventStatus called on an event which is not a local echo.");
2992
+ }
2993
+
2994
+ const allowed = ALLOWED_TRANSITIONS[oldStatus];
2995
+ if (!allowed?.includes(newStatus)) {
2996
+ throw new Error(`Invalid EventStatus transition ${oldStatus}->${newStatus}`);
2997
+ }
2998
+
2999
+ event.setStatus(newStatus);
3000
+
3001
+ if (newStatus == EventStatus.SENT) {
3002
+ // update the event id
3003
+ event.replaceLocalEventId(newEventId!);
3004
+
3005
+ const { shouldLiveInRoom, threadId } = this.eventShouldLiveIn(event);
3006
+ const thread = threadId ? this.getThread(threadId) : undefined;
3007
+ thread?.setEventMetadata(event);
3008
+ thread?.timelineSet.replaceEventId(oldEventId, newEventId!);
3009
+
3010
+ if (shouldLiveInRoom) {
3011
+ // if the event was already in the timeline (which will be the case if
3012
+ // opts.pendingEventOrdering==chronological), we need to update the
3013
+ // timeline map.
3014
+ for (const timelineSet of this.timelineSets) {
3015
+ timelineSet.replaceEventId(oldEventId, newEventId!);
3016
+ }
3017
+ }
3018
+ } else if (newStatus == EventStatus.CANCELLED) {
3019
+ // remove it from the pending event list, or the timeline.
3020
+ if (this.pendingEventList) {
3021
+ const removedEvent = this.getPendingEvent(oldEventId);
3022
+ this.removePendingEvent(oldEventId);
3023
+ if (removedEvent?.isRedaction()) {
3024
+ this.revertRedactionLocalEcho(removedEvent);
3025
+ }
3026
+ }
3027
+ this.removeEvent(oldEventId);
3028
+ }
3029
+ this.savePendingEvents();
3030
+
3031
+ this.emit(RoomEvent.LocalEchoUpdated, event, this, oldEventId, oldStatus);
3032
+ }
3033
+
3034
+ private revertRedactionLocalEcho(redactionEvent: BriijEvent): void {
3035
+ const redactId = redactionEvent.event.redacts;
3036
+ if (!redactId) {
3037
+ return;
3038
+ }
3039
+ const redactedEvent = this.getUnfilteredTimelineSet().findEventById(redactId);
3040
+ if (redactedEvent) {
3041
+ redactedEvent.unmarkLocallyRedacted();
3042
+ // re-render after undoing redaction
3043
+ this.emit(RoomEvent.RedactionCancelled, redactionEvent, this);
3044
+ // reapply relation now redaction failed
3045
+ if (redactedEvent.isRelation()) {
3046
+ this.aggregateNonLiveRelation(redactedEvent);
3047
+ }
3048
+ }
3049
+ }
3050
+
3051
+ private assertTimelineSetsAreLive(): void {
3052
+ for (let i = 0; i < this.timelineSets.length; i++) {
3053
+ const liveTimeline = this.timelineSets[i].getLiveTimeline();
3054
+ if (liveTimeline.getPaginationToken(EventTimeline.FORWARDS)) {
3055
+ throw new Error(
3056
+ "live timeline " +
3057
+ i +
3058
+ " is no longer live - it has a pagination token " +
3059
+ "(" +
3060
+ liveTimeline.getPaginationToken(EventTimeline.FORWARDS) +
3061
+ ")",
3062
+ );
3063
+ }
3064
+ if (liveTimeline.getNeighbouringTimeline(EventTimeline.FORWARDS)) {
3065
+ throw new Error(`live timeline ${i} is no longer live - it has a neighbouring timeline`);
3066
+ }
3067
+ }
3068
+ }
3069
+
3070
+ /**
3071
+ * Add some events to this room. This can include state events, message
3072
+ * events and typing notifications. These events are treated as "live" so
3073
+ * they will go to the end of the timeline.
3074
+ *
3075
+ * @param events - A list of events to add.
3076
+ * @param addLiveEventOptions - addLiveEvent options
3077
+ * @throws If `duplicateStrategy` is not falsey, 'replace' or 'ignore'.
3078
+ */
3079
+ public async addLiveEvents(events: BriijEvent[], addLiveEventOptions: IAddLiveEventOptions): Promise<void> {
3080
+ const { duplicateStrategy, fromCache, timelineWasEmpty = false, addToState } = addLiveEventOptions;
3081
+ if (duplicateStrategy && ["replace", "ignore"].indexOf(duplicateStrategy) === -1) {
3082
+ throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");
3083
+ }
3084
+
3085
+ // sanity check that the live timeline is still live
3086
+ this.assertTimelineSetsAreLive();
3087
+
3088
+ const threadRoots = this.findThreadRoots(events);
3089
+ const eventsByThread: { [threadId: string]: BriijEvent[] } = {};
3090
+
3091
+ const options: IAddLiveEventOptions = {
3092
+ duplicateStrategy,
3093
+ fromCache,
3094
+ timelineWasEmpty,
3095
+ addToState,
3096
+ };
3097
+
3098
+ // List of extra events to check for being parents of any relations encountered
3099
+ const neighbouringEvents = [...events];
3100
+
3101
+ for (const event of events) {
3102
+ // TODO: We should have a filter to say "only add state event types X Y Z to the timeline".
3103
+ this.processLiveEvent(event);
3104
+
3105
+ if (event.getUnsigned().transaction_id) {
3106
+ const existingEvent = this.txnToEvent.get(event.getUnsigned().transaction_id!);
3107
+ if (existingEvent) {
3108
+ // remote echo of an event we sent earlier
3109
+ this.handleRemoteEcho(event, existingEvent);
3110
+ continue; // we can skip adding the event to the timeline sets, it is already there
3111
+ }
3112
+ }
3113
+
3114
+ let {
3115
+ shouldLiveInRoom,
3116
+ shouldLiveInThread,
3117
+ threadId = "",
3118
+ } = this.eventShouldLiveIn(event, neighbouringEvents, threadRoots);
3119
+
3120
+ if (!shouldLiveInThread && !shouldLiveInRoom && event.isRelation()) {
3121
+ try {
3122
+ const parentEvent = new BriijEvent(
3123
+ await this.client.fetchRoomEvent(this.roomId, event.relationEventId!),
3124
+ );
3125
+ neighbouringEvents.push(parentEvent);
3126
+ if (parentEvent.threadRootId) {
3127
+ threadRoots.add(parentEvent.threadRootId);
3128
+ const unsigned = event.getUnsigned();
3129
+ unsigned[UNSIGNED_THREAD_ID_FIELD.name] = parentEvent.threadRootId;
3130
+ event.setUnsigned(unsigned);
3131
+ }
3132
+
3133
+ ({
3134
+ shouldLiveInRoom,
3135
+ shouldLiveInThread,
3136
+ threadId = "",
3137
+ } = this.eventShouldLiveIn(event, neighbouringEvents, threadRoots));
3138
+ } catch (e) {
3139
+ logger.error("Failed to load parent event of unhandled relation", e);
3140
+ }
3141
+ }
3142
+
3143
+ if (shouldLiveInThread && !eventsByThread[threadId]) {
3144
+ eventsByThread[threadId] = [];
3145
+ }
3146
+ eventsByThread[threadId]?.push(event);
3147
+
3148
+ if (shouldLiveInRoom) {
3149
+ this.addLiveEvent(event, options);
3150
+ } else if (!shouldLiveInThread && event.isRelation()) {
3151
+ this.relations.aggregateChildEvent(event);
3152
+ }
3153
+ }
3154
+
3155
+ Object.entries(eventsByThread).forEach(([threadId, threadEvents]) => {
3156
+ this.addThreadedEvents(threadId, threadEvents, false);
3157
+ });
3158
+ }
3159
+
3160
+ public partitionThreadedEvents(
3161
+ events: BriijEvent[],
3162
+ ): [timelineEvents: BriijEvent[], threadedEvents: BriijEvent[], unknownRelations: BriijEvent[]] {
3163
+ // Indices to the events array, for readability
3164
+ const ROOM = 0;
3165
+ const THREAD = 1;
3166
+ const UNKNOWN_RELATION = 2;
3167
+ if (this.client.supportsThreads()) {
3168
+ const threadRoots = this.findThreadRoots(events);
3169
+ return events.reduce<[BriijEvent[], BriijEvent[], BriijEvent[]]>(
3170
+ (memo, event: BriijEvent) => {
3171
+ const { shouldLiveInRoom, shouldLiveInThread, threadId } = this.eventShouldLiveIn(
3172
+ event,
3173
+ events,
3174
+ threadRoots,
3175
+ );
3176
+
3177
+ if (shouldLiveInRoom) {
3178
+ memo[ROOM].push(event);
3179
+ }
3180
+
3181
+ if (shouldLiveInThread) {
3182
+ event.setThreadId(threadId ?? "");
3183
+ memo[THREAD].push(event);
3184
+ }
3185
+
3186
+ if (!shouldLiveInThread && !shouldLiveInRoom) {
3187
+ memo[UNKNOWN_RELATION].push(event);
3188
+ }
3189
+
3190
+ return memo;
3191
+ },
3192
+ [[], [], []],
3193
+ );
3194
+ } else {
3195
+ // When `threadSupport` is disabled treat all events as timelineEvents
3196
+ return [events as BriijEvent[], [] as BriijEvent[], [] as BriijEvent[]];
3197
+ }
3198
+ }
3199
+
3200
+ /**
3201
+ * Given some events, find the IDs of all the thread roots that are referred to by them.
3202
+ */
3203
+ private findThreadRoots(events: BriijEvent[]): Set<string> {
3204
+ const threadRoots = new Set<string>();
3205
+ for (const event of events) {
3206
+ const threadRootId = event.threadRootId;
3207
+ if (threadRootId != undefined) {
3208
+ threadRoots.add(threadRootId);
3209
+ }
3210
+ }
3211
+ return threadRoots;
3212
+ }
3213
+
3214
+ /**
3215
+ * Add a receipt event to the room.
3216
+ * @param event - The m.receipt event.
3217
+ * @param synthetic - True if this event is implicit.
3218
+ */
3219
+ public addReceipt(event: BriijEvent, synthetic = false): void {
3220
+ const content = event.getContent<ReceiptContent>();
3221
+
3222
+ this.roomReceipts.add(content, synthetic);
3223
+
3224
+ // TODO: delete the following code when it has been replaced by RoomReceipts
3225
+ Object.keys(content).forEach((eventId: string) => {
3226
+ Object.keys(content[eventId]).forEach((receiptType: ReceiptType | string) => {
3227
+ Object.keys(content[eventId][receiptType]).forEach((userId: string) => {
3228
+ const receipt = content[eventId][receiptType][userId] as Receipt;
3229
+ const receiptForMainTimeline = !receipt.thread_id || receipt.thread_id === MAIN_ROOM_TIMELINE;
3230
+ const receiptDestination: Thread | this | undefined = receiptForMainTimeline
3231
+ ? this
3232
+ : this.threads.get(receipt.thread_id ?? "");
3233
+
3234
+ if (receiptDestination) {
3235
+ receiptDestination.addReceiptToStructure(
3236
+ eventId,
3237
+ receiptType as ReceiptType,
3238
+ userId,
3239
+ receipt,
3240
+ synthetic,
3241
+ );
3242
+
3243
+ // If the read receipt sent for the logged in user matches
3244
+ // the last event of the live timeline, then we know for a fact
3245
+ // that the user has read that message, so we can mark the room
3246
+ // as read and not wait for the remote echo from synapse.
3247
+ //
3248
+ // This needs to be done after the initial sync as we do not want this
3249
+ // logic to run whilst the room is being initialised
3250
+ //
3251
+ // We only do this for non-synthetic receipts, because
3252
+ // our intention is to do this when the user really did
3253
+ // just read a message, not when we are e.g. receiving
3254
+ // an event during the sync. More explanation at:
3255
+ // https://github.com/matrix-org/matrix-js-sdk/issues/3684
3256
+ if (!synthetic && this.client.isInitialSyncComplete() && userId === this.client.getUserId()) {
3257
+ const lastEvent = receiptDestination.timeline[receiptDestination.timeline.length - 1];
3258
+ if (lastEvent && eventId === lastEvent.getId() && userId === lastEvent.getSender()) {
3259
+ receiptDestination.setUnread(NotificationCountType.Total, 0);
3260
+ receiptDestination.setUnread(NotificationCountType.Highlight, 0);
3261
+ }
3262
+ }
3263
+ } else {
3264
+ // The thread does not exist locally, keep the read receipt
3265
+ // in a cache locally, and re-apply the `addReceipt` logic
3266
+ // when the thread is created
3267
+ this.cachedThreadReadReceipts.set(receipt.thread_id!, [
3268
+ ...(this.cachedThreadReadReceipts.get(receipt.thread_id!) ?? []),
3269
+ { eventId, receiptType, userId, receipt, synthetic },
3270
+ ]);
3271
+ }
3272
+
3273
+ const me = this.client.getUserId();
3274
+ // Track the time of the current user's oldest threaded receipt in the room.
3275
+ if (userId === me && !receiptForMainTimeline && receipt.ts < this.oldestThreadedReceiptTs) {
3276
+ this.oldestThreadedReceiptTs = receipt.ts;
3277
+ }
3278
+
3279
+ // Track each user's unthreaded read receipt.
3280
+ if (!receipt.thread_id && receipt.ts > (this.unthreadedReceipts.get(userId)?.ts ?? 0)) {
3281
+ this.unthreadedReceipts.set(userId, receipt);
3282
+ }
3283
+ });
3284
+ });
3285
+ });
3286
+ // End of code to delete when replaced by RoomReceipts
3287
+
3288
+ // send events after we've regenerated the structure & cache, otherwise things that
3289
+ // listened for the event would read stale data.
3290
+ this.emit(RoomEvent.Receipt, event, this);
3291
+ }
3292
+
3293
+ /**
3294
+ * Adds/handles ephemeral events such as typing notifications and read receipts.
3295
+ * @param events - A list of events to process
3296
+ */
3297
+ public addEphemeralEvents(events: BriijEvent[]): void {
3298
+ for (const event of events) {
3299
+ if (event.getType() === EventType.Typing) {
3300
+ this.currentState.setTypingEvent(event);
3301
+ } else if (event.getType() === EventType.Receipt) {
3302
+ this.addReceipt(event);
3303
+ } // else ignore - life is too short for us to care about these events
3304
+ }
3305
+ }
3306
+
3307
+ /**
3308
+ * Removes events from this room.
3309
+ * @param eventIds - A list of eventIds to remove.
3310
+ */
3311
+ public removeEvents(eventIds: string[]): void {
3312
+ for (const eventId of eventIds) {
3313
+ this.removeEvent(eventId);
3314
+ }
3315
+ }
3316
+
3317
+ /**
3318
+ * Removes a single event from this room.
3319
+ *
3320
+ * @param eventId - The id of the event to remove
3321
+ *
3322
+ * @returns true if the event was removed from any of the room's timeline sets
3323
+ */
3324
+ public removeEvent(eventId: string): boolean {
3325
+ let removedAny = false;
3326
+ for (const timelineSet of this.timelineSets) {
3327
+ const removed = timelineSet.removeEvent(eventId);
3328
+ if (removed) {
3329
+ if (removed.isRedaction()) {
3330
+ this.revertRedactionLocalEcho(removed);
3331
+ }
3332
+ removedAny = true;
3333
+ }
3334
+ }
3335
+ return removedAny;
3336
+ }
3337
+
3338
+ /**
3339
+ * Recalculate various aspects of the room, including the room name and
3340
+ * room summary. Call this any time the room's current state is modified.
3341
+ * May fire "Room.name" if the room name is updated.
3342
+ *
3343
+ * @remarks
3344
+ * Fires {@link RoomEvent.Name}
3345
+ */
3346
+ public recalculate(): void {
3347
+ // set fake stripped state events if this is an invite room so logic remains
3348
+ // consistent elsewhere.
3349
+ const membershipEvent = this.currentState.getStateEvents(EventType.RoomMember, this.myUserId);
3350
+ if (membershipEvent) {
3351
+ const membership = membershipEvent.getContent().membership;
3352
+ this.updateMyMembership(membership!);
3353
+
3354
+ if (membership === KnownMembership.Invite) {
3355
+ const strippedStateEvents = membershipEvent.getUnsigned().invite_room_state || [];
3356
+ strippedStateEvents.forEach((strippedEvent) => {
3357
+ const existingEvent = this.currentState.getStateEvents(strippedEvent.type, strippedEvent.state_key);
3358
+ if (!existingEvent) {
3359
+ // set the fake stripped event instead
3360
+ this.currentState.setStateEvents([
3361
+ new BriijEvent({
3362
+ type: strippedEvent.type,
3363
+ state_key: strippedEvent.state_key,
3364
+ content: strippedEvent.content,
3365
+ event_id: "$fake" + Date.now(),
3366
+ room_id: this.roomId,
3367
+ sender: this.myUserId, // technically a lie
3368
+ }),
3369
+ ]);
3370
+ }
3371
+ });
3372
+ }
3373
+ }
3374
+
3375
+ const oldName = this.name;
3376
+ this.name = this.calculateRoomName(this.myUserId);
3377
+ this.normalizedName = normalize(this.name);
3378
+ this.summary = new RoomSummary(this.roomId, {
3379
+ title: this.name,
3380
+ });
3381
+
3382
+ if (oldName !== this.name) {
3383
+ this.emit(RoomEvent.Name, this);
3384
+ }
3385
+ }
3386
+
3387
+ /**
3388
+ * Update the room-tag event for the room. The previous one is overwritten.
3389
+ * @param event - the m.tag event
3390
+ */
3391
+ public addTags(event: BriijEvent): void {
3392
+ // event content looks like:
3393
+ // content: {
3394
+ // tags: {
3395
+ // $tagName: { $metadata: $value },
3396
+ // $tagName: { $metadata: $value },
3397
+ // }
3398
+ // }
3399
+
3400
+ // XXX: do we need to deep copy here?
3401
+ this.tags = event.getContent().tags || {};
3402
+
3403
+ // XXX: we could do a deep-comparison to see if the tags have really
3404
+ // changed - but do we want to bother?
3405
+ this.emit(RoomEvent.Tags, event, this);
3406
+ }
3407
+
3408
+ /**
3409
+ * Update the account_data events for this room, overwriting events of the same type.
3410
+ * @param events - an array of account_data events to add
3411
+ */
3412
+ public addAccountData(events: BriijEvent[]): void {
3413
+ for (const event of events) {
3414
+ if (event.getType() === "m.tag") {
3415
+ this.addTags(event);
3416
+ }
3417
+ const eventType = event.getType();
3418
+ const lastEvent = this.accountData.get(eventType);
3419
+ this.accountData.set(eventType, event);
3420
+ this.emit(RoomEvent.AccountData, event, this, lastEvent);
3421
+ }
3422
+ }
3423
+
3424
+ /**
3425
+ * Access account_data event of given event type for this room
3426
+ * @param type - the type of account_data event to be accessed
3427
+ * @returns the account_data event in question
3428
+ */
3429
+ public getAccountData(type: EventType | string): BriijEvent | undefined {
3430
+ return this.accountData.get(type);
3431
+ }
3432
+
3433
+ /**
3434
+ * Get an iterator of currently active sticky events.
3435
+ */
3436
+ // eslint-disable-next-line
3437
+ public _unstable_getStickyEvents(): ReturnType<RoomStickyEventsStore["getStickyEvents"]> {
3438
+ return this.stickyEvents.getStickyEvents();
3439
+ }
3440
+
3441
+ /**
3442
+ * Get a sticky event that match the given `type`, `sender`, and `stickyKey`
3443
+ * @param type The event `type`.
3444
+ * @param sender The sender of the sticky event.
3445
+ * @param stickyKey The sticky key used by the event.
3446
+ * @returns A matching active sticky event, or undefined.
3447
+ */
3448
+ // eslint-disable-next-line
3449
+ public _unstable_getKeyedStickyEvent(
3450
+ sender: string,
3451
+ type: string,
3452
+ stickyKey: string,
3453
+ ): ReturnType<RoomStickyEventsStore["getKeyedStickyEvent"]> {
3454
+ return this.stickyEvents.getKeyedStickyEvent(sender, type, stickyKey);
3455
+ }
3456
+
3457
+ /**
3458
+ * Get active sticky events without a sticky key that match the given `type` and `sender`.
3459
+ * @param type The event `type`.
3460
+ * @param sender The sender of the sticky event.
3461
+ * @returns An array of matching sticky events.
3462
+ */
3463
+ // eslint-disable-next-line
3464
+ public _unstable_getUnkeyedStickyEvent(
3465
+ sender: string,
3466
+ type: string,
3467
+ ): ReturnType<RoomStickyEventsStore["getUnkeyedStickyEvent"]> {
3468
+ return this.stickyEvents.getUnkeyedStickyEvent(sender, type);
3469
+ }
3470
+
3471
+ /**
3472
+ * Add a series of sticky events, emitting `RoomEvent.StickyEvents` if any
3473
+ * changes were made.
3474
+ * @param events A set of new sticky events.
3475
+ * @internal
3476
+ */
3477
+ // eslint-disable-next-line
3478
+ public _unstable_addStickyEvents(events: BriijEvent[]): ReturnType<RoomStickyEventsStore["addStickyEvents"]> {
3479
+ return this.stickyEvents.addStickyEvents(events);
3480
+ }
3481
+
3482
+ /**
3483
+ * Returns whether the syncing user has permission to send a message in the room
3484
+ * @returns true if the user should be permitted to send
3485
+ * message events into the room.
3486
+ */
3487
+ public maySendMessage(): boolean {
3488
+ return (
3489
+ this.getMyMembership() === KnownMembership.Join &&
3490
+ (this.hasEncryptionStateEvent()
3491
+ ? this.currentState.maySendEvent(EventType.RoomMessageEncrypted, this.myUserId)
3492
+ : this.currentState.maySendEvent(EventType.RoomMessage, this.myUserId))
3493
+ );
3494
+ }
3495
+
3496
+ /**
3497
+ * Returns whether the given user has permissions to issue an invite for this room.
3498
+ * @param userId - the ID of the Matrix user to check permissions for
3499
+ * @returns true if the user should be permitted to issue invites for this room.
3500
+ */
3501
+ public canInvite(userId: string): boolean {
3502
+ let canInvite = this.getMyMembership() === KnownMembership.Join;
3503
+ const powerLevelsEvent = this.currentState.getStateEvents(EventType.RoomPowerLevels, "");
3504
+ const powerLevels = powerLevelsEvent && powerLevelsEvent.getContent();
3505
+ const me = this.getMember(userId);
3506
+ if (powerLevels && me && powerLevels.invite > me.powerLevel) {
3507
+ canInvite = false;
3508
+ }
3509
+ return canInvite;
3510
+ }
3511
+
3512
+ /**
3513
+ * Returns the join rule based on the m.room.join_rule state event, defaulting to `invite`.
3514
+ * @returns the join_rule applied to this room
3515
+ */
3516
+ public getJoinRule(): JoinRule {
3517
+ return this.currentState.getJoinRule();
3518
+ }
3519
+
3520
+ /**
3521
+ * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.
3522
+ * @returns the history_visibility applied to this room
3523
+ */
3524
+ public getHistoryVisibility(): HistoryVisibility {
3525
+ return this.currentState.getHistoryVisibility();
3526
+ }
3527
+
3528
+ /**
3529
+ * Returns the history visibility based on the m.room.history_visibility state event, defaulting to `shared`.
3530
+ * @returns the history_visibility applied to this room
3531
+ */
3532
+ public getGuestAccess(): GuestAccess {
3533
+ return this.currentState.getGuestAccess();
3534
+ }
3535
+
3536
+ /**
3537
+ * Returns the type of the room from the `m.room.create` event content or undefined if none is set
3538
+ * @returns the type of the room.
3539
+ */
3540
+ public getType(): RoomType | string | undefined {
3541
+ const createEvent = this.currentState.getStateEvents(EventType.RoomCreate, "");
3542
+ if (!createEvent) {
3543
+ if (!this.getTypeWarning) {
3544
+ logger.warn("[getType] Room " + this.roomId + " does not have an m.room.create event");
3545
+ this.getTypeWarning = true;
3546
+ }
3547
+ return undefined;
3548
+ }
3549
+ return createEvent.getContent()[RoomCreateTypeField];
3550
+ }
3551
+
3552
+ /**
3553
+ * Returns whether the room is a space-room as defined by MSC1772.
3554
+ * @returns true if the room's type is RoomType.Space
3555
+ */
3556
+ public isSpaceRoom(): boolean {
3557
+ return this.getType() === RoomType.Space;
3558
+ }
3559
+
3560
+ /**
3561
+ * Returns whether the room is a call-room as defined by MSC3417.
3562
+ * @returns true if the room's type is RoomType.UnstableCall
3563
+ */
3564
+ public isCallRoom(): boolean {
3565
+ return this.getType() === RoomType.UnstableCall;
3566
+ }
3567
+
3568
+ /**
3569
+ * Returns whether the room is a video room.
3570
+ * @returns true if the room's type is RoomType.ElementVideo
3571
+ */
3572
+ public isElementVideoRoom(): boolean {
3573
+ return this.getType() === RoomType.ElementVideo;
3574
+ }
3575
+
3576
+ /**
3577
+ * Find the predecessor of this room.
3578
+ *
3579
+ * @param msc3946ProcessDynamicPredecessor - if true, look for an
3580
+ * m.room.predecessor state event and use it if found (MSC3946).
3581
+ * @returns null if this room has no predecessor. Otherwise, returns
3582
+ * the roomId, last eventId and viaServers of the predecessor room.
3583
+ *
3584
+ * If msc3946ProcessDynamicPredecessor is true, use m.predecessor events
3585
+ * as well as m.room.create events to find predecessors.
3586
+ *
3587
+ * Note: if an m.predecessor event is used, eventId may be undefined
3588
+ * since last_known_event_id is optional.
3589
+ *
3590
+ * Note: viaServers may be undefined, and will definitely be undefined if
3591
+ * this predecessor comes from a RoomCreate event (rather than a
3592
+ * RoomPredecessor, which has the optional via_servers property).
3593
+ */
3594
+ public findPredecessor(
3595
+ msc3946ProcessDynamicPredecessor = false,
3596
+ ): { roomId: string; eventId?: string; viaServers?: string[] } | null {
3597
+ const currentState = this.getLiveTimeline().getState(EventTimeline.FORWARDS);
3598
+ if (!currentState) {
3599
+ return null;
3600
+ }
3601
+ return currentState.findPredecessor(msc3946ProcessDynamicPredecessor);
3602
+ }
3603
+
3604
+ private roomNameGenerator(state: RoomNameState): string {
3605
+ if (this.client.roomNameGenerator) {
3606
+ const name = this.client.roomNameGenerator(this.roomId, state);
3607
+ if (name !== null) {
3608
+ return name;
3609
+ }
3610
+ }
3611
+
3612
+ switch (state.type) {
3613
+ case RoomNameType.Actual:
3614
+ return state.name;
3615
+ case RoomNameType.Generated:
3616
+ switch (state.subtype) {
3617
+ case "Inviting":
3618
+ return `Inviting ${memberNamesToRoomName(state.names, state.count)}`;
3619
+ default:
3620
+ return memberNamesToRoomName(state.names, state.count);
3621
+ }
3622
+ case RoomNameType.EmptyRoom:
3623
+ if (state.oldName) {
3624
+ return `Empty room (was ${state.oldName})`;
3625
+ } else {
3626
+ return "Empty room";
3627
+ }
3628
+ }
3629
+ }
3630
+
3631
+ /**
3632
+ * This is an internal method. Calculates the name of the room from the current
3633
+ * room state.
3634
+ * @param userId - The client's user ID. Used to filter room members
3635
+ * correctly.
3636
+ * @param ignoreRoomNameEvent - Return the implicit room name that we'd see if there
3637
+ * was no m.room.name event.
3638
+ * @returns The calculated room name.
3639
+ */
3640
+ private calculateRoomName(userId: string, ignoreRoomNameEvent = false): string {
3641
+ if (!ignoreRoomNameEvent) {
3642
+ const name = this.currentState.getStateEvents(EventType.RoomName, "")?.getContent().name;
3643
+ if (name && typeof name === "string") {
3644
+ return this.roomNameGenerator({
3645
+ type: RoomNameType.Actual,
3646
+ name,
3647
+ });
3648
+ }
3649
+ }
3650
+
3651
+ const alias = this.getCanonicalAlias();
3652
+ if (alias) {
3653
+ return this.roomNameGenerator({
3654
+ type: RoomNameType.Actual,
3655
+ name: alias,
3656
+ });
3657
+ }
3658
+
3659
+ const joinedMemberCount = this.currentState.getJoinedMemberCount();
3660
+ const invitedMemberCount = this.currentState.getInvitedMemberCount();
3661
+ // -1 because these numbers include the syncing user
3662
+ let inviteJoinCount = joinedMemberCount + invitedMemberCount - 1;
3663
+
3664
+ // get service members (e.g. helper bots) for exclusion
3665
+ const excludedUserIds = this.getFunctionalMembers();
3666
+
3667
+ // get members from heroes that are NOT ourselves
3668
+ let otherNames: string[] = [];
3669
+ if (this.heroes) {
3670
+ // if we have heroes, use those as the names
3671
+ this.heroes.forEach((hero) => {
3672
+ // filter service members
3673
+ if (excludedUserIds.includes(hero.userId)) {
3674
+ inviteJoinCount--;
3675
+ return;
3676
+ }
3677
+ // If the hero has a display name, use that.
3678
+ // Otherwise, look their user ID up in the membership and use
3679
+ // the name from there, or the user ID as a last resort.
3680
+ if (hero.displayName) {
3681
+ otherNames.push(hero.displayName);
3682
+ } else {
3683
+ const member = this.getMember(hero.userId);
3684
+ otherNames.push(member ? member.name : hero.userId);
3685
+ }
3686
+ });
3687
+ } else {
3688
+ let otherMembers = this.currentState.getMembers().filter((m) => {
3689
+ return (
3690
+ m.userId !== userId &&
3691
+ (m.membership === KnownMembership.Invite || m.membership === KnownMembership.Join)
3692
+ );
3693
+ });
3694
+ otherMembers = otherMembers.filter(({ userId }) => {
3695
+ // filter service members
3696
+ if (excludedUserIds.includes(userId)) {
3697
+ inviteJoinCount--;
3698
+ return false;
3699
+ }
3700
+ return true;
3701
+ });
3702
+ // make sure members have stable order
3703
+ const collator = new Intl.Collator();
3704
+ otherMembers.sort((a, b) => collator.compare(a.userId, b.userId));
3705
+ // only 5 first members, immitate summaryHeroes
3706
+ otherMembers = otherMembers.slice(0, 5);
3707
+ otherNames = otherMembers.map((m) => m.name);
3708
+ }
3709
+
3710
+ if (inviteJoinCount) {
3711
+ return this.roomNameGenerator({
3712
+ type: RoomNameType.Generated,
3713
+ names: otherNames,
3714
+ count: inviteJoinCount,
3715
+ });
3716
+ }
3717
+
3718
+ const myMembership = this.getMyMembership();
3719
+ // if I have created a room and invited people through
3720
+ // 3rd party invites
3721
+ if (myMembership == KnownMembership.Join) {
3722
+ const thirdPartyInvites = this.currentState.getStateEvents(EventType.RoomThirdPartyInvite);
3723
+
3724
+ if (thirdPartyInvites?.length) {
3725
+ const thirdPartyNames = thirdPartyInvites.map((i) => {
3726
+ return i.getContent().display_name;
3727
+ });
3728
+
3729
+ return this.roomNameGenerator({
3730
+ type: RoomNameType.Generated,
3731
+ subtype: "Inviting",
3732
+ names: thirdPartyNames,
3733
+ count: thirdPartyNames.length + 1,
3734
+ });
3735
+ }
3736
+ }
3737
+
3738
+ // let's try to figure out who was here before
3739
+ let leftNames = otherNames;
3740
+ // if we didn't have heroes, try finding them in the room state
3741
+ if (!leftNames.length) {
3742
+ leftNames = this.currentState
3743
+ .getMembers()
3744
+ .filter((m) => {
3745
+ return (
3746
+ m.userId !== userId &&
3747
+ m.membership !== KnownMembership.Invite &&
3748
+ m.membership !== KnownMembership.Join
3749
+ );
3750
+ })
3751
+ .map((m) => m.name);
3752
+ }
3753
+
3754
+ let oldName: string | undefined;
3755
+ if (leftNames.length) {
3756
+ oldName = this.roomNameGenerator({
3757
+ type: RoomNameType.Generated,
3758
+ names: leftNames,
3759
+ count: leftNames.length + 1,
3760
+ });
3761
+ }
3762
+
3763
+ return this.roomNameGenerator({
3764
+ type: RoomNameType.EmptyRoom,
3765
+ oldName,
3766
+ });
3767
+ }
3768
+
3769
+ /**
3770
+ * When we receive a new visibility change event:
3771
+ *
3772
+ * - store this visibility change alongside the timeline, in case we
3773
+ * later need to apply it to an event that we haven't received yet;
3774
+ * - if we have already received the event whose visibility has changed,
3775
+ * patch it to reflect the visibility change and inform listeners.
3776
+ */
3777
+ private applyNewVisibilityEvent(event: BriijEvent): void {
3778
+ const visibilityChange = event.asVisibilityChange();
3779
+ if (!visibilityChange) {
3780
+ // The event is ill-formed.
3781
+ return;
3782
+ }
3783
+
3784
+ // Ignore visibility change events that are not emitted by moderators.
3785
+ const userId = event.getSender();
3786
+ if (!userId) {
3787
+ return;
3788
+ }
3789
+ const isPowerSufficient =
3790
+ (EVENT_VISIBILITY_CHANGE_TYPE.name &&
3791
+ this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.name, userId)) ||
3792
+ (EVENT_VISIBILITY_CHANGE_TYPE.altName &&
3793
+ this.currentState.maySendStateEvent(EVENT_VISIBILITY_CHANGE_TYPE.altName, userId));
3794
+ if (!isPowerSufficient) {
3795
+ // Powerlevel is insufficient.
3796
+ return;
3797
+ }
3798
+
3799
+ // Record this change in visibility.
3800
+ // If the event is not in our timeline and we only receive it later,
3801
+ // we may need to apply the visibility change at a later date.
3802
+
3803
+ const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(visibilityChange.eventId);
3804
+ if (visibilityEventsOnOriginalEvent) {
3805
+ // It would be tempting to simply erase the latest visibility change
3806
+ // but we need to record all of the changes in case the latest change
3807
+ // is ever redacted.
3808
+ //
3809
+ // In practice, linear scans through `visibilityEvents` should be fast.
3810
+ // However, to protect against a potential DoS attack, we limit the
3811
+ // number of iterations in this loop.
3812
+ let index = visibilityEventsOnOriginalEvent.length - 1;
3813
+ const min = Math.max(
3814
+ 0,
3815
+ visibilityEventsOnOriginalEvent.length - MAX_NUMBER_OF_VISIBILITY_EVENTS_TO_SCAN_THROUGH,
3816
+ );
3817
+ for (; index >= min; --index) {
3818
+ const target = visibilityEventsOnOriginalEvent[index];
3819
+ if (target.getTs() < event.getTs()) {
3820
+ break;
3821
+ }
3822
+ }
3823
+ if (index === -1) {
3824
+ visibilityEventsOnOriginalEvent.unshift(event);
3825
+ } else {
3826
+ visibilityEventsOnOriginalEvent.splice(index + 1, 0, event);
3827
+ }
3828
+ } else {
3829
+ this.visibilityEvents.set(visibilityChange.eventId, [event]);
3830
+ }
3831
+
3832
+ // Finally, let's check if the event is already in our timeline.
3833
+ // If so, we need to patch it and inform listeners.
3834
+
3835
+ const originalEvent = this.findEventById(visibilityChange.eventId);
3836
+ if (!originalEvent) {
3837
+ return;
3838
+ }
3839
+ originalEvent.applyVisibilityEvent(visibilityChange);
3840
+ }
3841
+
3842
+ private redactVisibilityChangeEvent(event: BriijEvent): void {
3843
+ // Sanity checks.
3844
+ if (!event.isVisibilityEvent) {
3845
+ throw new Error("expected a visibility change event");
3846
+ }
3847
+ const relation = event.getRelation();
3848
+ const originalEventId = relation?.event_id;
3849
+ const visibilityEventsOnOriginalEvent = this.visibilityEvents.get(originalEventId!);
3850
+ if (!visibilityEventsOnOriginalEvent) {
3851
+ // No visibility changes on the original event.
3852
+ // In particular, this change event was not recorded,
3853
+ // most likely because it was ill-formed.
3854
+ return;
3855
+ }
3856
+ const index = visibilityEventsOnOriginalEvent.findIndex((change) => change.getId() === event.getId());
3857
+ if (index === -1) {
3858
+ // This change event was not recorded, most likely because
3859
+ // it was ill-formed.
3860
+ return;
3861
+ }
3862
+ // Remove visibility change.
3863
+ visibilityEventsOnOriginalEvent.splice(index, 1);
3864
+
3865
+ // If we removed the latest visibility change event, propagate changes.
3866
+ if (index === visibilityEventsOnOriginalEvent.length) {
3867
+ const originalEvent = this.findEventById(originalEventId!);
3868
+ if (!originalEvent) {
3869
+ return;
3870
+ }
3871
+ if (index === 0) {
3872
+ // We have just removed the only visibility change event.
3873
+ this.visibilityEvents.delete(originalEventId!);
3874
+ originalEvent.applyVisibilityEvent();
3875
+ } else {
3876
+ const newEvent = visibilityEventsOnOriginalEvent[visibilityEventsOnOriginalEvent.length - 1];
3877
+ const newVisibility = newEvent.asVisibilityChange();
3878
+ if (!newVisibility) {
3879
+ // Event is ill-formed.
3880
+ // This breaks our invariant.
3881
+ throw new Error("at this stage, visibility changes should be well-formed");
3882
+ }
3883
+ originalEvent.applyVisibilityEvent(newVisibility);
3884
+ }
3885
+ }
3886
+ }
3887
+
3888
+ /**
3889
+ * When we receive an event whose visibility has been altered by
3890
+ * a (more recent) visibility change event, patch the event in
3891
+ * place so that clients now not to display it.
3892
+ *
3893
+ * @param event - Any matrix event. If this event has at least one a
3894
+ * pending visibility change event, apply the latest visibility
3895
+ * change event.
3896
+ */
3897
+ private applyPendingVisibilityEvents(event: BriijEvent): void {
3898
+ const visibilityEvents = this.visibilityEvents.get(event.getId()!);
3899
+ if (!visibilityEvents || visibilityEvents.length == 0) {
3900
+ // No pending visibility change in store.
3901
+ return;
3902
+ }
3903
+ const visibilityEvent = visibilityEvents[visibilityEvents.length - 1];
3904
+ const visibilityChange = visibilityEvent.asVisibilityChange();
3905
+ if (!visibilityChange) {
3906
+ return;
3907
+ }
3908
+ if (visibilityChange.visible) {
3909
+ // Events are visible by default, no need to apply a visibility change.
3910
+ // Note that we need to keep the visibility changes in `visibilityEvents`,
3911
+ // in case we later fetch an older visibility change event that is superseded
3912
+ // by `visibilityChange`.
3913
+ }
3914
+ if (visibilityEvent.getTs() < event.getTs()) {
3915
+ // Something is wrong, the visibility change cannot happen before the
3916
+ // event. Presumably an ill-formed event.
3917
+ return;
3918
+ }
3919
+ event.applyVisibilityEvent(visibilityChange);
3920
+ }
3921
+
3922
+ /**
3923
+ * Find when a client has gained thread capabilities by inspecting the oldest
3924
+ * threaded receipt
3925
+ * @returns the timestamp of the oldest threaded receipt
3926
+ */
3927
+ public getOldestThreadedReceiptTs(): number {
3928
+ return this.oldestThreadedReceiptTs;
3929
+ }
3930
+
3931
+ /**
3932
+ * Determines if the given user has read a particular event ID with the known
3933
+ * history of the room. This is not a definitive check as it relies only on
3934
+ * what is available to the room at the time of execution.
3935
+ *
3936
+ * @param userId - The user ID to check the read state of.
3937
+ * @param eventId - The event ID to check if the user read.
3938
+ * @returns true if the user has read the event, false otherwise.
3939
+ */
3940
+ public hasUserReadEvent(userId: string, eventId: string): boolean {
3941
+ return this.roomReceipts.hasUserReadEvent(userId, eventId);
3942
+ }
3943
+
3944
+ /**
3945
+ * Returns the most recent unthreaded receipt for a given user
3946
+ * @param userId - the MxID of the User
3947
+ * @returns an unthreaded Receipt. Can be undefined if receipts have been disabled
3948
+ * or a user chooses to use private read receipts (or we have simply not received
3949
+ * a receipt from this user yet).
3950
+ */
3951
+ public getLastUnthreadedReceiptFor(userId: string): Receipt | undefined {
3952
+ return this.unthreadedReceipts.get(userId);
3953
+ }
3954
+
3955
+ /**
3956
+ * This issue should also be addressed on synapse's side and is tracked as part
3957
+ * of https://github.com/matrix-org/synapse/issues/14837
3958
+ *
3959
+ *
3960
+ * We consider a room fully read if the current user has sent
3961
+ * the last event in the live timeline of that context and if the read receipt
3962
+ * we have on record matches.
3963
+ * This also detects all unread threads and applies the same logic to those
3964
+ * contexts
3965
+ */
3966
+ public fixupNotifications(userId: string): void {
3967
+ super.fixupNotifications(userId);
3968
+
3969
+ const unreadThreads = this.getThreads().filter(
3970
+ (thread) => this.getThreadUnreadNotificationCount(thread.id, NotificationCountType.Total) > 0,
3971
+ );
3972
+
3973
+ for (const thread of unreadThreads) {
3974
+ thread.fixupNotifications(userId);
3975
+ }
3976
+ }
3977
+
3978
+ /**
3979
+ * Determine the order of two events in this room.
3980
+ *
3981
+ * In principle this should use the same order as the server, but in practice
3982
+ * this is difficult for events that were not received over the Sync API. See
3983
+ * MSC4033 for details.
3984
+ *
3985
+ * This implementation leans on the order of events within their timelines, and
3986
+ * falls back to comparing event timestamps when they are in different
3987
+ * timelines.
3988
+ *
3989
+ * See https://github.com/matrix-org/matrix-js-sdk/issues/3325 for where we are
3990
+ * tracking the work to fix this.
3991
+ *
3992
+ * @param leftEventId - the id of the first event
3993
+ * @param rightEventId - the id of the second event
3994
+
3995
+ * @returns -1 if left \< right, 1 if left \> right, 0 if left == right, null if
3996
+ * we can't tell (because we can't find the events).
3997
+ */
3998
+ public compareEventOrdering(leftEventId: string, rightEventId: string): number | null {
3999
+ return compareEventOrdering(this, leftEventId, rightEventId);
4000
+ }
4001
+
4002
+ /**
4003
+ * Return true if this room has an `m.room.encryption` state event.
4004
+ *
4005
+ * If this returns `true`, events sent to this room should be encrypted (and `BriijClient.sendEvent` and friends
4006
+ * will encrypt outgoing events).
4007
+ */
4008
+ public hasEncryptionStateEvent(): boolean {
4009
+ return Boolean(
4010
+ this.getLiveTimeline().getState(EventTimeline.FORWARDS)?.getStateEvents(EventType.RoomEncryption, ""),
4011
+ );
4012
+ }
4013
+ }
4014
+
4015
+ // a map from current event status to a list of allowed next statuses
4016
+ const ALLOWED_TRANSITIONS: Record<EventStatus, EventStatus[]> = {
4017
+ [EventStatus.ENCRYPTING]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],
4018
+ [EventStatus.SENDING]: [EventStatus.ENCRYPTING, EventStatus.QUEUED, EventStatus.NOT_SENT, EventStatus.SENT],
4019
+ [EventStatus.QUEUED]: [EventStatus.SENDING, EventStatus.NOT_SENT, EventStatus.CANCELLED],
4020
+ [EventStatus.SENT]: [],
4021
+ [EventStatus.NOT_SENT]: [EventStatus.SENDING, EventStatus.QUEUED, EventStatus.CANCELLED],
4022
+ [EventStatus.CANCELLED]: [],
4023
+ };
4024
+
4025
+ export enum RoomNameType {
4026
+ EmptyRoom,
4027
+ Generated,
4028
+ Actual,
4029
+ }
4030
+
4031
+ export interface EmptyRoomNameState {
4032
+ type: RoomNameType.EmptyRoom;
4033
+ oldName?: string;
4034
+ }
4035
+
4036
+ export interface GeneratedRoomNameState {
4037
+ type: RoomNameType.Generated;
4038
+ subtype?: "Inviting";
4039
+ names: string[];
4040
+ count: number;
4041
+ }
4042
+
4043
+ export interface ActualRoomNameState {
4044
+ type: RoomNameType.Actual;
4045
+ name: string;
4046
+ }
4047
+
4048
+ export type RoomNameState = EmptyRoomNameState | GeneratedRoomNameState | ActualRoomNameState;
4049
+
4050
+ // Can be overriden by IBriijClientCreateOpts::memberNamesToRoomNameFn
4051
+ function memberNamesToRoomName(names: string[], count: number): string {
4052
+ const countWithoutMe = count - 1;
4053
+ if (!names.length) {
4054
+ return "Empty room";
4055
+ } else if (names.length === 1 && countWithoutMe <= 1) {
4056
+ return names[0];
4057
+ } else if (names.length === 2 && countWithoutMe <= 2) {
4058
+ return `${names[0]} and ${names[1]}`;
4059
+ } else {
4060
+ const plural = countWithoutMe > 1;
4061
+ if (plural) {
4062
+ return `${names[0]} and ${countWithoutMe} others`;
4063
+ } else {
4064
+ return `${names[0]} and 1 other`;
4065
+ }
4066
+ }
4067
+ }