@jeongsu816/matrix-bot-sdk 0.0.0-stage → 0.8.1

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 (377) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -2
  3. package/lib/AdminApis.d.ts +52 -0
  4. package/lib/AdminApis.js +29 -0
  5. package/lib/AdminApis.js.map +1 -0
  6. package/lib/DMs.d.ts +48 -0
  7. package/lib/DMs.js +160 -0
  8. package/lib/DMs.js.map +1 -0
  9. package/lib/IFilter.d.ts +7 -0
  10. package/lib/IFilter.js +3 -0
  11. package/lib/IFilter.js.map +1 -0
  12. package/lib/MatrixAuth.d.ts +45 -0
  13. package/lib/MatrixAuth.js +125 -0
  14. package/lib/MatrixAuth.js.map +1 -0
  15. package/lib/MatrixClient.d.ts +834 -0
  16. package/lib/MatrixClient.js +2268 -0
  17. package/lib/MatrixClient.js.map +1 -0
  18. package/lib/PantalaimonClient.d.ts +42 -0
  19. package/lib/PantalaimonClient.js +44 -0
  20. package/lib/PantalaimonClient.js.map +1 -0
  21. package/lib/SynapseAdminApis.d.ts +350 -0
  22. package/lib/SynapseAdminApis.js +244 -0
  23. package/lib/SynapseAdminApis.js.map +1 -0
  24. package/lib/SynchronousMatrixClient.d.ts +82 -0
  25. package/lib/SynchronousMatrixClient.js +130 -0
  26. package/lib/SynchronousMatrixClient.js.map +1 -0
  27. package/lib/UnstableApis.d.ts +43 -0
  28. package/lib/UnstableApis.js +74 -0
  29. package/lib/UnstableApis.js.map +1 -0
  30. package/lib/appservice/Appservice.d.ts +328 -0
  31. package/lib/appservice/Appservice.js +803 -0
  32. package/lib/appservice/Appservice.js.map +1 -0
  33. package/lib/appservice/Intent.d.ts +113 -0
  34. package/lib/appservice/Intent.js +363 -0
  35. package/lib/appservice/Intent.js.map +1 -0
  36. package/lib/appservice/MatrixBridge.d.ts +85 -0
  37. package/lib/appservice/MatrixBridge.js +111 -0
  38. package/lib/appservice/MatrixBridge.js.map +1 -0
  39. package/lib/appservice/UnstableAppserviceApis.d.ts +41 -0
  40. package/lib/appservice/UnstableAppserviceApis.js +62 -0
  41. package/lib/appservice/UnstableAppserviceApis.js.map +1 -0
  42. package/lib/appservice/http_responses.d.ts +77 -0
  43. package/lib/appservice/http_responses.js +3 -0
  44. package/lib/appservice/http_responses.js.map +1 -0
  45. package/lib/b64.d.ts +42 -0
  46. package/lib/b64.js +68 -0
  47. package/lib/b64.js.map +1 -0
  48. package/lib/e2ee/CrossSigningBootstrap.d.ts +73 -0
  49. package/lib/e2ee/CrossSigningBootstrap.js +86 -0
  50. package/lib/e2ee/CrossSigningBootstrap.js.map +1 -0
  51. package/lib/e2ee/CryptoClient.d.ts +163 -0
  52. package/lib/e2ee/CryptoClient.js +382 -0
  53. package/lib/e2ee/CryptoClient.js.map +1 -0
  54. package/lib/e2ee/ICryptoRoomInformation.d.ts +8 -0
  55. package/lib/e2ee/ICryptoRoomInformation.js +3 -0
  56. package/lib/e2ee/ICryptoRoomInformation.js.map +1 -0
  57. package/lib/e2ee/RoomTracker.d.ts +41 -0
  58. package/lib/e2ee/RoomTracker.js +96 -0
  59. package/lib/e2ee/RoomTracker.js.map +1 -0
  60. package/lib/e2ee/RustEngine.d.ts +149 -0
  61. package/lib/e2ee/RustEngine.js +467 -0
  62. package/lib/e2ee/RustEngine.js.map +1 -0
  63. package/lib/e2ee/decorators.d.ts +10 -0
  64. package/lib/e2ee/decorators.js +37 -0
  65. package/lib/e2ee/decorators.js.map +1 -0
  66. package/lib/helpers/MatrixEntity.d.ts +37 -0
  67. package/lib/helpers/MatrixEntity.js +67 -0
  68. package/lib/helpers/MatrixEntity.js.map +1 -0
  69. package/lib/helpers/MatrixGlob.d.ts +22 -0
  70. package/lib/helpers/MatrixGlob.js +35 -0
  71. package/lib/helpers/MatrixGlob.js.map +1 -0
  72. package/lib/helpers/MentionPill.d.ts +40 -0
  73. package/lib/helpers/MentionPill.js +91 -0
  74. package/lib/helpers/MentionPill.js.map +1 -0
  75. package/lib/helpers/Permalinks.d.ts +58 -0
  76. package/lib/helpers/Permalinks.js +73 -0
  77. package/lib/helpers/Permalinks.js.map +1 -0
  78. package/lib/helpers/ProfileCache.d.ts +48 -0
  79. package/lib/helpers/ProfileCache.js +114 -0
  80. package/lib/helpers/ProfileCache.js.map +1 -0
  81. package/lib/helpers/RichReply.d.ts +17 -0
  82. package/lib/helpers/RichReply.js +47 -0
  83. package/lib/helpers/RichReply.js.map +1 -0
  84. package/lib/helpers/UnpaddedBase64.d.ts +31 -0
  85. package/lib/helpers/UnpaddedBase64.js +45 -0
  86. package/lib/helpers/UnpaddedBase64.js.map +1 -0
  87. package/lib/http.d.ts +17 -0
  88. package/lib/http.js +147 -0
  89. package/lib/http.js.map +1 -0
  90. package/lib/identity/IdentityClient.d.ts +93 -0
  91. package/lib/identity/IdentityClient.js +248 -0
  92. package/lib/identity/IdentityClient.js.map +1 -0
  93. package/lib/index.d.ts +91 -0
  94. package/lib/index.js +125 -0
  95. package/lib/index.js.map +1 -0
  96. package/lib/logging/ConsoleLogger.d.ts +12 -0
  97. package/lib/logging/ConsoleLogger.js +28 -0
  98. package/lib/logging/ConsoleLogger.js.map +1 -0
  99. package/lib/logging/ILogger.d.ts +36 -0
  100. package/lib/logging/ILogger.js +3 -0
  101. package/lib/logging/ILogger.js.map +1 -0
  102. package/lib/logging/LogService.d.ts +100 -0
  103. package/lib/logging/LogService.js +169 -0
  104. package/lib/logging/LogService.js.map +1 -0
  105. package/lib/logging/RichConsoleLogger.d.ts +20 -0
  106. package/lib/logging/RichConsoleLogger.js +41 -0
  107. package/lib/logging/RichConsoleLogger.js.map +1 -0
  108. package/lib/metrics/IMetricListener.d.ts +52 -0
  109. package/lib/metrics/IMetricListener.js +3 -0
  110. package/lib/metrics/IMetricListener.js.map +1 -0
  111. package/lib/metrics/Metrics.d.ts +66 -0
  112. package/lib/metrics/Metrics.js +128 -0
  113. package/lib/metrics/Metrics.js.map +1 -0
  114. package/lib/metrics/contexts.d.ts +51 -0
  115. package/lib/metrics/contexts.js +3 -0
  116. package/lib/metrics/contexts.js.map +1 -0
  117. package/lib/metrics/decorators.d.ts +15 -0
  118. package/lib/metrics/decorators.js +92 -0
  119. package/lib/metrics/decorators.js.map +1 -0
  120. package/lib/metrics/names.d.ts +45 -0
  121. package/lib/metrics/names.js +49 -0
  122. package/lib/metrics/names.js.map +1 -0
  123. package/lib/mixins/AutojoinRoomsMixin.d.ts +10 -0
  124. package/lib/mixins/AutojoinRoomsMixin.js +25 -0
  125. package/lib/mixins/AutojoinRoomsMixin.js.map +1 -0
  126. package/lib/mixins/AutojoinUpgradedRoomsMixin.d.ts +10 -0
  127. package/lib/mixins/AutojoinUpgradedRoomsMixin.js +40 -0
  128. package/lib/mixins/AutojoinUpgradedRoomsMixin.js.map +1 -0
  129. package/lib/models/Account.d.ts +8 -0
  130. package/lib/models/Account.js +3 -0
  131. package/lib/models/Account.js.map +1 -0
  132. package/lib/models/CreateRoom.d.ts +125 -0
  133. package/lib/models/CreateRoom.js +3 -0
  134. package/lib/models/CreateRoom.js.map +1 -0
  135. package/lib/models/Crypto.d.ts +167 -0
  136. package/lib/models/Crypto.js +31 -0
  137. package/lib/models/Crypto.js.map +1 -0
  138. package/lib/models/EventContext.d.ts +19 -0
  139. package/lib/models/EventContext.js +3 -0
  140. package/lib/models/EventContext.js.map +1 -0
  141. package/lib/models/IdentityServerModels.d.ts +20 -0
  142. package/lib/models/IdentityServerModels.js +3 -0
  143. package/lib/models/IdentityServerModels.js.map +1 -0
  144. package/lib/models/MSC2176.d.ts +42 -0
  145. package/lib/models/MSC2176.js +3 -0
  146. package/lib/models/MSC2176.js.map +1 -0
  147. package/lib/models/MatrixError.d.ts +38 -0
  148. package/lib/models/MatrixError.js +30 -0
  149. package/lib/models/MatrixError.js.map +1 -0
  150. package/lib/models/MatrixProfile.d.ts +43 -0
  151. package/lib/models/MatrixProfile.js +43 -0
  152. package/lib/models/MatrixProfile.js.map +1 -0
  153. package/lib/models/OpenIDConnect.d.ts +10 -0
  154. package/lib/models/OpenIDConnect.js +3 -0
  155. package/lib/models/OpenIDConnect.js.map +1 -0
  156. package/lib/models/Policies.d.ts +25 -0
  157. package/lib/models/Policies.js +3 -0
  158. package/lib/models/Policies.js.map +1 -0
  159. package/lib/models/PowerLevelAction.d.ts +27 -0
  160. package/lib/models/PowerLevelAction.js +32 -0
  161. package/lib/models/PowerLevelAction.js.map +1 -0
  162. package/lib/models/PowerLevelBounds.d.ts +15 -0
  163. package/lib/models/PowerLevelBounds.js +3 -0
  164. package/lib/models/PowerLevelBounds.js.map +1 -0
  165. package/lib/models/Presence.d.ts +25 -0
  166. package/lib/models/Presence.js +38 -0
  167. package/lib/models/Presence.js.map +1 -0
  168. package/lib/models/ServerVersions.d.ts +8 -0
  169. package/lib/models/ServerVersions.js +3 -0
  170. package/lib/models/ServerVersions.js.map +1 -0
  171. package/lib/models/Spaces.d.ts +116 -0
  172. package/lib/models/Spaces.js +91 -0
  173. package/lib/models/Spaces.js.map +1 -0
  174. package/lib/models/Threepid.d.ts +8 -0
  175. package/lib/models/Threepid.js +3 -0
  176. package/lib/models/Threepid.js.map +1 -0
  177. package/lib/models/events/AliasesEvent.d.ts +27 -0
  178. package/lib/models/events/AliasesEvent.js +27 -0
  179. package/lib/models/events/AliasesEvent.js.map +1 -0
  180. package/lib/models/events/CanonicalAliasEvent.d.ts +23 -0
  181. package/lib/models/events/CanonicalAliasEvent.js +21 -0
  182. package/lib/models/events/CanonicalAliasEvent.js.map +1 -0
  183. package/lib/models/events/CreateEvent.d.ts +63 -0
  184. package/lib/models/events/CreateEvent.js +33 -0
  185. package/lib/models/events/CreateEvent.js.map +1 -0
  186. package/lib/models/events/EncryptedRoomEvent.d.ts +42 -0
  187. package/lib/models/events/EncryptedRoomEvent.js +28 -0
  188. package/lib/models/events/EncryptedRoomEvent.js.map +1 -0
  189. package/lib/models/events/EncryptionEvent.d.ts +47 -0
  190. package/lib/models/events/EncryptionEvent.js +42 -0
  191. package/lib/models/events/EncryptionEvent.js.map +1 -0
  192. package/lib/models/events/Event.d.ts +26 -0
  193. package/lib/models/events/Event.js +40 -0
  194. package/lib/models/events/Event.js.map +1 -0
  195. package/lib/models/events/EventKind.d.ts +15 -0
  196. package/lib/models/events/EventKind.js +20 -0
  197. package/lib/models/events/EventKind.js.map +1 -0
  198. package/lib/models/events/InvalidEventError.d.ts +14 -0
  199. package/lib/models/events/InvalidEventError.js +24 -0
  200. package/lib/models/events/InvalidEventError.js.map +1 -0
  201. package/lib/models/events/JoinRulesEvent.d.ts +29 -0
  202. package/lib/models/events/JoinRulesEvent.js +21 -0
  203. package/lib/models/events/JoinRulesEvent.js.map +1 -0
  204. package/lib/models/events/MembershipEvent.d.ts +54 -0
  205. package/lib/models/events/MembershipEvent.js +49 -0
  206. package/lib/models/events/MembershipEvent.js.map +1 -0
  207. package/lib/models/events/MessageEvent.d.ts +233 -0
  208. package/lib/models/events/MessageEvent.js +49 -0
  209. package/lib/models/events/MessageEvent.js.map +1 -0
  210. package/lib/models/events/PinnedEventsEvent.d.ts +23 -0
  211. package/lib/models/events/PinnedEventsEvent.js +21 -0
  212. package/lib/models/events/PinnedEventsEvent.js.map +1 -0
  213. package/lib/models/events/PowerLevelsEvent.d.ts +96 -0
  214. package/lib/models/events/PowerLevelsEvent.js +70 -0
  215. package/lib/models/events/PowerLevelsEvent.js.map +1 -0
  216. package/lib/models/events/PresenceEvent.d.ts +56 -0
  217. package/lib/models/events/PresenceEvent.js +21 -0
  218. package/lib/models/events/PresenceEvent.js.map +1 -0
  219. package/lib/models/events/RedactionEvent.d.ts +28 -0
  220. package/lib/models/events/RedactionEvent.js +36 -0
  221. package/lib/models/events/RedactionEvent.js.map +1 -0
  222. package/lib/models/events/RoomAvatarEvent.d.ts +28 -0
  223. package/lib/models/events/RoomAvatarEvent.js +21 -0
  224. package/lib/models/events/RoomAvatarEvent.js.map +1 -0
  225. package/lib/models/events/RoomEvent.d.ts +58 -0
  226. package/lib/models/events/RoomEvent.js +57 -0
  227. package/lib/models/events/RoomEvent.js.map +1 -0
  228. package/lib/models/events/RoomNameEvent.d.ts +20 -0
  229. package/lib/models/events/RoomNameEvent.js +21 -0
  230. package/lib/models/events/RoomNameEvent.js.map +1 -0
  231. package/lib/models/events/RoomTopicEvent.d.ts +20 -0
  232. package/lib/models/events/RoomTopicEvent.js +21 -0
  233. package/lib/models/events/RoomTopicEvent.js.map +1 -0
  234. package/lib/models/events/SpaceChildEvent.d.ts +53 -0
  235. package/lib/models/events/SpaceChildEvent.js +49 -0
  236. package/lib/models/events/SpaceChildEvent.js.map +1 -0
  237. package/lib/models/events/converter.d.ts +8 -0
  238. package/lib/models/events/converter.js +50 -0
  239. package/lib/models/events/converter.js.map +1 -0
  240. package/lib/models/unstable/MediaInfo.d.ts +16 -0
  241. package/lib/models/unstable/MediaInfo.js +3 -0
  242. package/lib/models/unstable/MediaInfo.js.map +1 -0
  243. package/lib/preprocessors/IPreprocessor.d.ts +22 -0
  244. package/lib/preprocessors/IPreprocessor.js +3 -0
  245. package/lib/preprocessors/IPreprocessor.js.map +1 -0
  246. package/lib/preprocessors/RichRepliesPreprocessor.d.ts +67 -0
  247. package/lib/preprocessors/RichRepliesPreprocessor.js +112 -0
  248. package/lib/preprocessors/RichRepliesPreprocessor.js.map +1 -0
  249. package/lib/request.d.ts +13 -0
  250. package/lib/request.js +23 -0
  251. package/lib/request.js.map +1 -0
  252. package/lib/simple-validation.d.ts +10 -0
  253. package/lib/simple-validation.js +30 -0
  254. package/lib/simple-validation.js.map +1 -0
  255. package/lib/storage/IAppserviceStorageProvider.d.ts +48 -0
  256. package/lib/storage/IAppserviceStorageProvider.js +3 -0
  257. package/lib/storage/IAppserviceStorageProvider.js.map +1 -0
  258. package/lib/storage/ICryptoStorageProvider.d.ts +32 -0
  259. package/lib/storage/ICryptoStorageProvider.js +3 -0
  260. package/lib/storage/ICryptoStorageProvider.js.map +1 -0
  261. package/lib/storage/IStorageProvider.d.ts +47 -0
  262. package/lib/storage/IStorageProvider.js +3 -0
  263. package/lib/storage/IStorageProvider.js.map +1 -0
  264. package/lib/storage/MemoryStorageProvider.d.ts +26 -0
  265. package/lib/storage/MemoryStorageProvider.js +55 -0
  266. package/lib/storage/MemoryStorageProvider.js.map +1 -0
  267. package/lib/storage/RustSdkCryptoStorageProvider.d.ts +38 -0
  268. package/lib/storage/RustSdkCryptoStorageProvider.js +69 -0
  269. package/lib/storage/RustSdkCryptoStorageProvider.js.map +1 -0
  270. package/lib/storage/SimpleFsStorageProvider.d.ts +31 -0
  271. package/lib/storage/SimpleFsStorageProvider.js +122 -0
  272. package/lib/storage/SimpleFsStorageProvider.js.map +1 -0
  273. package/lib/storage/SimplePostgresStorageProvider.d.ts +32 -0
  274. package/lib/storage/SimplePostgresStorageProvider.js +148 -0
  275. package/lib/storage/SimplePostgresStorageProvider.js.map +1 -0
  276. package/lib/strategies/AppserviceJoinRoomStrategy.d.ts +14 -0
  277. package/lib/strategies/AppserviceJoinRoomStrategy.js +54 -0
  278. package/lib/strategies/AppserviceJoinRoomStrategy.js.map +1 -0
  279. package/lib/strategies/JoinRoomStrategy.d.ts +11 -0
  280. package/lib/strategies/JoinRoomStrategy.js +44 -0
  281. package/lib/strategies/JoinRoomStrategy.js.map +1 -0
  282. package/package.json +136 -4
  283. package/src/AdminApis.ts +60 -0
  284. package/src/DMs.ts +164 -0
  285. package/src/IFilter.ts +7 -0
  286. package/src/MatrixAuth.ts +129 -0
  287. package/src/MatrixClient.ts +2046 -0
  288. package/src/PantalaimonClient.ts +62 -0
  289. package/src/SynapseAdminApis.ts +482 -0
  290. package/src/SynchronousMatrixClient.ts +129 -0
  291. package/src/UnstableApis.ts +75 -0
  292. package/src/appservice/Appservice.ts +1089 -0
  293. package/src/appservice/Intent.ts +342 -0
  294. package/src/appservice/MatrixBridge.ts +139 -0
  295. package/src/appservice/UnstableAppserviceApis.ts +63 -0
  296. package/src/appservice/http_responses.ts +77 -0
  297. package/src/b64.ts +63 -0
  298. package/src/e2ee/CrossSigningBootstrap.ts +141 -0
  299. package/src/e2ee/CryptoClient.ts +378 -0
  300. package/src/e2ee/ICryptoRoomInformation.ts +9 -0
  301. package/src/e2ee/RoomTracker.ts +99 -0
  302. package/src/e2ee/RustEngine.ts +580 -0
  303. package/src/e2ee/decorators.ts +38 -0
  304. package/src/helpers/MatrixEntity.ts +65 -0
  305. package/src/helpers/MatrixGlob.ts +38 -0
  306. package/src/helpers/MentionPill.ts +95 -0
  307. package/src/helpers/Permalinks.ts +101 -0
  308. package/src/helpers/ProfileCache.ts +119 -0
  309. package/src/helpers/RichReply.ts +46 -0
  310. package/src/helpers/UnpaddedBase64.ts +44 -0
  311. package/src/http.ts +166 -0
  312. package/src/identity/IdentityClient.ts +225 -0
  313. package/src/index.ts +125 -0
  314. package/src/logging/ConsoleLogger.ts +31 -0
  315. package/src/logging/ILogger.ts +40 -0
  316. package/src/logging/LogService.ts +167 -0
  317. package/src/logging/RichConsoleLogger.ts +70 -0
  318. package/src/metrics/IMetricListener.ts +57 -0
  319. package/src/metrics/Metrics.ts +134 -0
  320. package/src/metrics/contexts.ts +56 -0
  321. package/src/metrics/decorators.ts +94 -0
  322. package/src/metrics/names.ts +53 -0
  323. package/src/mixins/AutojoinRoomsMixin.ts +24 -0
  324. package/src/mixins/AutojoinUpgradedRoomsMixin.ts +37 -0
  325. package/src/models/Account.ts +8 -0
  326. package/src/models/CreateRoom.ts +144 -0
  327. package/src/models/Crypto.ts +188 -0
  328. package/src/models/EventContext.ts +23 -0
  329. package/src/models/IdentityServerModels.ts +18 -0
  330. package/src/models/MSC2176.ts +47 -0
  331. package/src/models/MatrixError.ts +39 -0
  332. package/src/models/MatrixProfile.ts +55 -0
  333. package/src/models/OpenIDConnect.ts +10 -0
  334. package/src/models/Policies.ts +28 -0
  335. package/src/models/PowerLevelAction.ts +31 -0
  336. package/src/models/PowerLevelBounds.ts +16 -0
  337. package/src/models/Presence.ts +38 -0
  338. package/src/models/ServerVersions.ts +8 -0
  339. package/src/models/Spaces.ts +167 -0
  340. package/src/models/Threepid.ts +8 -0
  341. package/src/models/events/AliasesEvent.ts +37 -0
  342. package/src/models/events/CanonicalAliasEvent.ts +30 -0
  343. package/src/models/events/CreateEvent.ts +82 -0
  344. package/src/models/events/EncryptedRoomEvent.ts +58 -0
  345. package/src/models/events/EncryptionEvent.ts +63 -0
  346. package/src/models/events/Event.ts +38 -0
  347. package/src/models/events/EventKind.ts +16 -0
  348. package/src/models/events/InvalidEventError.ts +19 -0
  349. package/src/models/events/JoinRulesEvent.ts +37 -0
  350. package/src/models/events/MembershipEvent.ts +77 -0
  351. package/src/models/events/MessageEvent.ts +292 -0
  352. package/src/models/events/PinnedEventsEvent.ts +30 -0
  353. package/src/models/events/PowerLevelsEvent.ts +135 -0
  354. package/src/models/events/PresenceEvent.ts +69 -0
  355. package/src/models/events/RedactionEvent.ts +44 -0
  356. package/src/models/events/RoomAvatarEvent.ts +36 -0
  357. package/src/models/events/RoomEvent.ts +83 -0
  358. package/src/models/events/RoomNameEvent.ts +27 -0
  359. package/src/models/events/RoomTopicEvent.ts +27 -0
  360. package/src/models/events/SpaceChildEvent.ts +74 -0
  361. package/src/models/events/_MissingEvents.md +35 -0
  362. package/src/models/events/converter.ts +47 -0
  363. package/src/models/unstable/MediaInfo.ts +16 -0
  364. package/src/preprocessors/IPreprocessor.ts +24 -0
  365. package/src/preprocessors/RichRepliesPreprocessor.ts +159 -0
  366. package/src/request.ts +21 -0
  367. package/src/simple-validation.ts +30 -0
  368. package/src/storage/IAppserviceStorageProvider.ts +54 -0
  369. package/src/storage/ICryptoStorageProvider.ts +36 -0
  370. package/src/storage/IStorageProvider.ts +53 -0
  371. package/src/storage/MemoryStorageProvider.ts +65 -0
  372. package/src/storage/RustSdkCryptoStorageProvider.ts +81 -0
  373. package/src/storage/SimpleFsStorageProvider.ts +142 -0
  374. package/src/storage/SimplePostgresStorageProvider.ts +168 -0
  375. package/src/strategies/AppserviceJoinRoomStrategy.ts +47 -0
  376. package/src/strategies/JoinRoomStrategy.ts +45 -0
  377. package/tsconfig.json +22 -0
@@ -0,0 +1,2268 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var _a, _b;
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.MatrixClient = void 0;
14
+ const events_1 = require("events");
15
+ const htmlencode_1 = require("htmlencode");
16
+ const html_to_text_1 = require("html-to-text");
17
+ const MemoryStorageProvider_1 = require("./storage/MemoryStorageProvider");
18
+ const UnstableApis_1 = require("./UnstableApis");
19
+ const request_1 = require("./request");
20
+ const LogService_1 = require("./logging/LogService");
21
+ const RichReply_1 = require("./helpers/RichReply");
22
+ const Metrics_1 = require("./metrics/Metrics");
23
+ const decorators_1 = require("./metrics/decorators");
24
+ const AdminApis_1 = require("./AdminApis");
25
+ const Presence_1 = require("./models/Presence");
26
+ const MembershipEvent_1 = require("./models/events/MembershipEvent");
27
+ const RoomEvent_1 = require("./models/events/RoomEvent");
28
+ const EventKind_1 = require("./models/events/EventKind");
29
+ const IdentityClient_1 = require("./identity/IdentityClient");
30
+ const http_1 = require("./http");
31
+ const Spaces_1 = require("./models/Spaces");
32
+ const PowerLevelAction_1 = require("./models/PowerLevelAction");
33
+ const CryptoClient_1 = require("./e2ee/CryptoClient");
34
+ const Crypto_1 = require("./models/Crypto");
35
+ const decorators_2 = require("./e2ee/decorators");
36
+ const EncryptedRoomEvent_1 = require("./models/events/EncryptedRoomEvent");
37
+ const RustSdkCryptoStorageProvider_1 = require("./storage/RustSdkCryptoStorageProvider");
38
+ const DMs_1 = require("./DMs");
39
+ const SYNC_BACKOFF_MIN_MS = 5000;
40
+ const SYNC_BACKOFF_MAX_MS = 15000;
41
+ const VERSIONS_CACHE_MS = 7200000; // 2 hours
42
+ /**
43
+ * A client that is capable of interacting with a matrix homeserver.
44
+ */
45
+ class MatrixClient extends events_1.EventEmitter {
46
+ /**
47
+ * Creates a new matrix client
48
+ * @param {string} homeserverUrl The homeserver's client-server API URL
49
+ * @param {string} accessToken The access token for the homeserver
50
+ * @param {IStorageProvider} storage The storage provider to use. Defaults to MemoryStorageProvider.
51
+ * @param {ICryptoStorageProvider} cryptoStore Optional crypto storage provider to use. If not supplied,
52
+ * end-to-end encryption will not be functional in this client.
53
+ */
54
+ constructor(homeserverUrl, accessToken, storage = null, cryptoStore = null) {
55
+ super();
56
+ this.homeserverUrl = homeserverUrl;
57
+ this.accessToken = accessToken;
58
+ this.storage = storage;
59
+ this.cryptoStore = cryptoStore;
60
+ /**
61
+ * The presence status to use while syncing. The valid values are "online" to set the account as online,
62
+ * "offline" to set the user as offline, "unavailable" for marking the user away, and null for not setting
63
+ * an explicit presence (the default).
64
+ *
65
+ * Has no effect if the client is not syncing. Does not apply until the next sync request.
66
+ */
67
+ this.syncingPresence = null;
68
+ /**
69
+ * The number of milliseconds to wait for new events for on the next sync.
70
+ *
71
+ * Has no effect if the client is not syncing. Does not apply until the next sync request.
72
+ */
73
+ this.syncingTimeout = 30000;
74
+ this.requestId = 0;
75
+ this.lastJoinedRoomIds = [];
76
+ this.joinStrategy = null;
77
+ this.eventProcessors = {};
78
+ this.filterId = 0;
79
+ this.stopSyncing = false;
80
+ this.metricsInstance = new Metrics_1.Metrics();
81
+ this.unstableApisInstance = new UnstableApis_1.UnstableApis(this);
82
+ this.versionsLastFetched = 0;
83
+ /**
84
+ * Set this to true to have the client only persist the sync token after the sync
85
+ * has been processed successfully. Note that if this is true then when the sync
86
+ * loop throws an error the client will not persist a token.
87
+ */
88
+ this.persistTokenAfterSync = false;
89
+ if (this.homeserverUrl.endsWith("/")) {
90
+ this.homeserverUrl = this.homeserverUrl.substring(0, this.homeserverUrl.length - 1);
91
+ }
92
+ if (this.cryptoStore) {
93
+ if (!this.storage || this.storage instanceof MemoryStorageProvider_1.MemoryStorageProvider) {
94
+ LogService_1.LogService.warn("MatrixClientLite", "Starting an encryption-capable client with a memory store is not considered a good idea.");
95
+ }
96
+ if (!(this.cryptoStore instanceof RustSdkCryptoStorageProvider_1.RustSdkCryptoStorageProvider)) {
97
+ throw new Error("Cannot support custom encryption stores: Use a RustSdkCryptoStorageProvider");
98
+ }
99
+ this.crypto = new CryptoClient_1.CryptoClient(this);
100
+ this.on("room.event", (roomId, event) => {
101
+ // noinspection JSIgnoredPromiseFromCall
102
+ this.crypto.onRoomEvent(roomId, event);
103
+ });
104
+ this.on("room.join", (roomId) => {
105
+ // noinspection JSIgnoredPromiseFromCall
106
+ this.crypto.onRoomJoin(roomId);
107
+ });
108
+ LogService_1.LogService.debug("MatrixClientLite", "End-to-end encryption client created");
109
+ }
110
+ else {
111
+ // LogService.trace("MatrixClientLite", "Not setting up encryption");
112
+ }
113
+ if (!this.storage)
114
+ this.storage = new MemoryStorageProvider_1.MemoryStorageProvider();
115
+ this.dms = new DMs_1.DMs(this);
116
+ }
117
+ /**
118
+ * The storage provider for this client. Direct access is usually not required.
119
+ */
120
+ get storageProvider() {
121
+ return this.storage;
122
+ }
123
+ /**
124
+ * The metrics instance for this client
125
+ */
126
+ get metrics() {
127
+ return this.metricsInstance;
128
+ }
129
+ /**
130
+ * Assigns a new metrics instance, overwriting the old one.
131
+ * @param {Metrics} metrics The new metrics instance.
132
+ */
133
+ set metrics(metrics) {
134
+ if (!metrics)
135
+ throw new Error("Metrics cannot be null/undefined");
136
+ this.metricsInstance = metrics;
137
+ }
138
+ /**
139
+ * Gets the unstable API access class. This is generally not recommended to be
140
+ * used by clients.
141
+ * @return {UnstableApis} The unstable API access class.
142
+ */
143
+ get unstableApis() {
144
+ return this.unstableApisInstance;
145
+ }
146
+ /**
147
+ * Gets the admin API access class.
148
+ * @return {AdminApis} The admin API access class.
149
+ */
150
+ get adminApis() {
151
+ return new AdminApis_1.AdminApis(this);
152
+ }
153
+ /**
154
+ * Sets a user ID to impersonate as. This will assume that the access token for this client
155
+ * is for an application service, and that the userId given is within the reach of the
156
+ * application service. Setting this to null will stop future impersonation. The user ID is
157
+ * assumed to already be valid
158
+ * @param {string} userId The user ID to masquerade as, or `null` to clear masquerading.
159
+ * @param {string} deviceId Optional device ID to impersonate under the given user, if supported
160
+ * by the server. Check the whoami response after setting.
161
+ */
162
+ impersonateUserId(userId, deviceId) {
163
+ this.impersonatedUserId = userId;
164
+ this.userId = userId;
165
+ if (userId) {
166
+ this.impersonatedDeviceId = deviceId;
167
+ }
168
+ else if (deviceId) {
169
+ throw new Error("Cannot impersonate just a device: need a user ID");
170
+ }
171
+ else {
172
+ this.impersonatedDeviceId = null;
173
+ }
174
+ }
175
+ /**
176
+ * Acquires an identity server client for communicating with an identity server. Note that
177
+ * this will automatically do the login portion to establish a usable token with the identity
178
+ * server provided, but it will not automatically accept any terms of service.
179
+ *
180
+ * The identity server name provided will in future be resolved to a server address - for now
181
+ * that resolution is assumed to be prefixing the name with `https://`.
182
+ * @param {string} identityServerName The domain of the identity server to connect to.
183
+ * @returns {Promise<IdentityClient>} Resolves to a prepared identity client.
184
+ */
185
+ async getIdentityServerClient(identityServerName) {
186
+ const oidcToken = await this.getOpenIDConnectToken();
187
+ return IdentityClient_1.IdentityClient.acquire(oidcToken, `https://${identityServerName}`, this);
188
+ }
189
+ /**
190
+ * Sets the strategy to use for when joinRoom is called on this client
191
+ * @param {IJoinRoomStrategy} strategy The strategy to use, or null to use none
192
+ */
193
+ setJoinStrategy(strategy) {
194
+ this.joinStrategy = strategy;
195
+ }
196
+ /**
197
+ * Adds a preprocessor to the event pipeline. When this client encounters an event, it
198
+ * will try to run it through the preprocessors it can in the order they were added.
199
+ * @param {IPreprocessor} preprocessor the preprocessor to add
200
+ */
201
+ addPreprocessor(preprocessor) {
202
+ if (!preprocessor)
203
+ throw new Error("Preprocessor cannot be null");
204
+ const eventTypes = preprocessor.getSupportedEventTypes();
205
+ if (!eventTypes)
206
+ return; // Nothing to do
207
+ for (const eventType of eventTypes) {
208
+ if (!this.eventProcessors[eventType])
209
+ this.eventProcessors[eventType] = [];
210
+ this.eventProcessors[eventType].push(preprocessor);
211
+ }
212
+ }
213
+ async processEvent(event) {
214
+ if (!event)
215
+ return event;
216
+ if (!this.eventProcessors[event["type"]])
217
+ return event;
218
+ for (const processor of this.eventProcessors[event["type"]]) {
219
+ await processor.processEvent(event, this, EventKind_1.EventKind.RoomEvent);
220
+ }
221
+ return event;
222
+ }
223
+ /**
224
+ * Retrieves the server's supported specification versions and unstable features.
225
+ * @returns {Promise<ServerVersions>} Resolves to the server's supported versions.
226
+ */
227
+ async getServerVersions() {
228
+ if (!this.cachedVersions || (Date.now() - this.versionsLastFetched) >= VERSIONS_CACHE_MS) {
229
+ this.cachedVersions = await this.doRequest("GET", "/_matrix/client/versions");
230
+ this.versionsLastFetched = Date.now();
231
+ }
232
+ return this.cachedVersions;
233
+ }
234
+ /**
235
+ * Determines if the server supports a given unstable feature flag. Useful for determining
236
+ * if the server can support an unstable MSC.
237
+ * @param {string} feature The feature name to look for.
238
+ * @returns {Promise<boolean>} Resolves to true if the server supports the flag, false otherwise.
239
+ */
240
+ async doesServerSupportUnstableFeature(feature) {
241
+ return !!(await this.getServerVersions()).unstable_features?.[feature];
242
+ }
243
+ /**
244
+ * Determines if the server supports a given version of the specification or not.
245
+ * @param {string} version The version to look for. Eg: "v1.1"
246
+ * @returns {Promise<boolean>} Resolves to true if the server supports the version, false otherwise.
247
+ */
248
+ async doesServerSupportVersion(version) {
249
+ return (await this.getServerVersions()).versions.includes(version);
250
+ }
251
+ /**
252
+ * Determines if the server supports at least one of the given specification versions or not.
253
+ * @param {string[]} versions The versions to look for. Eg: ["v1.1"]
254
+ * @returns {Promise<boolean>} Resolves to true if the server supports any of the versions, false otherwise.
255
+ */
256
+ async doesServerSupportAnyOneVersion(versions) {
257
+ for (const version of versions) {
258
+ if (await this.doesServerSupportVersion(version)) {
259
+ return true;
260
+ }
261
+ }
262
+ return false;
263
+ }
264
+ /**
265
+ * Retrieves an OpenID Connect token from the homeserver for the current user.
266
+ * @returns {Promise<OpenIDConnectToken>} Resolves to the token.
267
+ */
268
+ async getOpenIDConnectToken() {
269
+ const userId = encodeURIComponent(await this.getUserId());
270
+ return this.doRequest("POST", "/_matrix/client/v3/user/" + userId + "/openid/request_token", null, {});
271
+ }
272
+ /**
273
+ * Retrieves content from account data.
274
+ * @param {string} eventType The type of account data to retrieve.
275
+ * @returns {Promise<any>} Resolves to the content of that account data.
276
+ */
277
+ async getAccountData(eventType) {
278
+ const userId = encodeURIComponent(await this.getUserId());
279
+ eventType = encodeURIComponent(eventType);
280
+ return this.doRequest("GET", "/_matrix/client/v3/user/" + userId + "/account_data/" + eventType);
281
+ }
282
+ /**
283
+ * Retrieves content from room account data.
284
+ * @param {string} eventType The type of room account data to retrieve.
285
+ * @param {string} roomId The room to read the account data from.
286
+ * @returns {Promise<any>} Resolves to the content of that account data.
287
+ */
288
+ async getRoomAccountData(eventType, roomId) {
289
+ const userId = encodeURIComponent(await this.getUserId());
290
+ eventType = encodeURIComponent(eventType);
291
+ roomId = encodeURIComponent(roomId);
292
+ return this.doRequest("GET", "/_matrix/client/v3/user/" + userId + "/rooms/" + roomId + "/account_data/" + eventType);
293
+ }
294
+ /**
295
+ * Retrieves content from account data. If the account data request throws an error,
296
+ * this simply returns the default provided.
297
+ * @param {string} eventType The type of account data to retrieve.
298
+ * @param {any} defaultContent The default value. Defaults to null.
299
+ * @returns {Promise<any>} Resolves to the content of that account data, or the default.
300
+ */
301
+ async getSafeAccountData(eventType, defaultContent = null) {
302
+ try {
303
+ return await this.getAccountData(eventType);
304
+ }
305
+ catch (e) {
306
+ LogService_1.LogService.warn("MatrixClient", `Error getting ${eventType} account data:`, (0, LogService_1.extractRequestError)(e));
307
+ return defaultContent;
308
+ }
309
+ }
310
+ /**
311
+ * Retrieves content from room account data. If the account data request throws an error,
312
+ * this simply returns the default provided.
313
+ * @param {string} eventType The type of room account data to retrieve.
314
+ * @param {string} roomId The room to read the account data from.
315
+ * @param {any} defaultContent The default value. Defaults to null.
316
+ * @returns {Promise<any>} Resolves to the content of that room account data, or the default.
317
+ */
318
+ async getSafeRoomAccountData(eventType, roomId, defaultContent = null) {
319
+ try {
320
+ return await this.getRoomAccountData(eventType, roomId);
321
+ }
322
+ catch (e) {
323
+ LogService_1.LogService.warn("MatrixClient", `Error getting ${eventType} room account data in ${roomId}:`, (0, LogService_1.extractRequestError)(e));
324
+ return defaultContent;
325
+ }
326
+ }
327
+ /**
328
+ * Sets account data.
329
+ * @param {string} eventType The type of account data to set
330
+ * @param {any} content The content to set
331
+ * @returns {Promise<any>} Resolves when updated
332
+ */
333
+ async setAccountData(eventType, content) {
334
+ const userId = encodeURIComponent(await this.getUserId());
335
+ eventType = encodeURIComponent(eventType);
336
+ return this.doRequest("PUT", "/_matrix/client/v3/user/" + userId + "/account_data/" + eventType, null, content);
337
+ }
338
+ /**
339
+ * Sets room account data.
340
+ * @param {string} eventType The type of room account data to set
341
+ * @param {string} roomId The room to set account data in
342
+ * @param {any} content The content to set
343
+ * @returns {Promise<any>} Resolves when updated
344
+ */
345
+ async setRoomAccountData(eventType, roomId, content) {
346
+ const userId = encodeURIComponent(await this.getUserId());
347
+ eventType = encodeURIComponent(eventType);
348
+ roomId = encodeURIComponent(roomId);
349
+ return this.doRequest("PUT", "/_matrix/client/v3/user/" + userId + "/rooms/" + roomId + "/account_data/" + eventType, null, content);
350
+ }
351
+ /**
352
+ * Gets the presence information for the current user.
353
+ * @returns {Promise<Presence>} Resolves to the presence status of the user.
354
+ */
355
+ async getPresenceStatus() {
356
+ return this.getPresenceStatusFor(await this.getUserId());
357
+ }
358
+ /**
359
+ * Gets the presence information for a given user.
360
+ * @param {string} userId The user ID to look up the presence of.
361
+ * @returns {Promise<Presence>} Resolves to the presence status of the user.
362
+ */
363
+ async getPresenceStatusFor(userId) {
364
+ return this.doRequest("GET", "/_matrix/client/v3/presence/" + encodeURIComponent(userId) + "/status").then(r => new Presence_1.Presence(r));
365
+ }
366
+ /**
367
+ * Sets the presence status for the current user.
368
+ * @param {PresenceState} presence The new presence state for the user.
369
+ * @param {string?} statusMessage Optional status message to include with the presence.
370
+ * @returns {Promise<any>} Resolves when complete.
371
+ */
372
+ async setPresenceStatus(presence, statusMessage = undefined) {
373
+ return this.doRequest("PUT", "/_matrix/client/v3/presence/" + encodeURIComponent(await this.getUserId()) + "/status", null, {
374
+ presence: presence,
375
+ status_msg: statusMessage,
376
+ });
377
+ }
378
+ /**
379
+ * Gets a published alias for the given room. These are supplied by the room admins
380
+ * and should point to the room, but may not. This is primarily intended to be used
381
+ * in the context of rendering a mention (pill) for a room.
382
+ * @param {string} roomIdOrAlias The room ID or alias to get an alias for.
383
+ * @returns {Promise<string>} Resolves to a published room alias, or falsey if none found.
384
+ */
385
+ async getPublishedAlias(roomIdOrAlias) {
386
+ try {
387
+ const roomId = await this.resolveRoom(roomIdOrAlias);
388
+ const event = await this.getRoomStateEvent(roomId, "m.room.canonical_alias", "");
389
+ if (!event)
390
+ return null;
391
+ const canonical = event['alias'];
392
+ const alt = event['alt_aliases'] || [];
393
+ return canonical || alt[0];
394
+ }
395
+ catch (e) {
396
+ // Assume none
397
+ return null;
398
+ }
399
+ }
400
+ /**
401
+ * Adds a new room alias to the room directory
402
+ * @param {string} alias The alias to add (eg: "#my-room:matrix.org")
403
+ * @param {string} roomId The room ID to add the alias to
404
+ * @returns {Promise} resolves when the alias has been added
405
+ */
406
+ createRoomAlias(alias, roomId) {
407
+ alias = encodeURIComponent(alias);
408
+ return this.doRequest("PUT", "/_matrix/client/v3/directory/room/" + alias, null, {
409
+ "room_id": roomId,
410
+ });
411
+ }
412
+ /**
413
+ * Removes a room alias from the room directory
414
+ * @param {string} alias The alias to remove
415
+ * @returns {Promise} resolves when the alias has been deleted
416
+ */
417
+ deleteRoomAlias(alias) {
418
+ alias = encodeURIComponent(alias);
419
+ return this.doRequest("DELETE", "/_matrix/client/v3/directory/room/" + alias);
420
+ }
421
+ /**
422
+ * Sets the visibility of a room in the directory.
423
+ * @param {string} roomId The room ID to manipulate the visibility of
424
+ * @param {"public" | "private"} visibility The visibility to set for the room
425
+ * @return {Promise} resolves when the visibility has been updated
426
+ */
427
+ setDirectoryVisibility(roomId, visibility) {
428
+ roomId = encodeURIComponent(roomId);
429
+ return this.doRequest("PUT", "/_matrix/client/v3/directory/list/room/" + roomId, null, {
430
+ "visibility": visibility,
431
+ });
432
+ }
433
+ /**
434
+ * Gets the visibility of a room in the directory.
435
+ * @param {string} roomId The room ID to query the visibility of
436
+ * @return {Promise<"public"|"private">} The visibility of the room
437
+ */
438
+ getDirectoryVisibility(roomId) {
439
+ roomId = encodeURIComponent(roomId);
440
+ return this.doRequest("GET", "/_matrix/client/v3/directory/list/room/" + roomId).then(response => {
441
+ return response["visibility"];
442
+ });
443
+ }
444
+ /**
445
+ * Resolves a room ID or alias to a room ID. If the given ID or alias looks like a room ID
446
+ * already, it will be returned as-is. If the room ID or alias looks like a room alias, it
447
+ * will be resolved to a room ID if possible. If the room ID or alias is neither, an error
448
+ * will be raised.
449
+ * @param {string} roomIdOrAlias the room ID or alias to resolve to a room ID
450
+ * @returns {Promise<string>} resolves to the room ID
451
+ */
452
+ async resolveRoom(roomIdOrAlias) {
453
+ if (roomIdOrAlias.startsWith("!"))
454
+ return roomIdOrAlias; // probably
455
+ if (roomIdOrAlias.startsWith("#"))
456
+ return this.lookupRoomAlias(roomIdOrAlias).then(r => r.roomId);
457
+ throw new Error("Invalid room ID or alias");
458
+ }
459
+ /**
460
+ * Does a room directory lookup for a given room alias
461
+ * @param {string} roomAlias the room alias to look up in the room directory
462
+ * @returns {Promise<RoomDirectoryLookupResponse>} resolves to the room's information
463
+ */
464
+ lookupRoomAlias(roomAlias) {
465
+ return this.doRequest("GET", "/_matrix/client/v3/directory/room/" + encodeURIComponent(roomAlias)).then(response => {
466
+ return {
467
+ roomId: response["room_id"],
468
+ residentServers: response["servers"],
469
+ };
470
+ });
471
+ }
472
+ /**
473
+ * Invites a user to a room.
474
+ * @param {string} userId the user ID to invite
475
+ * @param {string} roomId the room ID to invite the user to
476
+ * @returns {Promise<any>} resolves when completed
477
+ */
478
+ inviteUser(userId, roomId) {
479
+ return this.doRequest("POST", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/invite", null, {
480
+ user_id: userId,
481
+ });
482
+ }
483
+ /**
484
+ * Kicks a user from a room.
485
+ * @param {string} userId the user ID to kick
486
+ * @param {string} roomId the room ID to kick the user in
487
+ * @param {string?} reason optional reason for the kick
488
+ * @returns {Promise<any>} resolves when completed
489
+ */
490
+ kickUser(userId, roomId, reason = null) {
491
+ return this.doRequest("POST", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/kick", null, {
492
+ user_id: userId,
493
+ reason: reason,
494
+ });
495
+ }
496
+ /**
497
+ * Bans a user from a room.
498
+ * @param {string} userId the user ID to ban
499
+ * @param {string} roomId the room ID to set the ban in
500
+ * @param {string?} reason optional reason for the ban
501
+ * @returns {Promise<any>} resolves when completed
502
+ */
503
+ banUser(userId, roomId, reason = null) {
504
+ return this.doRequest("POST", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/ban", null, {
505
+ user_id: userId,
506
+ reason: reason,
507
+ });
508
+ }
509
+ /**
510
+ * Unbans a user in a room.
511
+ * @param {string} userId the user ID to unban
512
+ * @param {string} roomId the room ID to lift the ban in
513
+ * @returns {Promise<any>} resolves when completed
514
+ */
515
+ unbanUser(userId, roomId) {
516
+ return this.doRequest("POST", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/unban", null, {
517
+ user_id: userId,
518
+ });
519
+ }
520
+ /**
521
+ * Gets the current user ID for this client
522
+ * @returns {Promise<string>} The user ID of this client
523
+ */
524
+ async getUserId() {
525
+ if (this.userId)
526
+ return this.userId;
527
+ // getWhoAmI should populate `this.userId` for us
528
+ await this.getWhoAmI();
529
+ return this.userId;
530
+ }
531
+ /**
532
+ * Gets the user's information from the server directly.
533
+ * @returns {Promise<IWhoAmI>} The "who am I" response.
534
+ */
535
+ async getWhoAmI() {
536
+ const whoami = await this.doRequest("GET", "/_matrix/client/v3/account/whoami");
537
+ this.userId = whoami["user_id"];
538
+ return whoami;
539
+ }
540
+ /**
541
+ * Stops the client from syncing.
542
+ */
543
+ stop() {
544
+ this.stopSyncing = true;
545
+ }
546
+ /**
547
+ * Starts syncing the client with an optional filter
548
+ * @param {any} filter The filter to use, or null for none
549
+ * @returns {Promise<any>} Resolves when the client has started syncing
550
+ */
551
+ async start(filter = null) {
552
+ await this.dms.update();
553
+ this.stopSyncing = false;
554
+ if (!filter || typeof (filter) !== "object") {
555
+ LogService_1.LogService.trace("MatrixClientLite", "No filter given or invalid object - using defaults.");
556
+ filter = null;
557
+ }
558
+ LogService_1.LogService.trace("MatrixClientLite", "Populating joined rooms to avoid excessive join emits");
559
+ this.lastJoinedRoomIds = await this.getJoinedRooms();
560
+ const userId = await this.getUserId();
561
+ if (this.crypto) {
562
+ LogService_1.LogService.debug("MatrixClientLite", "Preparing end-to-end encryption");
563
+ await this.crypto.prepare(this.lastJoinedRoomIds);
564
+ LogService_1.LogService.info("MatrixClientLite", "End-to-end encryption enabled");
565
+ }
566
+ let createFilter = false;
567
+ // noinspection ES6RedundantAwait
568
+ const existingFilter = await Promise.resolve(this.storage.getFilter());
569
+ if (existingFilter) {
570
+ LogService_1.LogService.trace("MatrixClientLite", "Found existing filter. Checking consistency with given filter");
571
+ if (JSON.stringify(existingFilter.filter) === JSON.stringify(filter)) {
572
+ LogService_1.LogService.trace("MatrixClientLite", "Filters match");
573
+ this.filterId = existingFilter.id;
574
+ }
575
+ else {
576
+ createFilter = true;
577
+ }
578
+ }
579
+ else {
580
+ createFilter = true;
581
+ }
582
+ if (createFilter && filter) {
583
+ LogService_1.LogService.trace("MatrixClientLite", "Creating new filter");
584
+ await this.doRequest("POST", "/_matrix/client/v3/user/" + encodeURIComponent(userId) + "/filter", null, filter).then(async (response) => {
585
+ this.filterId = response["filter_id"];
586
+ // noinspection ES6RedundantAwait
587
+ await Promise.resolve(this.storage.setSyncToken(null));
588
+ // noinspection ES6RedundantAwait
589
+ await Promise.resolve(this.storage.setFilter({
590
+ id: this.filterId,
591
+ filter: filter,
592
+ }));
593
+ });
594
+ }
595
+ LogService_1.LogService.trace("MatrixClientLite", "Starting sync with filter ID " + this.filterId);
596
+ return this.startSyncInternal();
597
+ }
598
+ startSyncInternal() {
599
+ return this.startSync();
600
+ }
601
+ async startSync(emitFn = null) {
602
+ // noinspection ES6RedundantAwait
603
+ let token = await Promise.resolve(this.storage.getSyncToken());
604
+ const promiseWhile = async () => {
605
+ if (this.stopSyncing) {
606
+ LogService_1.LogService.info("MatrixClientLite", "Client stop requested - stopping sync");
607
+ return;
608
+ }
609
+ try {
610
+ const response = await this.doSync(token);
611
+ token = response["next_batch"];
612
+ if (!this.persistTokenAfterSync) {
613
+ await Promise.resolve(this.storage.setSyncToken(token));
614
+ }
615
+ LogService_1.LogService.debug("MatrixClientLite", "Received sync. Next token: " + token);
616
+ await this.processSync(response, emitFn);
617
+ if (this.persistTokenAfterSync) {
618
+ await Promise.resolve(this.storage.setSyncToken(token));
619
+ }
620
+ }
621
+ catch (e) {
622
+ // If we've requested to stop syncing, don't bother checking the error.
623
+ if (this.stopSyncing) {
624
+ LogService_1.LogService.info("MatrixClientLite", "Client stop requested - cancelling sync");
625
+ return;
626
+ }
627
+ LogService_1.LogService.error("MatrixClientLite", "Error handling sync " + (0, LogService_1.extractRequestError)(e));
628
+ const backoffTime = SYNC_BACKOFF_MIN_MS + Math.random() * (SYNC_BACKOFF_MAX_MS - SYNC_BACKOFF_MIN_MS);
629
+ LogService_1.LogService.info("MatrixClientLite", `Backing off for ${backoffTime}ms`);
630
+ await new Promise((r) => setTimeout(r, backoffTime));
631
+ }
632
+ return promiseWhile();
633
+ };
634
+ promiseWhile(); // start the loop
635
+ }
636
+ doSync(token) {
637
+ LogService_1.LogService.debug("MatrixClientLite", "Performing sync with token " + token);
638
+ const conf = {
639
+ full_state: false,
640
+ timeout: Math.max(0, this.syncingTimeout),
641
+ };
642
+ // synapse complains if the variables are null, so we have to have it unset instead
643
+ if (token)
644
+ conf["since"] = token;
645
+ if (this.filterId)
646
+ conf['filter'] = this.filterId;
647
+ if (this.syncingPresence)
648
+ conf['presence'] = this.syncingPresence;
649
+ // timeout is 40s if we have a token, otherwise 10min
650
+ return this.doRequest("GET", "/_matrix/client/v3/sync", conf, null, (token ? 40000 : 600000));
651
+ }
652
+ async processSync(raw, emitFn = null) {
653
+ if (!emitFn)
654
+ emitFn = (e, ...p) => Promise.resolve(this.emit(e, ...p));
655
+ if (!raw)
656
+ return; // nothing to process
657
+ const inbox = [];
658
+ if (raw['to_device']?.['events']) {
659
+ inbox.push(...raw['to_device']['events']);
660
+ }
661
+ for (const message of inbox) {
662
+ this.emit("to-device", message);
663
+ }
664
+ if (this.crypto) {
665
+ let unusedFallbacks = [];
666
+ if (raw['org.matrix.msc2732.device_unused_fallback_key_types']) {
667
+ unusedFallbacks = raw['org.matrix.msc2732.device_unused_fallback_key_types'];
668
+ }
669
+ else if (raw['device_unused_fallback_key_types']) {
670
+ unusedFallbacks = raw['device_unused_fallback_key_types'];
671
+ }
672
+ const counts = raw['device_one_time_keys_count'] ?? {};
673
+ const changed = raw['device_lists']?.['changed'] ?? [];
674
+ const left = raw['device_lists']?.['left'] ?? [];
675
+ await this.crypto.updateSyncData(inbox, counts, unusedFallbacks, changed, left);
676
+ }
677
+ // Always process device messages first to ensure there are decryption keys
678
+ if (raw['account_data'] && raw['account_data']['events']) {
679
+ for (const event of raw['account_data']['events']) {
680
+ await emitFn("account_data", event);
681
+ }
682
+ }
683
+ if (!raw['rooms'])
684
+ return; // nothing more to process
685
+ const leftRooms = raw['rooms']['leave'] || {};
686
+ const inviteRooms = raw['rooms']['invite'] || {};
687
+ const joinedRooms = raw['rooms']['join'] || {};
688
+ // Process rooms we've left first
689
+ for (const roomId in leftRooms) {
690
+ const room = leftRooms[roomId];
691
+ if (room['account_data'] && room['account_data']['events']) {
692
+ for (const event of room['account_data']['events']) {
693
+ await emitFn("room.account_data", roomId, event);
694
+ }
695
+ }
696
+ if (!room['timeline'] || !room['timeline']['events'])
697
+ continue;
698
+ let leaveEvent = null;
699
+ for (const event of room['timeline']['events']) {
700
+ if (event['type'] !== 'm.room.member')
701
+ continue;
702
+ if (event['state_key'] !== await this.getUserId())
703
+ continue;
704
+ const membership = event["content"]?.["membership"];
705
+ if (membership !== "leave" && membership !== "ban")
706
+ continue;
707
+ const oldAge = leaveEvent && leaveEvent['unsigned'] && leaveEvent['unsigned']['age'] ? leaveEvent['unsigned']['age'] : 0;
708
+ const newAge = event['unsigned'] && event['unsigned']['age'] ? event['unsigned']['age'] : 0;
709
+ if (leaveEvent && oldAge < newAge)
710
+ continue;
711
+ leaveEvent = event;
712
+ }
713
+ if (!leaveEvent) {
714
+ LogService_1.LogService.warn("MatrixClientLite", "Left room " + roomId + " without receiving an event");
715
+ continue;
716
+ }
717
+ leaveEvent = await this.processEvent(leaveEvent);
718
+ await emitFn("room.leave", roomId, leaveEvent);
719
+ this.lastJoinedRoomIds = this.lastJoinedRoomIds.filter(r => r !== roomId);
720
+ }
721
+ // Process rooms we've been invited to
722
+ for (const roomId in inviteRooms) {
723
+ const room = inviteRooms[roomId];
724
+ if (!room['invite_state'] || !room['invite_state']['events'])
725
+ continue;
726
+ let inviteEvent = null;
727
+ for (const event of room['invite_state']['events']) {
728
+ if (event['type'] !== 'm.room.member')
729
+ continue;
730
+ if (event['state_key'] !== await this.getUserId())
731
+ continue;
732
+ if (!event['content'])
733
+ continue;
734
+ if (event['content']['membership'] !== "invite")
735
+ continue;
736
+ const oldAge = inviteEvent && inviteEvent['unsigned'] && inviteEvent['unsigned']['age'] ? inviteEvent['unsigned']['age'] : 0;
737
+ const newAge = event['unsigned'] && event['unsigned']['age'] ? event['unsigned']['age'] : 0;
738
+ if (inviteEvent && oldAge < newAge)
739
+ continue;
740
+ inviteEvent = event;
741
+ }
742
+ if (!inviteEvent) {
743
+ LogService_1.LogService.warn("MatrixClientLite", "Invited to room " + roomId + " without receiving an event");
744
+ continue;
745
+ }
746
+ inviteEvent = await this.processEvent(inviteEvent);
747
+ await emitFn("room.invite", roomId, inviteEvent);
748
+ }
749
+ // Process rooms we've joined and their events
750
+ for (const roomId in joinedRooms) {
751
+ const room = joinedRooms[roomId];
752
+ if (room['account_data'] && room['account_data']['events']) {
753
+ for (const event of room['account_data']['events']) {
754
+ await emitFn("room.account_data", roomId, event);
755
+ }
756
+ }
757
+ if (!room['timeline'] || !room['timeline']['events'])
758
+ continue;
759
+ for (let event of room['timeline']['events']) {
760
+ if (event['type'] === "m.room.member" && event['state_key'] === await this.getUserId()) {
761
+ if (event['content']?.['membership'] === "join" && this.lastJoinedRoomIds.indexOf(roomId) === -1) {
762
+ await emitFn("room.join", roomId, await this.processEvent(event));
763
+ this.lastJoinedRoomIds.push(roomId);
764
+ }
765
+ }
766
+ event = await this.processEvent(event);
767
+ if (event['type'] === 'm.room.encrypted' && await this.crypto?.isRoomEncrypted(roomId)) {
768
+ await emitFn("room.encrypted_event", roomId, event);
769
+ try {
770
+ event = (await this.crypto.decryptRoomEvent(new EncryptedRoomEvent_1.EncryptedRoomEvent(event), roomId)).raw;
771
+ event = await this.processEvent(event);
772
+ await emitFn("room.decrypted_event", roomId, event);
773
+ }
774
+ catch (e) {
775
+ LogService_1.LogService.error("MatrixClientLite", `Decryption error on ${roomId} ${event['event_id']}`, e);
776
+ await emitFn("room.failed_decryption", roomId, event, e);
777
+ }
778
+ }
779
+ if (event['type'] === 'm.room.message') {
780
+ await emitFn("room.message", roomId, event);
781
+ }
782
+ if (event['type'] === 'm.room.tombstone' && event['state_key'] === '') {
783
+ await emitFn("room.archived", roomId, event);
784
+ }
785
+ if (event['type'] === 'm.room.create' && event['state_key'] === '' && event['content']
786
+ && event['content']['predecessor'] && event['content']['predecessor']['room_id']) {
787
+ await emitFn("room.upgraded", roomId, event);
788
+ }
789
+ await emitFn("room.event", roomId, event);
790
+ }
791
+ }
792
+ }
793
+ /**
794
+ * Gets an event for a room. If the event is encrypted, and the client supports encryption,
795
+ * and the room is encrypted, then this will return a decrypted event.
796
+ * @param {string} roomId the room ID to get the event in
797
+ * @param {string} eventId the event ID to look up
798
+ * @returns {Promise<any>} resolves to the found event
799
+ */
800
+ async getEvent(roomId, eventId) {
801
+ const event = await this.getRawEvent(roomId, eventId);
802
+ if (event['type'] === 'm.room.encrypted' && await this.crypto?.isRoomEncrypted(roomId)) {
803
+ return this.processEvent((await this.crypto.decryptRoomEvent(new EncryptedRoomEvent_1.EncryptedRoomEvent(event), roomId)).raw);
804
+ }
805
+ return event;
806
+ }
807
+ /**
808
+ * Gets an event for a room. Returned as a raw event.
809
+ * @param {string} roomId the room ID to get the event in
810
+ * @param {string} eventId the event ID to look up
811
+ * @returns {Promise<any>} resolves to the found event
812
+ */
813
+ getRawEvent(roomId, eventId) {
814
+ return this.doRequest("GET", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/event/" + encodeURIComponent(eventId))
815
+ .then(ev => this.processEvent(ev));
816
+ }
817
+ /**
818
+ * Gets the room state for the given room. Returned as raw events.
819
+ * @param {string} roomId the room ID to get state for
820
+ * @returns {Promise<any[]>} resolves to the room's state
821
+ */
822
+ getRoomState(roomId) {
823
+ return this.doRequest("GET", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/state")
824
+ .then(state => Promise.all(state.map(ev => this.processEvent(ev))));
825
+ }
826
+ /**
827
+ * Gets the state events for a given room of a given type under the given state key.
828
+ * @param {string} roomId the room ID
829
+ * @param {string} type the event type
830
+ * @param {String} stateKey the state key, falsey if not needed
831
+ * @returns {Promise<any|any[]>} resolves to the state event(s)
832
+ * @deprecated It is not possible to get an array of events - use getRoomStateEvent instead
833
+ */
834
+ getRoomStateEvents(roomId, type, stateKey) {
835
+ return this.getRoomStateEvent(roomId, type, stateKey);
836
+ }
837
+ /**
838
+ * Gets a state event for a given room of a given type under the given state key.
839
+ * @param {string} roomId the room ID
840
+ * @param {string} type the event type
841
+ * @param {String} stateKey the state key
842
+ * @returns {Promise<any>} resolves to the state event
843
+ */
844
+ getRoomStateEvent(roomId, type, stateKey) {
845
+ const path = "/_matrix/client/v3/rooms/"
846
+ + encodeURIComponent(roomId) + "/state/"
847
+ + encodeURIComponent(type) + "/"
848
+ + encodeURIComponent(stateKey ? stateKey : '');
849
+ return this.doRequest("GET", path)
850
+ .then(ev => this.processEvent(ev));
851
+ }
852
+ /**
853
+ * Gets the context surrounding an event.
854
+ * @param {string} roomId The room ID to get the context in.
855
+ * @param {string} eventId The event ID to get the context of.
856
+ * @param {number} limit The maximum number of events to return on either side of the event.
857
+ * @returns {Promise<EventContext>} The context of the event
858
+ */
859
+ async getEventContext(roomId, eventId, limit = 10) {
860
+ const res = await this.doRequest("GET", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/context/" + encodeURIComponent(eventId), { limit });
861
+ return {
862
+ event: new RoomEvent_1.RoomEvent(res['event']),
863
+ before: res['events_before'].map(e => new RoomEvent_1.RoomEvent(e)),
864
+ after: res['events_after'].map(e => new RoomEvent_1.RoomEvent(e)),
865
+ state: res['state'].map(e => new RoomEvent_1.StateEvent(e)),
866
+ };
867
+ }
868
+ /**
869
+ * Gets the profile for a given user
870
+ * @param {string} userId the user ID to lookup
871
+ * @returns {Promise<any>} the profile of the user
872
+ */
873
+ getUserProfile(userId) {
874
+ return this.doRequest("GET", "/_matrix/client/v3/profile/" + encodeURIComponent(userId));
875
+ }
876
+ /**
877
+ * Sets a new display name for the user.
878
+ * @param {string} displayName the new display name for the user, or null to clear
879
+ * @returns {Promise<any>} resolves when complete
880
+ */
881
+ async setDisplayName(displayName) {
882
+ const userId = encodeURIComponent(await this.getUserId());
883
+ return this.doRequest("PUT", "/_matrix/client/v3/profile/" + userId + "/displayname", null, {
884
+ displayname: displayName,
885
+ });
886
+ }
887
+ /**
888
+ * Sets a new avatar url for the user.
889
+ * @param {string} avatarUrl the new avatar URL for the user, in the form of a Matrix Content URI
890
+ * @returns {Promise<any>} resolves when complete
891
+ */
892
+ async setAvatarUrl(avatarUrl) {
893
+ const userId = encodeURIComponent(await this.getUserId());
894
+ return this.doRequest("PUT", "/_matrix/client/v3/profile/" + userId + "/avatar_url", null, {
895
+ avatar_url: avatarUrl,
896
+ });
897
+ }
898
+ /**
899
+ * Joins the given room
900
+ * @param {string} roomIdOrAlias the room ID or alias to join
901
+ * @param {string[]} viaServers the server names to try and join through
902
+ * @returns {Promise<string>} resolves to the joined room ID
903
+ */
904
+ async joinRoom(roomIdOrAlias, viaServers = []) {
905
+ const apiCall = (targetIdOrAlias) => {
906
+ targetIdOrAlias = encodeURIComponent(targetIdOrAlias);
907
+ const qs = {};
908
+ if (viaServers.length > 0)
909
+ qs['server_name'] = viaServers;
910
+ return this.doRequest("POST", "/_matrix/client/v3/join/" + targetIdOrAlias, qs, {}).then(response => {
911
+ return response['room_id'];
912
+ });
913
+ };
914
+ const userId = await this.getUserId();
915
+ if (this.joinStrategy)
916
+ return this.joinStrategy.joinRoom(roomIdOrAlias, userId, apiCall);
917
+ else
918
+ return apiCall(roomIdOrAlias);
919
+ }
920
+ /**
921
+ * Gets a list of joined room IDs
922
+ * @returns {Promise<string[]>} resolves to a list of room IDs the client participates in
923
+ */
924
+ getJoinedRooms() {
925
+ return this.doRequest("GET", "/_matrix/client/v3/joined_rooms").then(response => response['joined_rooms']);
926
+ }
927
+ /**
928
+ * Gets the joined members in a room. The client must be in the room to make this request.
929
+ * @param {string} roomId The room ID to get the joined members of.
930
+ * @returns {Promise<string>} The joined user IDs in the room
931
+ */
932
+ getJoinedRoomMembers(roomId) {
933
+ return this.doRequest("GET", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/joined_members").then(response => {
934
+ return Object.keys(response['joined']);
935
+ });
936
+ }
937
+ /**
938
+ * Gets the joined members in a room, as an object mapping userIds to profiles. The client must be in the room to make this request.
939
+ * @param {string} roomId The room ID to get the joined members of.
940
+ * @returns {Object} The joined user IDs in the room as an object mapped to a set of profiles.
941
+ */
942
+ async getJoinedRoomMembersWithProfiles(roomId) {
943
+ return (await this.doRequest("GET", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/joined_members")).joined;
944
+ }
945
+ /**
946
+ * Gets the membership events of users in the room. Defaults to all membership
947
+ * types, though this can be controlled with the membership and notMembership
948
+ * arguments. To change the point in time, use the batchToken.
949
+ * @param {string} roomId The room ID to get members in.
950
+ * @param {string} batchToken The point in time to get members at (or null for 'now')
951
+ * @param {string[]} membership The membership kinds to search for.
952
+ * @param {string[]} notMembership The membership kinds to not search for.
953
+ * @returns {Promise<MembershipEvent[]>} Resolves to the membership events of the users in the room.
954
+ * @see getRoomMembersByMembership
955
+ * @see getRoomMembersWithoutMembership
956
+ * @see getAllRoomMembers
957
+ */
958
+ getRoomMembers(roomId, batchToken = null, membership = null, notMembership = null) {
959
+ if (!membership && !notMembership) {
960
+ return this.getAllRoomMembers(roomId, batchToken);
961
+ }
962
+ return Promise.all([
963
+ ...(membership ?? []).map(m => this.getRoomMembersAt(roomId, m, null, batchToken)),
964
+ ...(notMembership ?? []).map(m => this.getRoomMembersAt(roomId, null, m, batchToken)),
965
+ ]).then(r => r.reduce((p, c) => {
966
+ p.push(...c);
967
+ return p;
968
+ }, [])).then(r => {
969
+ // Shouldn't ever happen, but dedupe just in case.
970
+ const vals = new Map();
971
+ for (const ev of r) {
972
+ if (!vals.has(ev.membershipFor)) {
973
+ vals.set(ev.membershipFor, ev);
974
+ }
975
+ }
976
+ return Array.from(vals.values());
977
+ });
978
+ }
979
+ /**
980
+ * Gets all room members in the room, optionally at a given point in time.
981
+ * @param {string} roomId The room ID to get members of.
982
+ * @param {string} atToken Optional batch token to get members at. Leave falsy for "now".
983
+ * @returns {Promise<MembershipEvent[]>} Resolves to the member events in the room.
984
+ */
985
+ getAllRoomMembers(roomId, atToken) {
986
+ return this.getRoomMembersAt(roomId, null, null, atToken);
987
+ }
988
+ /**
989
+ * Gets the membership events of users in the room which have a particular membership type. To change
990
+ * the point in time the server should return membership events at, use `atToken`.
991
+ * @param {string} roomId The room ID to get members in.
992
+ * @param {Membership} membership The membership to search for.
993
+ * @param {string?} atToken Optional batch token to use, or null for "now".
994
+ * @returns {Promise<MembershipEvent[]>} Resolves to the membership events of the users in the room.
995
+ */
996
+ getRoomMembersByMembership(roomId, membership, atToken) {
997
+ return this.getRoomMembersAt(roomId, membership, null, atToken);
998
+ }
999
+ /**
1000
+ * Gets the membership events of users in the room which lack a particular membership type. To change
1001
+ * the point in time the server should return membership events at, use `atToken`.
1002
+ * @param {string} roomId The room ID to get members in.
1003
+ * @param {Membership} notMembership The membership to NOT search for.
1004
+ * @param {string?} atToken Optional batch token to use, or null for "now".
1005
+ * @returns {Promise<MembershipEvent[]>} Resolves to the membership events of the users in the room.
1006
+ */
1007
+ async getRoomMembersWithoutMembership(roomId, notMembership, atToken) {
1008
+ return this.getRoomMembersAt(roomId, null, notMembership, atToken);
1009
+ }
1010
+ getRoomMembersAt(roomId, membership, notMembership, atToken) {
1011
+ const qs = {};
1012
+ if (atToken)
1013
+ qs["at"] = atToken;
1014
+ if (membership)
1015
+ qs["membership"] = membership;
1016
+ if (notMembership)
1017
+ qs["not_membership"] = notMembership;
1018
+ return this.doRequest("GET", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/members", qs).then(r => {
1019
+ return r['chunk'].map(e => new MembershipEvent_1.MembershipEvent(e));
1020
+ });
1021
+ }
1022
+ /**
1023
+ * Leaves the given room
1024
+ * @param {string} roomId the room ID to leave
1025
+ * @param {string=} reason Optional reason to be included as the reason for leaving the room.
1026
+ * @returns {Promise<any>} resolves when left
1027
+ */
1028
+ leaveRoom(roomId, reason) {
1029
+ return this.doRequest("POST", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/leave", null, { reason });
1030
+ }
1031
+ /**
1032
+ * Forgets the given room
1033
+ * @param {string} roomId the room ID to forget
1034
+ * @returns {Promise<{}>} Resolves when forgotten
1035
+ */
1036
+ forgetRoom(roomId) {
1037
+ return this.doRequest("POST", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/forget");
1038
+ }
1039
+ /**
1040
+ * Sends a read receipt for an event in a room
1041
+ * @param {string} roomId the room ID to send the receipt to
1042
+ * @param {string} eventId the event ID to set the receipt at
1043
+ * @returns {Promise<any>} resolves when the receipt has been sent
1044
+ */
1045
+ sendReadReceipt(roomId, eventId) {
1046
+ return this.doRequest("POST", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/receipt/m.read/" + encodeURIComponent(eventId), null, {});
1047
+ }
1048
+ /**
1049
+ * Sets the typing status of the current user in a room
1050
+ * @param {string} roomId the room ID the user is typing in
1051
+ * @param {boolean} typing is the user currently typing
1052
+ * @param {number} timeout how long should the server preserve the typing state, in milliseconds
1053
+ * @returns {Promise<any>} resolves when the typing state has been set
1054
+ */
1055
+ async setTyping(roomId, typing, timeout = 30000) {
1056
+ const userId = await this.getUserId();
1057
+ return this.doRequest("PUT", "/_matrix/client/v3/rooms/" + encodeURIComponent(roomId) + "/typing/" + encodeURIComponent(userId), null, {
1058
+ typing,
1059
+ timeout,
1060
+ });
1061
+ }
1062
+ /**
1063
+ * Replies to a given event with the given text. The event is sent with a msgtype of m.text.
1064
+ * The message will be encrypted if the client supports encryption and the room is encrypted.
1065
+ * @param {string} roomId the room ID to reply in
1066
+ * @param {any} event the event to reply to
1067
+ * @param {string} text the text to reply with
1068
+ * @param {string} html the HTML to reply with, or falsey to use the `text`
1069
+ * @returns {Promise<string>} resolves to the event ID which was sent
1070
+ */
1071
+ replyText(roomId, event, text, html = null) {
1072
+ if (!html)
1073
+ html = (0, htmlencode_1.htmlEncode)(text);
1074
+ const reply = RichReply_1.RichReply.createFor(roomId, event, text, html);
1075
+ return this.sendMessage(roomId, reply);
1076
+ }
1077
+ /**
1078
+ * Replies to a given event with the given HTML. The event is sent with a msgtype of m.text.
1079
+ * The message will be encrypted if the client supports encryption and the room is encrypted.
1080
+ * @param {string} roomId the room ID to reply in
1081
+ * @param {any} event the event to reply to
1082
+ * @param {string} html the HTML to reply with.
1083
+ * @returns {Promise<string>} resolves to the event ID which was sent
1084
+ */
1085
+ replyHtmlText(roomId, event, html) {
1086
+ const text = (0, html_to_text_1.htmlToText)(html, { wordwrap: false });
1087
+ const reply = RichReply_1.RichReply.createFor(roomId, event, text, html);
1088
+ return this.sendMessage(roomId, reply);
1089
+ }
1090
+ /**
1091
+ * Replies to a given event with the given text. The event is sent with a msgtype of m.notice.
1092
+ * The message will be encrypted if the client supports encryption and the room is encrypted.
1093
+ * @param {string} roomId the room ID to reply in
1094
+ * @param {any} event the event to reply to
1095
+ * @param {string} text the text to reply with
1096
+ * @param {string} html the HTML to reply with, or falsey to use the `text`
1097
+ * @returns {Promise<string>} resolves to the event ID which was sent
1098
+ */
1099
+ replyNotice(roomId, event, text, html = null) {
1100
+ if (!html)
1101
+ html = (0, htmlencode_1.htmlEncode)(text);
1102
+ const reply = RichReply_1.RichReply.createFor(roomId, event, text, html);
1103
+ reply['msgtype'] = 'm.notice';
1104
+ return this.sendMessage(roomId, reply);
1105
+ }
1106
+ /**
1107
+ * Replies to a given event with the given HTML. The event is sent with a msgtype of m.notice.
1108
+ * The message will be encrypted if the client supports encryption and the room is encrypted.
1109
+ * @param {string} roomId the room ID to reply in
1110
+ * @param {any} event the event to reply to
1111
+ * @param {string} html the HTML to reply with.
1112
+ * @returns {Promise<string>} resolves to the event ID which was sent
1113
+ */
1114
+ replyHtmlNotice(roomId, event, html) {
1115
+ const text = (0, html_to_text_1.htmlToText)(html, { wordwrap: false });
1116
+ const reply = RichReply_1.RichReply.createFor(roomId, event, text, html);
1117
+ reply['msgtype'] = 'm.notice';
1118
+ return this.sendMessage(roomId, reply);
1119
+ }
1120
+ /**
1121
+ * Sends a notice to the given room. The message will be encrypted if the client supports
1122
+ * encryption and the room is encrypted.
1123
+ * @param {string} roomId the room ID to send the notice to
1124
+ * @param {string} text the text to send
1125
+ * @returns {Promise<string>} resolves to the event ID that represents the message
1126
+ */
1127
+ sendNotice(roomId, text) {
1128
+ return this.sendMessage(roomId, {
1129
+ body: text,
1130
+ msgtype: "m.notice",
1131
+ });
1132
+ }
1133
+ /**
1134
+ * Sends a notice to the given room with HTML content. The message will be encrypted if the client supports
1135
+ * encryption and the room is encrypted.
1136
+ * @param {string} roomId the room ID to send the notice to
1137
+ * @param {string} html the HTML to send
1138
+ * @returns {Promise<string>} resolves to the event ID that represents the message
1139
+ */
1140
+ sendHtmlNotice(roomId, html) {
1141
+ return this.sendMessage(roomId, {
1142
+ body: (0, html_to_text_1.htmlToText)(html, { wordwrap: false }),
1143
+ msgtype: "m.notice",
1144
+ format: "org.matrix.custom.html",
1145
+ formatted_body: html,
1146
+ });
1147
+ }
1148
+ /**
1149
+ * Sends a text message to the given room. The message will be encrypted if the client supports
1150
+ * encryption and the room is encrypted.
1151
+ * @param {string} roomId the room ID to send the text to
1152
+ * @param {string} text the text to send
1153
+ * @returns {Promise<string>} resolves to the event ID that represents the message
1154
+ */
1155
+ sendText(roomId, text) {
1156
+ return this.sendMessage(roomId, {
1157
+ body: text,
1158
+ msgtype: "m.text",
1159
+ });
1160
+ }
1161
+ /**
1162
+ * Sends a text message to the given room with HTML content. The message will be encrypted if the client supports
1163
+ * encryption and the room is encrypted.
1164
+ * @param {string} roomId the room ID to send the text to
1165
+ * @param {string} html the HTML to send
1166
+ * @returns {Promise<string>} resolves to the event ID that represents the message
1167
+ */
1168
+ sendHtmlText(roomId, html) {
1169
+ return this.sendMessage(roomId, {
1170
+ body: (0, html_to_text_1.htmlToText)(html, { wordwrap: false }),
1171
+ msgtype: "m.text",
1172
+ format: "org.matrix.custom.html",
1173
+ formatted_body: html,
1174
+ });
1175
+ }
1176
+ /**
1177
+ * Sends a message to the given room. The message will be encrypted if the client supports
1178
+ * encryption and the room is encrypted.
1179
+ * @param {string} roomId the room ID to send the message to
1180
+ * @param {object} content the event content to send
1181
+ * @returns {Promise<string>} resolves to the event ID that represents the message
1182
+ */
1183
+ sendMessage(roomId, content) {
1184
+ return this.sendEvent(roomId, "m.room.message", content);
1185
+ }
1186
+ /**
1187
+ * Sends an event to the given room. This will encrypt the event before sending if the room is
1188
+ * encrypted and the client supports encryption. Use sendRawEvent() to avoid this behaviour.
1189
+ * @param {string} roomId the room ID to send the event to
1190
+ * @param {string} eventType the type of event to send
1191
+ * @param {string} content the event body to send
1192
+ * @returns {Promise<string>} resolves to the event ID that represents the event
1193
+ */
1194
+ async sendEvent(roomId, eventType, content) {
1195
+ if (await this.crypto?.isRoomEncrypted(roomId)) {
1196
+ content = await this.crypto.encryptRoomEvent(roomId, eventType, content);
1197
+ eventType = "m.room.encrypted";
1198
+ }
1199
+ return this.sendRawEvent(roomId, eventType, content);
1200
+ }
1201
+ /**
1202
+ * Sends an event to the given room.
1203
+ * @param {string} roomId the room ID to send the event to
1204
+ * @param {string} eventType the type of event to send
1205
+ * @param {string} content the event body to send
1206
+ * @returns {Promise<string>} resolves to the event ID that represents the event
1207
+ */
1208
+ async sendRawEvent(roomId, eventType, content) {
1209
+ const txnId = (new Date().getTime()) + "__inc" + (++this.requestId);
1210
+ const path = "/_matrix/client/v3/rooms/"
1211
+ + encodeURIComponent(roomId) + "/send/"
1212
+ + encodeURIComponent(eventType) + "/"
1213
+ + encodeURIComponent(txnId);
1214
+ return this.doRequest("PUT", path, null, content).then(response => {
1215
+ return response['event_id'];
1216
+ });
1217
+ }
1218
+ /**
1219
+ * Sends a state event to the given room
1220
+ * @param {string} roomId the room ID to send the event to
1221
+ * @param {string} type the event type to send
1222
+ * @param {string} stateKey the state key to send, should not be null
1223
+ * @param {string} content the event body to send
1224
+ * @returns {Promise<string>} resolves to the event ID that represents the message
1225
+ */
1226
+ sendStateEvent(roomId, type, stateKey, content) {
1227
+ const path = "/_matrix/client/v3/rooms/"
1228
+ + encodeURIComponent(roomId) + "/state/"
1229
+ + encodeURIComponent(type) + "/"
1230
+ + encodeURIComponent(stateKey);
1231
+ return this.doRequest("PUT", path, null, content).then(response => {
1232
+ return response['event_id'];
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Redact an event in a given room
1237
+ * @param {string} roomId the room ID to send the redaction to
1238
+ * @param {string} eventId the event ID to redact
1239
+ * @param {String} reason an optional reason for redacting the event
1240
+ * @returns {Promise<string>} resolves to the event ID that represents the redaction
1241
+ */
1242
+ redactEvent(roomId, eventId, reason = null) {
1243
+ const txnId = (new Date().getTime()) + "__inc" + (++this.requestId);
1244
+ const content = reason !== null ? { reason } : {};
1245
+ return this.doRequest("PUT", `/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/redact/${encodeURIComponent(eventId)}/${txnId}`, null, content).then(response => {
1246
+ return response['event_id'];
1247
+ });
1248
+ }
1249
+ /**
1250
+ * Creates a room. See the RoomCreateOptions interface
1251
+ * for more information on what to provide for `properties`. Note that creating
1252
+ * a room may cause the bot/appservice to raise a join event.
1253
+ * @param {RoomCreateOptions} properties the properties of the room.
1254
+ * @returns {Promise<string>} resolves to the room ID that represents the room
1255
+ */
1256
+ createRoom(properties = {}) {
1257
+ return this.doRequest("POST", "/_matrix/client/v3/createRoom", null, properties).then(response => {
1258
+ return response['room_id'];
1259
+ });
1260
+ }
1261
+ /**
1262
+ * Checks if a given user has a required power level required to send the given event.
1263
+ * @param {string} userId the user ID to check the power level of
1264
+ * @param {string} roomId the room ID to check the power level in
1265
+ * @param {string} eventType the event type to look for in the `events` property of the power levels
1266
+ * @param {boolean} isState true to indicate the event is intended to be a state event
1267
+ * @returns {Promise<boolean>} resolves to true if the user has the required power level, resolves to false otherwise
1268
+ */
1269
+ async userHasPowerLevelFor(userId, roomId, eventType, isState) {
1270
+ const powerLevelsEvent = await this.getRoomStateEvent(roomId, "m.room.power_levels", "");
1271
+ if (!powerLevelsEvent) {
1272
+ // This is technically supposed to be non-fatal, but it's pretty unreasonable for a room to be missing
1273
+ // power levels.
1274
+ throw new Error("No power level event found");
1275
+ }
1276
+ let requiredPower = isState ? 50 : 0;
1277
+ if (isState && Number.isFinite(powerLevelsEvent["state_default"]))
1278
+ requiredPower = powerLevelsEvent["state_default"];
1279
+ if (!isState && Number.isFinite(powerLevelsEvent["events_default"]))
1280
+ requiredPower = powerLevelsEvent["events_default"];
1281
+ if (Number.isFinite(powerLevelsEvent["events"]?.[eventType]))
1282
+ requiredPower = powerLevelsEvent["events"][eventType];
1283
+ let userPower = 0;
1284
+ if (Number.isFinite(powerLevelsEvent["users_default"]))
1285
+ userPower = powerLevelsEvent["users_default"];
1286
+ if (Number.isFinite(powerLevelsEvent["users"]?.[userId]))
1287
+ userPower = powerLevelsEvent["users"][userId];
1288
+ return userPower >= requiredPower;
1289
+ }
1290
+ /**
1291
+ * Checks if a given user has a required power level to perform the given action
1292
+ * @param {string} userId the user ID to check the power level of
1293
+ * @param {string} roomId the room ID to check the power level in
1294
+ * @param {PowerLevelAction} action the action to check power level for
1295
+ * @returns {Promise<boolean>} resolves to true if the user has the required power level, resolves to false otherwise
1296
+ */
1297
+ async userHasPowerLevelForAction(userId, roomId, action) {
1298
+ const powerLevelsEvent = await this.getRoomStateEvent(roomId, "m.room.power_levels", "");
1299
+ if (!powerLevelsEvent) {
1300
+ // This is technically supposed to be non-fatal, but it's pretty unreasonable for a room to be missing
1301
+ // power levels.
1302
+ throw new Error("No power level event found");
1303
+ }
1304
+ const defaultForActions = {
1305
+ [PowerLevelAction_1.PowerLevelAction.Ban]: 50,
1306
+ [PowerLevelAction_1.PowerLevelAction.Invite]: 50,
1307
+ [PowerLevelAction_1.PowerLevelAction.Kick]: 50,
1308
+ [PowerLevelAction_1.PowerLevelAction.RedactEvents]: 50,
1309
+ [PowerLevelAction_1.PowerLevelAction.NotifyRoom]: 50,
1310
+ };
1311
+ let requiredPower = defaultForActions[action];
1312
+ let investigate = powerLevelsEvent;
1313
+ action.split('.').forEach(k => (investigate = investigate?.[k]));
1314
+ if (Number.isFinite(investigate))
1315
+ requiredPower = investigate;
1316
+ let userPower = 0;
1317
+ if (Number.isFinite(powerLevelsEvent["users_default"]))
1318
+ userPower = powerLevelsEvent["users_default"];
1319
+ if (Number.isFinite(powerLevelsEvent["users"]?.[userId]))
1320
+ userPower = powerLevelsEvent["users"][userId];
1321
+ return userPower >= requiredPower;
1322
+ }
1323
+ /**
1324
+ * Determines the boundary conditions for this client's ability to change another user's power level
1325
+ * in a given room. This will identify the maximum possible level this client can change the user to,
1326
+ * and if that change could even be possible. If the returned object indicates that the client can
1327
+ * change the power level of the user, the client is able to set the power level to any value equal
1328
+ * to or less than the maximum value.
1329
+ * @param {string} targetUserId The user ID to compare against.
1330
+ * @param {string} roomId The room ID to compare within.
1331
+ * @returns {Promise<PowerLevelBounds>} The bounds of the client's ability to change the user's power level.
1332
+ */
1333
+ async calculatePowerLevelChangeBoundsOn(targetUserId, roomId) {
1334
+ const myUserId = await this.getUserId();
1335
+ const canChangePower = await this.userHasPowerLevelFor(myUserId, roomId, "m.room.power_levels", true);
1336
+ if (!canChangePower)
1337
+ return { canModify: false, maximumPossibleLevel: 0 };
1338
+ const powerLevelsEvent = await this.getRoomStateEvent(roomId, "m.room.power_levels", "");
1339
+ if (!powerLevelsEvent) {
1340
+ throw new Error("No power level event found");
1341
+ }
1342
+ let targetUserPower = 0;
1343
+ let myUserPower = 0;
1344
+ if (powerLevelsEvent["users"] && powerLevelsEvent["users"][targetUserId])
1345
+ targetUserPower = powerLevelsEvent["users"][targetUserId];
1346
+ if (powerLevelsEvent["users"] && powerLevelsEvent["users"][myUserId])
1347
+ myUserPower = powerLevelsEvent["users"][myUserId];
1348
+ if (myUserId === targetUserId) {
1349
+ return { canModify: true, maximumPossibleLevel: myUserPower };
1350
+ }
1351
+ if (targetUserPower >= myUserPower) {
1352
+ return { canModify: false, maximumPossibleLevel: myUserPower };
1353
+ }
1354
+ return { canModify: true, maximumPossibleLevel: myUserPower };
1355
+ }
1356
+ /**
1357
+ * Sets the power level for a given user ID in the given room. Note that this is not safe to
1358
+ * call multiple times concurrently as changes are not atomic. This will throw an error if
1359
+ * the user lacks enough permission to change the power level, or if a power level event is
1360
+ * missing from the room.
1361
+ * @param {string} userId The user ID to change
1362
+ * @param {string} roomId The room ID to change the power level in
1363
+ * @param {number} newLevel The integer power level to set the user to.
1364
+ * @returns {Promise<any>} Resolves when complete.
1365
+ */
1366
+ async setUserPowerLevel(userId, roomId, newLevel) {
1367
+ const currentLevels = await this.getRoomStateEvent(roomId, "m.room.power_levels", "");
1368
+ if (!currentLevels['users'])
1369
+ currentLevels['users'] = {};
1370
+ currentLevels['users'][userId] = newLevel;
1371
+ await this.sendStateEvent(roomId, "m.room.power_levels", "", currentLevels);
1372
+ }
1373
+ /**
1374
+ * Converts a MXC URI to an HTTP URL.
1375
+ * @param {string} mxc The MXC URI to convert
1376
+ * @returns {string} The HTTP URL for the content.
1377
+ */
1378
+ mxcToHttp(mxc) {
1379
+ if (!mxc.startsWith("mxc://"))
1380
+ throw new Error("Not a MXC URI");
1381
+ const parts = mxc.substring("mxc://".length).split('/');
1382
+ const originHomeserver = parts[0];
1383
+ const mediaId = parts.slice(1, parts.length).join('/');
1384
+ return `${this.homeserverUrl}/_matrix/media/v3/download/${encodeURIComponent(originHomeserver)}/${encodeURIComponent(mediaId)}`;
1385
+ }
1386
+ /**
1387
+ * Converts a MXC URI to an HTTP URL for downsizing the content.
1388
+ * @param {string} mxc The MXC URI to convert and downsize.
1389
+ * @param {number} width The width, as an integer, for the thumbnail.
1390
+ * @param {number} height The height, as an intenger, for the thumbnail.
1391
+ * @param {"crop"|"scale"} method Whether to crop or scale (preserve aspect ratio) the content.
1392
+ * @returns {string} The HTTP URL for the downsized content.
1393
+ */
1394
+ mxcToHttpThumbnail(mxc, width, height, method) {
1395
+ const downloadUri = this.mxcToHttp(mxc);
1396
+ return downloadUri.replace("/_matrix/media/v3/download", "/_matrix/media/v3/thumbnail")
1397
+ + `?width=${width}&height=${height}&method=${encodeURIComponent(method)}`;
1398
+ }
1399
+ /**
1400
+ * Uploads data to the homeserver's media repository. Note that this will <b>not</b> automatically encrypt
1401
+ * media as it cannot determine if the media should be encrypted.
1402
+ * @param {Buffer} data the content to upload.
1403
+ * @param {string} contentType the content type of the file. Defaults to application/octet-stream
1404
+ * @param {string} filename the name of the file. Optional.
1405
+ * @returns {Promise<string>} resolves to the MXC URI of the content
1406
+ */
1407
+ uploadContent(data, contentType = "application/octet-stream", filename = null) {
1408
+ // TODO: Make doRequest take an object for options
1409
+ return this.doRequest("POST", "/_matrix/media/v3/upload", { filename: filename }, data, 60000, false, contentType)
1410
+ .then(response => response["content_uri"]);
1411
+ }
1412
+ /**
1413
+ * Download content from the homeserver's media repository. Note that this will <b>not</b> automatically decrypt
1414
+ * media as it cannot determine if the media is encrypted.
1415
+ * @param {string} mxcUrl The MXC URI for the content.
1416
+ * @param {string} allowRemote Indicates to the server that it should not attempt to fetch the
1417
+ * media if it is deemed remote. This is to prevent routing loops where the server contacts itself.
1418
+ * Defaults to true if not provided.
1419
+ * @returns {Promise<{data: Buffer, contentType: string}>} Resolves to the downloaded content.
1420
+ */
1421
+ async downloadContent(mxcUrl, allowRemote = true) {
1422
+ if (!mxcUrl.toLowerCase().startsWith("mxc://")) {
1423
+ throw Error("'mxcUrl' does not begin with mxc://");
1424
+ }
1425
+ const urlParts = mxcUrl.substring("mxc://".length).split("/");
1426
+ const domain = encodeURIComponent(urlParts[0]);
1427
+ const mediaId = encodeURIComponent(urlParts[1].split("/")[0]);
1428
+ const path = `/_matrix/client/v1/media/download/${domain}/${mediaId}`;
1429
+ const res = await this.doRequest("GET", path, { allow_remote: allowRemote }, null, null, true, null, true);
1430
+ return {
1431
+ data: res.body,
1432
+ contentType: res.headers["content-type"],
1433
+ };
1434
+ }
1435
+ /**
1436
+ * Uploads data to the homeserver's media repository after downloading it from the
1437
+ * provided URL.
1438
+ * @param {string} url The URL to download content from.
1439
+ * @returns {Promise<string>} Resolves to the MXC URI of the content
1440
+ */
1441
+ uploadContentFromUrl(url) {
1442
+ return new Promise((resolve, reject) => {
1443
+ const requestId = ++this.requestId;
1444
+ const params = {
1445
+ uri: url,
1446
+ method: "GET",
1447
+ encoding: null,
1448
+ };
1449
+ (0, request_1.getRequestFn)()(params, (err, response, resBody) => {
1450
+ if (err) {
1451
+ LogService_1.LogService.error("MatrixClientLite", "(REQ-" + requestId + ")", (0, LogService_1.extractRequestError)(err));
1452
+ reject(err);
1453
+ }
1454
+ else {
1455
+ const contentType = response.headers['content-type'] || "application/octet-stream";
1456
+ LogService_1.LogService.trace("MatrixClientLite", "(REQ-" + requestId + " RESP-H" + response.statusCode + ")", "<data>");
1457
+ if (response.statusCode < 200 || response.statusCode >= 300) {
1458
+ LogService_1.LogService.error("MatrixClientLite", "(REQ-" + requestId + ")", "<data>");
1459
+ reject(response);
1460
+ }
1461
+ else
1462
+ resolve({ body: resBody, contentType: contentType });
1463
+ }
1464
+ });
1465
+ }).then(obj => {
1466
+ return this.uploadContent(obj.body, obj.contentType);
1467
+ });
1468
+ }
1469
+ /**
1470
+ * Determines the upgrade history for a given room as a doubly-linked list styled structure. Given
1471
+ * a room ID in the history of upgrades, the resulting `previous` array will hold any rooms which
1472
+ * are older than the given room. The resulting `newer` array will hold any rooms which are newer
1473
+ * versions of the room. Both arrays will be defined, but may be empty individually. Element zero
1474
+ * of each will always be the nearest to the given room ID and the last element will be the furthest
1475
+ * from the room. The given room will never be in either array.
1476
+ * @param {string} roomId the room ID to get the history of
1477
+ * @returns {Promise<{previous: RoomReference[], newer: RoomReference[]}>} Resolves to the room's
1478
+ * upgrade history
1479
+ */
1480
+ async getRoomUpgradeHistory(roomId) {
1481
+ const result = { previous: [], newer: [], current: null };
1482
+ const chaseCreates = async (findRoomId) => {
1483
+ try {
1484
+ const createEvent = await this.getRoomStateEvent(findRoomId, "m.room.create", "");
1485
+ if (!createEvent)
1486
+ return;
1487
+ if (findRoomId === roomId && !result.current) {
1488
+ const version = createEvent['room_version'] || '1';
1489
+ result.current = {
1490
+ roomId: roomId,
1491
+ version: version,
1492
+ refEventId: null,
1493
+ };
1494
+ }
1495
+ if (createEvent['predecessor'] && createEvent['predecessor']['room_id']) {
1496
+ const prevRoomId = createEvent['predecessor']['room_id'];
1497
+ if (prevRoomId === findRoomId)
1498
+ return; // Recursion is bad
1499
+ if (result.previous.find(r => r.roomId === prevRoomId))
1500
+ return; // Already found
1501
+ let tombstoneEventId = null;
1502
+ let prevVersion = "1";
1503
+ try {
1504
+ const roomState = await this.getRoomState(prevRoomId);
1505
+ const tombstone = roomState.find(e => e['type'] === 'm.room.tombstone' && e['state_key'] === '');
1506
+ const create = roomState.find(e => e['type'] === 'm.room.create' && e['state_key'] === '');
1507
+ if (tombstone) {
1508
+ if (!tombstone['content'])
1509
+ tombstone['content'] = {};
1510
+ const tombstoneRefRoomId = tombstone['content']['replacement_room'];
1511
+ if (tombstoneRefRoomId === findRoomId)
1512
+ tombstoneEventId = tombstone['event_id'];
1513
+ }
1514
+ if (create) {
1515
+ if (!create['content'])
1516
+ create['content'] = {};
1517
+ prevVersion = create['content']['room_version'] || "1";
1518
+ }
1519
+ }
1520
+ catch (e) {
1521
+ // state not available
1522
+ }
1523
+ result.previous.push({
1524
+ roomId: prevRoomId,
1525
+ version: prevVersion,
1526
+ refEventId: tombstoneEventId,
1527
+ });
1528
+ return chaseCreates(prevRoomId);
1529
+ }
1530
+ }
1531
+ catch (e) {
1532
+ // no create event - that's fine
1533
+ }
1534
+ };
1535
+ const chaseTombstones = async (findRoomId) => {
1536
+ try {
1537
+ const tombstoneEvent = await this.getRoomStateEvent(findRoomId, "m.room.tombstone", "");
1538
+ if (!tombstoneEvent)
1539
+ return;
1540
+ if (!tombstoneEvent['replacement_room'])
1541
+ return;
1542
+ const newRoomId = tombstoneEvent['replacement_room'];
1543
+ if (newRoomId === findRoomId)
1544
+ return; // Recursion is bad
1545
+ if (result.newer.find(r => r.roomId === newRoomId))
1546
+ return; // Already found
1547
+ let newRoomVersion = "1";
1548
+ let createEventId = null;
1549
+ try {
1550
+ const roomState = await this.getRoomState(newRoomId);
1551
+ const create = roomState.find(e => e['type'] === 'm.room.create' && e['state_key'] === '');
1552
+ if (create) {
1553
+ if (!create['content'])
1554
+ create['content'] = {};
1555
+ const predecessor = create['content']['predecessor'] || {};
1556
+ const refPrevRoomId = predecessor['room_id'];
1557
+ if (refPrevRoomId === findRoomId) {
1558
+ createEventId = create['event_id'];
1559
+ }
1560
+ newRoomVersion = create['content']['room_version'] || "1";
1561
+ }
1562
+ }
1563
+ catch (e) {
1564
+ // state not available
1565
+ }
1566
+ result.newer.push({
1567
+ roomId: newRoomId,
1568
+ version: newRoomVersion,
1569
+ refEventId: createEventId,
1570
+ });
1571
+ return await chaseTombstones(newRoomId);
1572
+ }
1573
+ catch (e) {
1574
+ // no tombstone - that's fine
1575
+ }
1576
+ };
1577
+ await chaseCreates(roomId);
1578
+ await chaseTombstones(roomId);
1579
+ return result;
1580
+ }
1581
+ /**
1582
+ * Creates a Space room.
1583
+ * @param {SpaceCreateOptions} opts The creation options.
1584
+ * @returns {Promise<Space>} Resolves to the created space.
1585
+ */
1586
+ async createSpace(opts) {
1587
+ const roomCreateOpts = {
1588
+ name: opts.name,
1589
+ topic: opts.topic || "",
1590
+ preset: opts.isPublic ? "public_chat" : "private_chat",
1591
+ room_alias_name: opts.localpart,
1592
+ initial_state: [
1593
+ {
1594
+ type: "m.room.history_visibility",
1595
+ state_key: "",
1596
+ content: {
1597
+ history_visibility: opts.isPublic ? 'world_readable' : 'shared',
1598
+ },
1599
+ },
1600
+ ],
1601
+ creation_content: {
1602
+ type: "m.space",
1603
+ },
1604
+ invite: opts.invites || [],
1605
+ power_level_content_override: {
1606
+ ban: 100,
1607
+ events_default: 50,
1608
+ invite: 50,
1609
+ kick: 100,
1610
+ notifications: {
1611
+ room: 100,
1612
+ },
1613
+ redact: 100,
1614
+ state_default: 100,
1615
+ users: {
1616
+ [await this.getUserId()]: 100,
1617
+ },
1618
+ users_default: 0,
1619
+ },
1620
+ };
1621
+ if (opts.avatarUrl) {
1622
+ roomCreateOpts.initial_state.push({
1623
+ type: 'm.room.avatar',
1624
+ state_key: "",
1625
+ content: {
1626
+ url: opts.avatarUrl,
1627
+ },
1628
+ });
1629
+ }
1630
+ const roomId = await this.createRoom(roomCreateOpts);
1631
+ return new Spaces_1.Space(roomId, this);
1632
+ }
1633
+ /**
1634
+ * Gets a Space.
1635
+ * This API does not work with unstable spaces (e.g. org.matrix.msc.1772.space)
1636
+ *
1637
+ * @throws If the room is not a space or there was an error
1638
+ * @returns {Promise<Space>} Resolves to the space.
1639
+ */
1640
+ async getSpace(roomIdOrAlias) {
1641
+ const roomId = await this.resolveRoom(roomIdOrAlias);
1642
+ const createEvent = await this.getRoomStateEvent(roomId, "m.room.create", "");
1643
+ if (createEvent["type"] !== "m.space") {
1644
+ throw new Error("Room is not a space");
1645
+ }
1646
+ return new Spaces_1.Space(roomId, this);
1647
+ }
1648
+ /**
1649
+ * Uploads One Time Keys for the current device.
1650
+ * @param {OTKs} keys The keys to upload.
1651
+ * @returns {Promise<OTKCounts>} Resolves to the current One Time Key counts when complete.
1652
+ */
1653
+ async uploadDeviceOneTimeKeys(keys) {
1654
+ return this.doRequest("POST", "/_matrix/client/v3/keys/upload", null, {
1655
+ one_time_keys: keys,
1656
+ }).then(r => r['one_time_key_counts']);
1657
+ }
1658
+ /**
1659
+ * Gets the current One Time Key counts.
1660
+ * @returns {Promise<OTKCounts>} Resolves to the One Time Key counts.
1661
+ */
1662
+ async checkOneTimeKeyCounts() {
1663
+ return this.doRequest("POST", "/_matrix/client/v3/keys/upload", null, {})
1664
+ .then(r => r['one_time_key_counts']);
1665
+ }
1666
+ /**
1667
+ * Uploads a fallback One Time Key to the server for usage. This will replace the existing fallback
1668
+ * key.
1669
+ * @param {FallbackKey} fallbackKey The fallback key.
1670
+ * @returns {Promise<OTKCounts>} Resolves to the One Time Key counts.
1671
+ */
1672
+ async uploadFallbackKey(fallbackKey) {
1673
+ const keyObj = {
1674
+ [`${Crypto_1.OTKAlgorithm.Signed}:${fallbackKey.keyId}`]: fallbackKey.key,
1675
+ };
1676
+ return this.doRequest("POST", "/_matrix/client/v3/keys/upload", null, {
1677
+ "org.matrix.msc2732.fallback_keys": keyObj,
1678
+ "fallback_keys": keyObj,
1679
+ }).then(r => r['one_time_key_counts']);
1680
+ }
1681
+ /**
1682
+ * Gets <b>unverified</b> device lists for the given users. The caller is expected to validate
1683
+ * and verify the device lists, including that the returned devices belong to the claimed users.
1684
+ *
1685
+ * Failures with federation are reported in the returned object. Users which did not fail a federation
1686
+ * lookup but have no devices will not appear in either the failures or in the returned devices.
1687
+ *
1688
+ * See https://matrix.org/docs/spec/client_server/r0.6.1#post-matrix-client-r0-keys-query for more
1689
+ * information.
1690
+ * @param {string[]} userIds The user IDs to query.
1691
+ * @param {number} federationTimeoutMs The default timeout for requesting devices over federation. Defaults to
1692
+ * 10 seconds.
1693
+ * @returns {Promise<MultiUserDeviceListResponse>} Resolves to the device list/errors for the requested user IDs.
1694
+ */
1695
+ async getUserDevices(userIds, federationTimeoutMs = 10000) {
1696
+ const req = {};
1697
+ for (const userId of userIds) {
1698
+ req[userId] = [];
1699
+ }
1700
+ return this.doRequest("POST", "/_matrix/client/v3/keys/query", {}, {
1701
+ timeout: federationTimeoutMs,
1702
+ device_keys: req,
1703
+ });
1704
+ }
1705
+ /**
1706
+ * Gets a device list for the client's own account, with metadata. The devices are not verified
1707
+ * in this response, but should be active on the account.
1708
+ * @returns {Promise<OwnUserDevice[]>} Resolves to the active devices on the account.
1709
+ */
1710
+ async getOwnDevices() {
1711
+ return this.doRequest("GET", "/_matrix/client/v3/devices").then(r => {
1712
+ return r['devices'];
1713
+ });
1714
+ }
1715
+ /**
1716
+ * Claims One Time Keys for a set of user devices, returning those keys. The caller is expected to verify
1717
+ * and validate the returned keys.
1718
+ *
1719
+ * Failures with federation are reported in the returned object.
1720
+ * @param {Record<string, Record<string, OTKAlgorithm>>} userDeviceMap The map of user IDs to device IDs to
1721
+ * OTKAlgorithm to request a claim for.
1722
+ * @param {number} federationTimeoutMs The default timeout for claiming keys over federation. Defaults to
1723
+ * 10 seconds.
1724
+ */
1725
+ async claimOneTimeKeys(userDeviceMap, federationTimeoutMs = 10000) {
1726
+ return this.doRequest("POST", "/_matrix/client/v3/keys/claim", {}, {
1727
+ timeout: federationTimeoutMs,
1728
+ one_time_keys: userDeviceMap,
1729
+ });
1730
+ }
1731
+ /**
1732
+ * Sends to-device messages to the respective users/devices.
1733
+ * @param {string} type The message type being sent.
1734
+ * @param {Record<string, Record<string, any>>} messages The messages to send, mapped as user ID to
1735
+ * device ID (or "*" to denote all of the user's devices) to message payload (content).
1736
+ * @returns {Promise<void>} Resolves when complete.
1737
+ */
1738
+ async sendToDevices(type, messages) {
1739
+ const txnId = (new Date().getTime()) + "_TDEV__inc" + (++this.requestId);
1740
+ return this.doRequest("PUT", `/_matrix/client/v3/sendToDevice/${encodeURIComponent(type)}/${encodeURIComponent(txnId)}`, null, {
1741
+ messages: messages,
1742
+ });
1743
+ }
1744
+ /**
1745
+ * Get relations for a given event.
1746
+ * @param {string} roomId The room ID to for the given event.
1747
+ * @param {string} eventId The event ID to list relations for.
1748
+ * @param {string?} relationType The type of relations (e.g. `m.room.member`) to filter for. Optional.
1749
+ * @param {string?} eventType The type of event to look for (e.g. `m.room.member`). Optional.
1750
+ * @returns {Promise<{chunk: any[]}>} Resolves to an object containing the chunk of relations
1751
+ */
1752
+ async getRelationsForEvent(roomId, eventId, relationType, eventType) {
1753
+ let url = `/_matrix/client/v1/rooms/${encodeURIComponent(roomId)}/relations/${encodeURIComponent(eventId)}`;
1754
+ if (relationType) {
1755
+ url += `/${relationType}`;
1756
+ }
1757
+ if (eventType) {
1758
+ url += `/${eventType}`;
1759
+ }
1760
+ return this.doRequest("GET", url);
1761
+ }
1762
+ /**
1763
+ * Performs a web request to the homeserver, applying appropriate authorization headers for
1764
+ * this client.
1765
+ * @param {"GET"|"POST"|"PUT"|"DELETE"} method The HTTP method to use in the request
1766
+ * @param {string} endpoint The endpoint to call. For example: "/_matrix/client/v3/account/whoami"
1767
+ * @param {any} qs The query string to send. Optional.
1768
+ * @param {any} body The request body to send. Optional. Will be converted to JSON unless the type is a Buffer.
1769
+ * @param {number} timeout The number of milliseconds to wait before timing out.
1770
+ * @param {boolean} raw If true, the raw response will be returned instead of the response body.
1771
+ * @param {string} contentType The content type to send. Only used if the `body` is a Buffer.
1772
+ * @param {string} noEncoding Set to true to disable encoding, and return a Buffer. Defaults to false
1773
+ * @returns {Promise<any>} Resolves to the response (body), rejected if a non-2xx status code was returned.
1774
+ */
1775
+ doRequest(method, endpoint, qs = null, body = null, timeout = 60000, raw = false, contentType = "application/json", noEncoding = false) {
1776
+ if (this.impersonatedUserId) {
1777
+ if (!qs)
1778
+ qs = { "user_id": this.impersonatedUserId };
1779
+ else
1780
+ qs["user_id"] = this.impersonatedUserId;
1781
+ }
1782
+ if (this.impersonatedDeviceId) {
1783
+ if (!qs)
1784
+ qs = { "org.matrix.msc3202.device_id": this.impersonatedDeviceId };
1785
+ else
1786
+ qs["org.matrix.msc3202.device_id"] = this.impersonatedDeviceId;
1787
+ }
1788
+ const headers = {};
1789
+ if (this.accessToken) {
1790
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
1791
+ }
1792
+ return (0, http_1.doHttpRequest)(this.homeserverUrl, method, endpoint, qs, body, headers, timeout, raw, contentType, noEncoding);
1793
+ }
1794
+ }
1795
+ exports.MatrixClient = MatrixClient;
1796
+ __decorate([
1797
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1798
+ __metadata("design:type", Function),
1799
+ __metadata("design:paramtypes", []),
1800
+ __metadata("design:returntype", Promise)
1801
+ ], MatrixClient.prototype, "getServerVersions", null);
1802
+ __decorate([
1803
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1804
+ __metadata("design:type", Function),
1805
+ __metadata("design:paramtypes", []),
1806
+ __metadata("design:returntype", Promise)
1807
+ ], MatrixClient.prototype, "getOpenIDConnectToken", null);
1808
+ __decorate([
1809
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1810
+ __metadata("design:type", Function),
1811
+ __metadata("design:paramtypes", [String]),
1812
+ __metadata("design:returntype", Promise)
1813
+ ], MatrixClient.prototype, "getAccountData", null);
1814
+ __decorate([
1815
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1816
+ __metadata("design:type", Function),
1817
+ __metadata("design:paramtypes", [String, String]),
1818
+ __metadata("design:returntype", Promise)
1819
+ ], MatrixClient.prototype, "getRoomAccountData", null);
1820
+ __decorate([
1821
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1822
+ __metadata("design:type", Function),
1823
+ __metadata("design:paramtypes", [String, typeof (_a = typeof T !== "undefined" && T) === "function" ? _a : Object]),
1824
+ __metadata("design:returntype", Promise)
1825
+ ], MatrixClient.prototype, "getSafeAccountData", null);
1826
+ __decorate([
1827
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1828
+ __metadata("design:type", Function),
1829
+ __metadata("design:paramtypes", [String, String, typeof (_b = typeof T !== "undefined" && T) === "function" ? _b : Object]),
1830
+ __metadata("design:returntype", Promise)
1831
+ ], MatrixClient.prototype, "getSafeRoomAccountData", null);
1832
+ __decorate([
1833
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1834
+ __metadata("design:type", Function),
1835
+ __metadata("design:paramtypes", [String, Object]),
1836
+ __metadata("design:returntype", Promise)
1837
+ ], MatrixClient.prototype, "setAccountData", null);
1838
+ __decorate([
1839
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1840
+ __metadata("design:type", Function),
1841
+ __metadata("design:paramtypes", [String, String, Object]),
1842
+ __metadata("design:returntype", Promise)
1843
+ ], MatrixClient.prototype, "setRoomAccountData", null);
1844
+ __decorate([
1845
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1846
+ __metadata("design:type", Function),
1847
+ __metadata("design:paramtypes", []),
1848
+ __metadata("design:returntype", Promise)
1849
+ ], MatrixClient.prototype, "getPresenceStatus", null);
1850
+ __decorate([
1851
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1852
+ __metadata("design:type", Function),
1853
+ __metadata("design:paramtypes", [String]),
1854
+ __metadata("design:returntype", Promise)
1855
+ ], MatrixClient.prototype, "getPresenceStatusFor", null);
1856
+ __decorate([
1857
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1858
+ __metadata("design:type", Function),
1859
+ __metadata("design:paramtypes", [String, String]),
1860
+ __metadata("design:returntype", Promise)
1861
+ ], MatrixClient.prototype, "setPresenceStatus", null);
1862
+ __decorate([
1863
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1864
+ __metadata("design:type", Function),
1865
+ __metadata("design:paramtypes", [String]),
1866
+ __metadata("design:returntype", Promise)
1867
+ ], MatrixClient.prototype, "getPublishedAlias", null);
1868
+ __decorate([
1869
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1870
+ __metadata("design:type", Function),
1871
+ __metadata("design:paramtypes", [String, String]),
1872
+ __metadata("design:returntype", Promise)
1873
+ ], MatrixClient.prototype, "createRoomAlias", null);
1874
+ __decorate([
1875
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1876
+ __metadata("design:type", Function),
1877
+ __metadata("design:paramtypes", [String]),
1878
+ __metadata("design:returntype", Promise)
1879
+ ], MatrixClient.prototype, "deleteRoomAlias", null);
1880
+ __decorate([
1881
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1882
+ __metadata("design:type", Function),
1883
+ __metadata("design:paramtypes", [String, String]),
1884
+ __metadata("design:returntype", Promise)
1885
+ ], MatrixClient.prototype, "setDirectoryVisibility", null);
1886
+ __decorate([
1887
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1888
+ __metadata("design:type", Function),
1889
+ __metadata("design:paramtypes", [String]),
1890
+ __metadata("design:returntype", Promise)
1891
+ ], MatrixClient.prototype, "getDirectoryVisibility", null);
1892
+ __decorate([
1893
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1894
+ __metadata("design:type", Function),
1895
+ __metadata("design:paramtypes", [String]),
1896
+ __metadata("design:returntype", Promise)
1897
+ ], MatrixClient.prototype, "resolveRoom", null);
1898
+ __decorate([
1899
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1900
+ __metadata("design:type", Function),
1901
+ __metadata("design:paramtypes", [String]),
1902
+ __metadata("design:returntype", Promise)
1903
+ ], MatrixClient.prototype, "lookupRoomAlias", null);
1904
+ __decorate([
1905
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1906
+ __metadata("design:type", Function),
1907
+ __metadata("design:paramtypes", [Object, Object]),
1908
+ __metadata("design:returntype", void 0)
1909
+ ], MatrixClient.prototype, "inviteUser", null);
1910
+ __decorate([
1911
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1912
+ __metadata("design:type", Function),
1913
+ __metadata("design:paramtypes", [Object, Object, Object]),
1914
+ __metadata("design:returntype", void 0)
1915
+ ], MatrixClient.prototype, "kickUser", null);
1916
+ __decorate([
1917
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1918
+ __metadata("design:type", Function),
1919
+ __metadata("design:paramtypes", [Object, Object, Object]),
1920
+ __metadata("design:returntype", void 0)
1921
+ ], MatrixClient.prototype, "banUser", null);
1922
+ __decorate([
1923
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1924
+ __metadata("design:type", Function),
1925
+ __metadata("design:paramtypes", [Object, Object]),
1926
+ __metadata("design:returntype", void 0)
1927
+ ], MatrixClient.prototype, "unbanUser", null);
1928
+ __decorate([
1929
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1930
+ __metadata("design:type", Function),
1931
+ __metadata("design:paramtypes", []),
1932
+ __metadata("design:returntype", Promise)
1933
+ ], MatrixClient.prototype, "getUserId", null);
1934
+ __decorate([
1935
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1936
+ __metadata("design:type", Function),
1937
+ __metadata("design:paramtypes", [String]),
1938
+ __metadata("design:returntype", Promise)
1939
+ ], MatrixClient.prototype, "doSync", null);
1940
+ __decorate([
1941
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1942
+ __metadata("design:type", Function),
1943
+ __metadata("design:paramtypes", [Object, Function]),
1944
+ __metadata("design:returntype", Promise)
1945
+ ], MatrixClient.prototype, "processSync", null);
1946
+ __decorate([
1947
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1948
+ __metadata("design:type", Function),
1949
+ __metadata("design:paramtypes", [String, String]),
1950
+ __metadata("design:returntype", Promise)
1951
+ ], MatrixClient.prototype, "getEvent", null);
1952
+ __decorate([
1953
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1954
+ __metadata("design:type", Function),
1955
+ __metadata("design:paramtypes", [String, String]),
1956
+ __metadata("design:returntype", Promise)
1957
+ ], MatrixClient.prototype, "getRawEvent", null);
1958
+ __decorate([
1959
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1960
+ __metadata("design:type", Function),
1961
+ __metadata("design:paramtypes", [String]),
1962
+ __metadata("design:returntype", Promise)
1963
+ ], MatrixClient.prototype, "getRoomState", null);
1964
+ __decorate([
1965
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1966
+ __metadata("design:type", Function),
1967
+ __metadata("design:paramtypes", [Object, Object, Object]),
1968
+ __metadata("design:returntype", Promise)
1969
+ ], MatrixClient.prototype, "getRoomStateEvents", null);
1970
+ __decorate([
1971
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1972
+ __metadata("design:type", Function),
1973
+ __metadata("design:paramtypes", [Object, Object, Object]),
1974
+ __metadata("design:returntype", Promise)
1975
+ ], MatrixClient.prototype, "getRoomStateEvent", null);
1976
+ __decorate([
1977
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1978
+ __metadata("design:type", Function),
1979
+ __metadata("design:paramtypes", [String, String, Object]),
1980
+ __metadata("design:returntype", Promise)
1981
+ ], MatrixClient.prototype, "getEventContext", null);
1982
+ __decorate([
1983
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1984
+ __metadata("design:type", Function),
1985
+ __metadata("design:paramtypes", [String]),
1986
+ __metadata("design:returntype", Promise)
1987
+ ], MatrixClient.prototype, "getUserProfile", null);
1988
+ __decorate([
1989
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1990
+ __metadata("design:type", Function),
1991
+ __metadata("design:paramtypes", [String]),
1992
+ __metadata("design:returntype", Promise)
1993
+ ], MatrixClient.prototype, "setDisplayName", null);
1994
+ __decorate([
1995
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
1996
+ __metadata("design:type", Function),
1997
+ __metadata("design:paramtypes", [String]),
1998
+ __metadata("design:returntype", Promise)
1999
+ ], MatrixClient.prototype, "setAvatarUrl", null);
2000
+ __decorate([
2001
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2002
+ __metadata("design:type", Function),
2003
+ __metadata("design:paramtypes", [String, Array]),
2004
+ __metadata("design:returntype", Promise)
2005
+ ], MatrixClient.prototype, "joinRoom", null);
2006
+ __decorate([
2007
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2008
+ __metadata("design:type", Function),
2009
+ __metadata("design:paramtypes", []),
2010
+ __metadata("design:returntype", Promise)
2011
+ ], MatrixClient.prototype, "getJoinedRooms", null);
2012
+ __decorate([
2013
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2014
+ __metadata("design:type", Function),
2015
+ __metadata("design:paramtypes", [String]),
2016
+ __metadata("design:returntype", Promise)
2017
+ ], MatrixClient.prototype, "getJoinedRoomMembers", null);
2018
+ __decorate([
2019
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2020
+ __metadata("design:type", Function),
2021
+ __metadata("design:paramtypes", [String]),
2022
+ __metadata("design:returntype", Promise)
2023
+ ], MatrixClient.prototype, "getJoinedRoomMembersWithProfiles", null);
2024
+ __decorate([
2025
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2026
+ __metadata("design:type", Function),
2027
+ __metadata("design:paramtypes", [String, String, Array, Array]),
2028
+ __metadata("design:returntype", Promise)
2029
+ ], MatrixClient.prototype, "getRoomMembers", null);
2030
+ __decorate([
2031
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2032
+ __metadata("design:type", Function),
2033
+ __metadata("design:paramtypes", [String, String]),
2034
+ __metadata("design:returntype", Promise)
2035
+ ], MatrixClient.prototype, "getAllRoomMembers", null);
2036
+ __decorate([
2037
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2038
+ __metadata("design:type", Function),
2039
+ __metadata("design:paramtypes", [String, String, String]),
2040
+ __metadata("design:returntype", Promise)
2041
+ ], MatrixClient.prototype, "getRoomMembersByMembership", null);
2042
+ __decorate([
2043
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2044
+ __metadata("design:type", Function),
2045
+ __metadata("design:paramtypes", [String, String, String]),
2046
+ __metadata("design:returntype", Promise)
2047
+ ], MatrixClient.prototype, "getRoomMembersWithoutMembership", null);
2048
+ __decorate([
2049
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2050
+ __metadata("design:type", Function),
2051
+ __metadata("design:paramtypes", [String, String]),
2052
+ __metadata("design:returntype", Promise)
2053
+ ], MatrixClient.prototype, "leaveRoom", null);
2054
+ __decorate([
2055
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2056
+ __metadata("design:type", Function),
2057
+ __metadata("design:paramtypes", [String]),
2058
+ __metadata("design:returntype", Promise)
2059
+ ], MatrixClient.prototype, "forgetRoom", null);
2060
+ __decorate([
2061
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2062
+ __metadata("design:type", Function),
2063
+ __metadata("design:paramtypes", [String, String]),
2064
+ __metadata("design:returntype", Promise)
2065
+ ], MatrixClient.prototype, "sendReadReceipt", null);
2066
+ __decorate([
2067
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2068
+ __metadata("design:type", Function),
2069
+ __metadata("design:paramtypes", [String, Boolean, Object]),
2070
+ __metadata("design:returntype", Promise)
2071
+ ], MatrixClient.prototype, "setTyping", null);
2072
+ __decorate([
2073
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2074
+ __metadata("design:type", Function),
2075
+ __metadata("design:paramtypes", [String, Object, String, String]),
2076
+ __metadata("design:returntype", Promise)
2077
+ ], MatrixClient.prototype, "replyText", null);
2078
+ __decorate([
2079
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2080
+ __metadata("design:type", Function),
2081
+ __metadata("design:paramtypes", [String, Object, String]),
2082
+ __metadata("design:returntype", Promise)
2083
+ ], MatrixClient.prototype, "replyHtmlText", null);
2084
+ __decorate([
2085
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2086
+ __metadata("design:type", Function),
2087
+ __metadata("design:paramtypes", [String, Object, String, String]),
2088
+ __metadata("design:returntype", Promise)
2089
+ ], MatrixClient.prototype, "replyNotice", null);
2090
+ __decorate([
2091
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2092
+ __metadata("design:type", Function),
2093
+ __metadata("design:paramtypes", [String, Object, String]),
2094
+ __metadata("design:returntype", Promise)
2095
+ ], MatrixClient.prototype, "replyHtmlNotice", null);
2096
+ __decorate([
2097
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2098
+ __metadata("design:type", Function),
2099
+ __metadata("design:paramtypes", [String, String]),
2100
+ __metadata("design:returntype", Promise)
2101
+ ], MatrixClient.prototype, "sendNotice", null);
2102
+ __decorate([
2103
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2104
+ __metadata("design:type", Function),
2105
+ __metadata("design:paramtypes", [String, String]),
2106
+ __metadata("design:returntype", Promise)
2107
+ ], MatrixClient.prototype, "sendHtmlNotice", null);
2108
+ __decorate([
2109
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2110
+ __metadata("design:type", Function),
2111
+ __metadata("design:paramtypes", [String, String]),
2112
+ __metadata("design:returntype", Promise)
2113
+ ], MatrixClient.prototype, "sendText", null);
2114
+ __decorate([
2115
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2116
+ __metadata("design:type", Function),
2117
+ __metadata("design:paramtypes", [String, String]),
2118
+ __metadata("design:returntype", Promise)
2119
+ ], MatrixClient.prototype, "sendHtmlText", null);
2120
+ __decorate([
2121
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2122
+ __metadata("design:type", Function),
2123
+ __metadata("design:paramtypes", [String, Object]),
2124
+ __metadata("design:returntype", Promise)
2125
+ ], MatrixClient.prototype, "sendMessage", null);
2126
+ __decorate([
2127
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2128
+ __metadata("design:type", Function),
2129
+ __metadata("design:paramtypes", [String, String, Object]),
2130
+ __metadata("design:returntype", Promise)
2131
+ ], MatrixClient.prototype, "sendEvent", null);
2132
+ __decorate([
2133
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2134
+ __metadata("design:type", Function),
2135
+ __metadata("design:paramtypes", [String, String, Object]),
2136
+ __metadata("design:returntype", Promise)
2137
+ ], MatrixClient.prototype, "sendRawEvent", null);
2138
+ __decorate([
2139
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2140
+ __metadata("design:type", Function),
2141
+ __metadata("design:paramtypes", [String, String, String, Object]),
2142
+ __metadata("design:returntype", Promise)
2143
+ ], MatrixClient.prototype, "sendStateEvent", null);
2144
+ __decorate([
2145
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2146
+ __metadata("design:type", Function),
2147
+ __metadata("design:paramtypes", [String, String, String]),
2148
+ __metadata("design:returntype", Promise)
2149
+ ], MatrixClient.prototype, "redactEvent", null);
2150
+ __decorate([
2151
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2152
+ __metadata("design:type", Function),
2153
+ __metadata("design:paramtypes", [Object]),
2154
+ __metadata("design:returntype", Promise)
2155
+ ], MatrixClient.prototype, "createRoom", null);
2156
+ __decorate([
2157
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2158
+ __metadata("design:type", Function),
2159
+ __metadata("design:paramtypes", [String, String, String, Boolean]),
2160
+ __metadata("design:returntype", Promise)
2161
+ ], MatrixClient.prototype, "userHasPowerLevelFor", null);
2162
+ __decorate([
2163
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2164
+ __metadata("design:type", Function),
2165
+ __metadata("design:paramtypes", [String, String, String]),
2166
+ __metadata("design:returntype", Promise)
2167
+ ], MatrixClient.prototype, "userHasPowerLevelForAction", null);
2168
+ __decorate([
2169
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2170
+ __metadata("design:type", Function),
2171
+ __metadata("design:paramtypes", [String, String]),
2172
+ __metadata("design:returntype", Promise)
2173
+ ], MatrixClient.prototype, "calculatePowerLevelChangeBoundsOn", null);
2174
+ __decorate([
2175
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2176
+ __metadata("design:type", Function),
2177
+ __metadata("design:paramtypes", [String, String, Number]),
2178
+ __metadata("design:returntype", Promise)
2179
+ ], MatrixClient.prototype, "setUserPowerLevel", null);
2180
+ __decorate([
2181
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2182
+ __metadata("design:type", Function),
2183
+ __metadata("design:paramtypes", [Buffer, Object, String]),
2184
+ __metadata("design:returntype", Promise)
2185
+ ], MatrixClient.prototype, "uploadContent", null);
2186
+ __decorate([
2187
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2188
+ __metadata("design:type", Function),
2189
+ __metadata("design:paramtypes", [String]),
2190
+ __metadata("design:returntype", Promise)
2191
+ ], MatrixClient.prototype, "uploadContentFromUrl", null);
2192
+ __decorate([
2193
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2194
+ __metadata("design:type", Function),
2195
+ __metadata("design:paramtypes", [String]),
2196
+ __metadata("design:returntype", Promise)
2197
+ ], MatrixClient.prototype, "getRoomUpgradeHistory", null);
2198
+ __decorate([
2199
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2200
+ __metadata("design:type", Function),
2201
+ __metadata("design:paramtypes", [Object]),
2202
+ __metadata("design:returntype", Promise)
2203
+ ], MatrixClient.prototype, "createSpace", null);
2204
+ __decorate([
2205
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2206
+ __metadata("design:type", Function),
2207
+ __metadata("design:paramtypes", [String]),
2208
+ __metadata("design:returntype", Promise)
2209
+ ], MatrixClient.prototype, "getSpace", null);
2210
+ __decorate([
2211
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2212
+ (0, decorators_2.requiresCrypto)(),
2213
+ __metadata("design:type", Function),
2214
+ __metadata("design:paramtypes", [Object]),
2215
+ __metadata("design:returntype", Promise)
2216
+ ], MatrixClient.prototype, "uploadDeviceOneTimeKeys", null);
2217
+ __decorate([
2218
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2219
+ (0, decorators_2.requiresCrypto)(),
2220
+ __metadata("design:type", Function),
2221
+ __metadata("design:paramtypes", []),
2222
+ __metadata("design:returntype", Promise)
2223
+ ], MatrixClient.prototype, "checkOneTimeKeyCounts", null);
2224
+ __decorate([
2225
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2226
+ (0, decorators_2.requiresCrypto)(),
2227
+ __metadata("design:type", Function),
2228
+ __metadata("design:paramtypes", [Object]),
2229
+ __metadata("design:returntype", Promise)
2230
+ ], MatrixClient.prototype, "uploadFallbackKey", null);
2231
+ __decorate([
2232
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2233
+ __metadata("design:type", Function),
2234
+ __metadata("design:paramtypes", [Array, Object]),
2235
+ __metadata("design:returntype", Promise)
2236
+ ], MatrixClient.prototype, "getUserDevices", null);
2237
+ __decorate([
2238
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2239
+ __metadata("design:type", Function),
2240
+ __metadata("design:paramtypes", []),
2241
+ __metadata("design:returntype", Promise)
2242
+ ], MatrixClient.prototype, "getOwnDevices", null);
2243
+ __decorate([
2244
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2245
+ (0, decorators_2.requiresCrypto)(),
2246
+ __metadata("design:type", Function),
2247
+ __metadata("design:paramtypes", [Object, Object]),
2248
+ __metadata("design:returntype", Promise)
2249
+ ], MatrixClient.prototype, "claimOneTimeKeys", null);
2250
+ __decorate([
2251
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2252
+ __metadata("design:type", Function),
2253
+ __metadata("design:paramtypes", [String, Object]),
2254
+ __metadata("design:returntype", Promise)
2255
+ ], MatrixClient.prototype, "sendToDevices", null);
2256
+ __decorate([
2257
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2258
+ __metadata("design:type", Function),
2259
+ __metadata("design:paramtypes", [String, String, String, String]),
2260
+ __metadata("design:returntype", Promise)
2261
+ ], MatrixClient.prototype, "getRelationsForEvent", null);
2262
+ __decorate([
2263
+ (0, decorators_1.timedMatrixClientFunctionCall)(),
2264
+ __metadata("design:type", Function),
2265
+ __metadata("design:paramtypes", [Object, Object, Object, Object, Object, Object, Object, Object]),
2266
+ __metadata("design:returntype", Promise)
2267
+ ], MatrixClient.prototype, "doRequest", null);
2268
+ //# sourceMappingURL=MatrixClient.js.map